babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023
  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 Internals;
  5050. (function (Internals) {
  5051. var _AlphaState = (function () {
  5052. function _AlphaState() {
  5053. this._isAlphaBlendDirty = false;
  5054. this._isBlendFunctionParametersDirty = false;
  5055. this._alphaBlend = false;
  5056. this._blendFunctionParameters = new Array(4);
  5057. }
  5058. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5059. get: function () {
  5060. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5061. },
  5062. enumerable: true,
  5063. configurable: true
  5064. });
  5065. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5066. get: function () {
  5067. return this._alphaBlend;
  5068. },
  5069. set: function (value) {
  5070. if (this._alphaBlend === value) {
  5071. return;
  5072. }
  5073. this._alphaBlend = value;
  5074. this._isAlphaBlendDirty = true;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5080. if (this._blendFunctionParameters[0] === value0 &&
  5081. this._blendFunctionParameters[1] === value1 &&
  5082. this._blendFunctionParameters[2] === value2 &&
  5083. this._blendFunctionParameters[3] === value3) {
  5084. return;
  5085. }
  5086. this._blendFunctionParameters[0] = value0;
  5087. this._blendFunctionParameters[1] = value1;
  5088. this._blendFunctionParameters[2] = value2;
  5089. this._blendFunctionParameters[3] = value3;
  5090. this._isBlendFunctionParametersDirty = true;
  5091. };
  5092. _AlphaState.prototype.reset = function () {
  5093. this._alphaBlend = false;
  5094. this._blendFunctionParameters[0] = null;
  5095. this._blendFunctionParameters[1] = null;
  5096. this._blendFunctionParameters[2] = null;
  5097. this._blendFunctionParameters[3] = null;
  5098. this._isAlphaBlendDirty = true;
  5099. this._isBlendFunctionParametersDirty = false;
  5100. };
  5101. _AlphaState.prototype.apply = function (gl) {
  5102. if (!this.isDirty) {
  5103. return;
  5104. }
  5105. // Alpha blend
  5106. if (this._isAlphaBlendDirty) {
  5107. if (this._alphaBlend) {
  5108. gl.enable(gl.BLEND);
  5109. }
  5110. else {
  5111. gl.disable(gl.BLEND);
  5112. }
  5113. this._isAlphaBlendDirty = false;
  5114. }
  5115. // Alpha function
  5116. if (this._isBlendFunctionParametersDirty) {
  5117. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5118. this._isBlendFunctionParametersDirty = false;
  5119. }
  5120. };
  5121. return _AlphaState;
  5122. })();
  5123. Internals._AlphaState = _AlphaState;
  5124. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5125. })(BABYLON || (BABYLON = {}));
  5126. var BABYLON;
  5127. (function (BABYLON) {
  5128. var Internals;
  5129. (function (Internals) {
  5130. var _DepthCullingState = (function () {
  5131. function _DepthCullingState() {
  5132. this._isDepthTestDirty = false;
  5133. this._isDepthMaskDirty = false;
  5134. this._isDepthFuncDirty = false;
  5135. this._isCullFaceDirty = false;
  5136. this._isCullDirty = false;
  5137. this._isZOffsetDirty = false;
  5138. }
  5139. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5140. get: function () {
  5141. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5147. get: function () {
  5148. return this._zOffset;
  5149. },
  5150. set: function (value) {
  5151. if (this._zOffset === value) {
  5152. return;
  5153. }
  5154. this._zOffset = value;
  5155. this._isZOffsetDirty = true;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5161. get: function () {
  5162. return this._cullFace;
  5163. },
  5164. set: function (value) {
  5165. if (this._cullFace === value) {
  5166. return;
  5167. }
  5168. this._cullFace = value;
  5169. this._isCullFaceDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5175. get: function () {
  5176. return this._cull;
  5177. },
  5178. set: function (value) {
  5179. if (this._cull === value) {
  5180. return;
  5181. }
  5182. this._cull = value;
  5183. this._isCullDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5189. get: function () {
  5190. return this._depthFunc;
  5191. },
  5192. set: function (value) {
  5193. if (this._depthFunc === value) {
  5194. return;
  5195. }
  5196. this._depthFunc = value;
  5197. this._isDepthFuncDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5203. get: function () {
  5204. return this._depthMask;
  5205. },
  5206. set: function (value) {
  5207. if (this._depthMask === value) {
  5208. return;
  5209. }
  5210. this._depthMask = value;
  5211. this._isDepthMaskDirty = true;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5217. get: function () {
  5218. return this._depthTest;
  5219. },
  5220. set: function (value) {
  5221. if (this._depthTest === value) {
  5222. return;
  5223. }
  5224. this._depthTest = value;
  5225. this._isDepthTestDirty = true;
  5226. },
  5227. enumerable: true,
  5228. configurable: true
  5229. });
  5230. _DepthCullingState.prototype.reset = function () {
  5231. this._depthMask = true;
  5232. this._depthTest = true;
  5233. this._depthFunc = null;
  5234. this._cull = null;
  5235. this._cullFace = null;
  5236. this._zOffset = 0;
  5237. this._isDepthTestDirty = true;
  5238. this._isDepthMaskDirty = true;
  5239. this._isDepthFuncDirty = false;
  5240. this._isCullFaceDirty = false;
  5241. this._isCullDirty = false;
  5242. this._isZOffsetDirty = false;
  5243. };
  5244. _DepthCullingState.prototype.apply = function (gl) {
  5245. if (!this.isDirty) {
  5246. return;
  5247. }
  5248. // Cull
  5249. if (this._isCullDirty) {
  5250. if (this.cull) {
  5251. gl.enable(gl.CULL_FACE);
  5252. }
  5253. else {
  5254. gl.disable(gl.CULL_FACE);
  5255. }
  5256. this._isCullDirty = false;
  5257. }
  5258. // Cull face
  5259. if (this._isCullFaceDirty) {
  5260. gl.cullFace(this.cullFace);
  5261. this._isCullFaceDirty = false;
  5262. }
  5263. // Depth mask
  5264. if (this._isDepthMaskDirty) {
  5265. gl.depthMask(this.depthMask);
  5266. this._isDepthMaskDirty = false;
  5267. }
  5268. // Depth test
  5269. if (this._isDepthTestDirty) {
  5270. if (this.depthTest) {
  5271. gl.enable(gl.DEPTH_TEST);
  5272. }
  5273. else {
  5274. gl.disable(gl.DEPTH_TEST);
  5275. }
  5276. this._isDepthTestDirty = false;
  5277. }
  5278. // Depth func
  5279. if (this._isDepthFuncDirty) {
  5280. gl.depthFunc(this.depthFunc);
  5281. this._isDepthFuncDirty = false;
  5282. }
  5283. // zOffset
  5284. if (this._isZOffsetDirty) {
  5285. if (this.zOffset) {
  5286. gl.enable(gl.POLYGON_OFFSET_FILL);
  5287. gl.polygonOffset(this.zOffset, 0);
  5288. }
  5289. else {
  5290. gl.disable(gl.POLYGON_OFFSET_FILL);
  5291. }
  5292. this._isZOffsetDirty = false;
  5293. }
  5294. };
  5295. return _DepthCullingState;
  5296. })();
  5297. Internals._DepthCullingState = _DepthCullingState;
  5298. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5299. })(BABYLON || (BABYLON = {}));
  5300. var BABYLON;
  5301. (function (BABYLON) {
  5302. var compileShader = function (gl, source, type, defines) {
  5303. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5304. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5305. gl.compileShader(shader);
  5306. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5307. throw new Error(gl.getShaderInfoLog(shader));
  5308. }
  5309. return shader;
  5310. };
  5311. var getWebGLTextureType = function (gl, type) {
  5312. var textureType = gl.UNSIGNED_BYTE;
  5313. if (type === Engine.TEXTURETYPE_FLOAT)
  5314. textureType = gl.FLOAT;
  5315. return textureType;
  5316. };
  5317. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5318. var magFilter = gl.NEAREST;
  5319. var minFilter = gl.NEAREST;
  5320. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5321. magFilter = gl.LINEAR;
  5322. if (generateMipMaps) {
  5323. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5324. }
  5325. else {
  5326. minFilter = gl.LINEAR;
  5327. }
  5328. }
  5329. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5339. magFilter = gl.NEAREST;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.NEAREST;
  5345. }
  5346. }
  5347. return {
  5348. min: minFilter,
  5349. mag: magFilter
  5350. };
  5351. };
  5352. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5354. var engine = scene.getEngine();
  5355. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5356. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5357. gl.bindTexture(gl.TEXTURE_2D, texture);
  5358. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5359. texture._baseWidth = width;
  5360. texture._baseHeight = height;
  5361. texture._width = potWidth;
  5362. texture._height = potHeight;
  5363. texture.isReady = true;
  5364. processFunction(potWidth, potHeight);
  5365. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5368. if (!noMipmap && !isCompressed) {
  5369. gl.generateMipmap(gl.TEXTURE_2D);
  5370. }
  5371. gl.bindTexture(gl.TEXTURE_2D, null);
  5372. engine.resetTextureCache();
  5373. scene._removePendingData(texture);
  5374. if (onLoad) {
  5375. onLoad();
  5376. }
  5377. };
  5378. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5379. var img;
  5380. var onload = function () {
  5381. loadedImages[index] = img;
  5382. loadedImages._internalCount++;
  5383. scene._removePendingData(img);
  5384. if (loadedImages._internalCount === 6) {
  5385. onfinish(loadedImages);
  5386. }
  5387. };
  5388. var onerror = function () {
  5389. scene._removePendingData(img);
  5390. };
  5391. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5392. scene._addPendingData(img);
  5393. };
  5394. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5395. var loadedImages = [];
  5396. loadedImages._internalCount = 0;
  5397. for (var index = 0; index < 6; index++) {
  5398. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5399. }
  5400. };
  5401. var EngineCapabilities = (function () {
  5402. function EngineCapabilities() {
  5403. }
  5404. return EngineCapabilities;
  5405. })();
  5406. BABYLON.EngineCapabilities = EngineCapabilities;
  5407. /**
  5408. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5409. */
  5410. var Engine = (function () {
  5411. /**
  5412. * @constructor
  5413. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5414. * @param {boolean} [antialias] - enable antialias
  5415. * @param options - further options to be sent to the getContext function
  5416. */
  5417. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5418. var _this = this;
  5419. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5420. // Public members
  5421. this.isFullscreen = false;
  5422. this.isPointerLock = false;
  5423. this.cullBackFaces = true;
  5424. this.renderEvenInBackground = true;
  5425. // To enable/disable IDB support and avoid XHR on .manifest
  5426. this.enableOfflineSupport = true;
  5427. this.scenes = new Array();
  5428. this._windowIsBackground = false;
  5429. this._webGLVersion = "1.0";
  5430. this._drawCalls = 0;
  5431. this._renderingQueueLaunched = false;
  5432. this._activeRenderLoops = [];
  5433. // FPS
  5434. this.fpsRange = 60;
  5435. this.previousFramesDuration = [];
  5436. this.fps = 60;
  5437. this.deltaTime = 0;
  5438. // States
  5439. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5440. this._alphaState = new BABYLON.Internals._AlphaState();
  5441. this._alphaMode = Engine.ALPHA_DISABLE;
  5442. // Cache
  5443. this._loadedTexturesCache = new Array();
  5444. this._maxTextureChannels = 16;
  5445. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5446. this._compiledEffects = {};
  5447. this._uintIndicesCurrentlySet = false;
  5448. this._renderingCanvas = canvas;
  5449. options = options || {};
  5450. options.antialias = antialias;
  5451. if (options.preserveDrawingBuffer === undefined) {
  5452. options.preserveDrawingBuffer = false;
  5453. }
  5454. // GL
  5455. //try {
  5456. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5457. // if (this._gl) {
  5458. // this._webGLVersion = "2.0";
  5459. // }
  5460. //} catch (e) {
  5461. // // Do nothing
  5462. //}
  5463. if (!this._gl) {
  5464. try {
  5465. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5466. }
  5467. catch (e) {
  5468. throw new Error("WebGL not supported");
  5469. }
  5470. }
  5471. if (!this._gl) {
  5472. throw new Error("WebGL not supported");
  5473. }
  5474. this._onBlur = function () {
  5475. _this._windowIsBackground = true;
  5476. };
  5477. this._onFocus = function () {
  5478. _this._windowIsBackground = false;
  5479. };
  5480. window.addEventListener("blur", this._onBlur);
  5481. window.addEventListener("focus", this._onFocus);
  5482. // Viewport
  5483. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5484. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5485. this.resize();
  5486. // Caps
  5487. this._caps = new EngineCapabilities();
  5488. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5489. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5490. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5491. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5492. // Infos
  5493. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5494. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5495. if (rendererInfo != null) {
  5496. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5497. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5498. }
  5499. if (!this._glVendor) {
  5500. this._glVendor = "Unknown vendor";
  5501. }
  5502. if (!this._glRenderer) {
  5503. this._glRenderer = "Unknown renderer";
  5504. }
  5505. // Extensions
  5506. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5507. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5508. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5509. 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');
  5510. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5511. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5512. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5513. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5514. this._caps.highPrecisionShaderSupported = true;
  5515. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5516. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5517. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5518. if (this._gl.getShaderPrecisionFormat) {
  5519. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5520. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5521. }
  5522. // Depth buffer
  5523. this.setDepthBuffer(true);
  5524. this.setDepthFunctionToLessOrEqual();
  5525. this.setDepthWrite(true);
  5526. // Fullscreen
  5527. this._onFullscreenChange = function () {
  5528. if (document.fullscreen !== undefined) {
  5529. _this.isFullscreen = document.fullscreen;
  5530. }
  5531. else if (document.mozFullScreen !== undefined) {
  5532. _this.isFullscreen = document.mozFullScreen;
  5533. }
  5534. else if (document.webkitIsFullScreen !== undefined) {
  5535. _this.isFullscreen = document.webkitIsFullScreen;
  5536. }
  5537. else if (document.msIsFullScreen !== undefined) {
  5538. _this.isFullscreen = document.msIsFullScreen;
  5539. }
  5540. // Pointer lock
  5541. if (_this.isFullscreen && _this._pointerLockRequested) {
  5542. canvas.requestPointerLock = canvas.requestPointerLock ||
  5543. canvas.msRequestPointerLock ||
  5544. canvas.mozRequestPointerLock ||
  5545. canvas.webkitRequestPointerLock;
  5546. if (canvas.requestPointerLock) {
  5547. canvas.requestPointerLock();
  5548. }
  5549. }
  5550. };
  5551. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5552. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5553. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5554. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5555. // Pointer lock
  5556. this._onPointerLockChange = function () {
  5557. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5558. document.webkitPointerLockElement === canvas ||
  5559. document.msPointerLockElement === canvas ||
  5560. document.pointerLockElement === canvas);
  5561. };
  5562. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5563. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5564. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5565. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5566. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5567. Engine.audioEngine = new BABYLON.AudioEngine();
  5568. }
  5569. //default loading screen
  5570. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5571. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5572. }
  5573. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5574. get: function () {
  5575. return Engine._ALPHA_DISABLE;
  5576. },
  5577. enumerable: true,
  5578. configurable: true
  5579. });
  5580. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5581. get: function () {
  5582. return Engine._ALPHA_ONEONE;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(Engine, "ALPHA_ADD", {
  5588. get: function () {
  5589. return Engine._ALPHA_ADD;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5595. get: function () {
  5596. return Engine._ALPHA_COMBINE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5602. get: function () {
  5603. return Engine._ALPHA_SUBTRACT;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5609. get: function () {
  5610. return Engine._ALPHA_MULTIPLY;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5616. get: function () {
  5617. return Engine._ALPHA_MAXIMIZED;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5623. get: function () {
  5624. return Engine._DELAYLOADSTATE_NONE;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5630. get: function () {
  5631. return Engine._DELAYLOADSTATE_LOADED;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5637. get: function () {
  5638. return Engine._DELAYLOADSTATE_LOADING;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5644. get: function () {
  5645. return Engine._DELAYLOADSTATE_NOTLOADED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5651. get: function () {
  5652. return Engine._TEXTUREFORMAT_ALPHA;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5658. get: function () {
  5659. return Engine._TEXTUREFORMAT_LUMINANCE;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5665. get: function () {
  5666. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5672. get: function () {
  5673. return Engine._TEXTUREFORMAT_RGB;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_RGBA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5686. get: function () {
  5687. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5693. get: function () {
  5694. return Engine._TEXTURETYPE_FLOAT;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "Version", {
  5700. get: function () {
  5701. return "2.4.0-alpha";
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5707. get: function () {
  5708. return this._webGLVersion;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Engine.prototype._prepareWorkingCanvas = function () {
  5714. if (this._workingCanvas) {
  5715. return;
  5716. }
  5717. this._workingCanvas = document.createElement("canvas");
  5718. this._workingContext = this._workingCanvas.getContext("2d");
  5719. };
  5720. Engine.prototype.resetTextureCache = function () {
  5721. for (var index = 0; index < this._maxTextureChannels; index++) {
  5722. this._activeTexturesCache[index] = null;
  5723. }
  5724. };
  5725. Engine.prototype.getGlInfo = function () {
  5726. return {
  5727. vendor: this._glVendor,
  5728. renderer: this._glRenderer,
  5729. version: this._glVersion
  5730. };
  5731. };
  5732. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5733. if (useScreen === void 0) { useScreen = false; }
  5734. var viewport = camera.viewport;
  5735. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5736. };
  5737. Engine.prototype.getRenderWidth = function (useScreen) {
  5738. if (useScreen === void 0) { useScreen = false; }
  5739. if (!useScreen && this._currentRenderTarget) {
  5740. return this._currentRenderTarget._width;
  5741. }
  5742. return this._renderingCanvas.width;
  5743. };
  5744. Engine.prototype.getRenderHeight = function (useScreen) {
  5745. if (useScreen === void 0) { useScreen = false; }
  5746. if (!useScreen && this._currentRenderTarget) {
  5747. return this._currentRenderTarget._height;
  5748. }
  5749. return this._renderingCanvas.height;
  5750. };
  5751. Engine.prototype.getRenderingCanvas = function () {
  5752. return this._renderingCanvas;
  5753. };
  5754. Engine.prototype.getRenderingCanvasClientRect = function () {
  5755. return this._renderingCanvas.getBoundingClientRect();
  5756. };
  5757. Engine.prototype.setHardwareScalingLevel = function (level) {
  5758. this._hardwareScalingLevel = level;
  5759. this.resize();
  5760. };
  5761. Engine.prototype.getHardwareScalingLevel = function () {
  5762. return this._hardwareScalingLevel;
  5763. };
  5764. Engine.prototype.getLoadedTexturesCache = function () {
  5765. return this._loadedTexturesCache;
  5766. };
  5767. Engine.prototype.getCaps = function () {
  5768. return this._caps;
  5769. };
  5770. Object.defineProperty(Engine.prototype, "drawCalls", {
  5771. get: function () {
  5772. return this._drawCalls;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. // Methods
  5778. Engine.prototype.resetDrawCalls = function () {
  5779. this._drawCalls = 0;
  5780. };
  5781. Engine.prototype.setDepthFunctionToGreater = function () {
  5782. this._depthCullingState.depthFunc = this._gl.GREATER;
  5783. };
  5784. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5785. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5786. };
  5787. Engine.prototype.setDepthFunctionToLess = function () {
  5788. this._depthCullingState.depthFunc = this._gl.LESS;
  5789. };
  5790. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5791. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5792. };
  5793. /**
  5794. * stop executing a render loop function and remove it from the execution array
  5795. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5796. */
  5797. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5798. if (!renderFunction) {
  5799. this._activeRenderLoops = [];
  5800. return;
  5801. }
  5802. var index = this._activeRenderLoops.indexOf(renderFunction);
  5803. if (index >= 0) {
  5804. this._activeRenderLoops.splice(index, 1);
  5805. }
  5806. };
  5807. Engine.prototype._renderLoop = function () {
  5808. var shouldRender = true;
  5809. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5810. shouldRender = false;
  5811. }
  5812. if (shouldRender) {
  5813. // Start new frame
  5814. this.beginFrame();
  5815. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5816. var renderFunction = this._activeRenderLoops[index];
  5817. renderFunction();
  5818. }
  5819. // Present
  5820. this.endFrame();
  5821. }
  5822. if (this._activeRenderLoops.length > 0) {
  5823. // Register new frame
  5824. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5825. }
  5826. else {
  5827. this._renderingQueueLaunched = false;
  5828. }
  5829. };
  5830. /**
  5831. * Register and execute a render loop. The engine can have more than one render function.
  5832. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5833. * @example
  5834. * engine.runRenderLoop(function () {
  5835. * scene.render()
  5836. * })
  5837. */
  5838. Engine.prototype.runRenderLoop = function (renderFunction) {
  5839. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5840. return;
  5841. }
  5842. this._activeRenderLoops.push(renderFunction);
  5843. if (!this._renderingQueueLaunched) {
  5844. this._renderingQueueLaunched = true;
  5845. this._bindedRenderFunction = this._renderLoop.bind(this);
  5846. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5847. }
  5848. };
  5849. /**
  5850. * Toggle full screen mode.
  5851. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5852. */
  5853. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5854. if (this.isFullscreen) {
  5855. BABYLON.Tools.ExitFullscreen();
  5856. }
  5857. else {
  5858. this._pointerLockRequested = requestPointerLock;
  5859. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5860. }
  5861. };
  5862. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5863. this.applyStates();
  5864. if (backBuffer) {
  5865. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5866. }
  5867. if (depthStencil && this._depthCullingState.depthMask) {
  5868. this._gl.clearDepth(1.0);
  5869. }
  5870. var mode = 0;
  5871. if (backBuffer) {
  5872. mode |= this._gl.COLOR_BUFFER_BIT;
  5873. }
  5874. if (depthStencil && this._depthCullingState.depthMask) {
  5875. mode |= this._gl.DEPTH_BUFFER_BIT;
  5876. }
  5877. this._gl.clear(mode);
  5878. };
  5879. /**
  5880. * Set the WebGL's viewport
  5881. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5882. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5883. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5884. */
  5885. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5886. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5887. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5888. var x = viewport.x || 0;
  5889. var y = viewport.y || 0;
  5890. this._cachedViewport = viewport;
  5891. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5892. };
  5893. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5894. this._cachedViewport = null;
  5895. this._gl.viewport(x, y, width, height);
  5896. };
  5897. Engine.prototype.beginFrame = function () {
  5898. this._measureFps();
  5899. };
  5900. Engine.prototype.endFrame = function () {
  5901. //this.flushFramebuffer();
  5902. };
  5903. /**
  5904. * resize the view according to the canvas' size.
  5905. * @example
  5906. * window.addEventListener("resize", function () {
  5907. * engine.resize();
  5908. * });
  5909. */
  5910. Engine.prototype.resize = function () {
  5911. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5912. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5913. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5914. for (var index = 0; index < this.scenes.length; index++) {
  5915. var scene = this.scenes[index];
  5916. if (scene.debugLayer.isVisible()) {
  5917. scene.debugLayer._syncPositions();
  5918. }
  5919. }
  5920. };
  5921. /**
  5922. * force a specific size of the canvas
  5923. * @param {number} width - the new canvas' width
  5924. * @param {number} height - the new canvas' height
  5925. */
  5926. Engine.prototype.setSize = function (width, height) {
  5927. this._renderingCanvas.width = width;
  5928. this._renderingCanvas.height = height;
  5929. for (var index = 0; index < this.scenes.length; index++) {
  5930. var scene = this.scenes[index];
  5931. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5932. var cam = scene.cameras[camIndex];
  5933. cam._currentRenderId = 0;
  5934. }
  5935. }
  5936. };
  5937. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5938. this._currentRenderTarget = texture;
  5939. var gl = this._gl;
  5940. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5941. if (texture.isCube) {
  5942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5943. }
  5944. else {
  5945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5946. }
  5947. this._gl.viewport(0, 0, texture._width, texture._height);
  5948. this.wipeCaches();
  5949. };
  5950. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5951. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5952. this._currentRenderTarget = null;
  5953. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5954. var gl = this._gl;
  5955. gl.bindTexture(gl.TEXTURE_2D, texture);
  5956. gl.generateMipmap(gl.TEXTURE_2D);
  5957. gl.bindTexture(gl.TEXTURE_2D, null);
  5958. }
  5959. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5960. };
  5961. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5962. if (texture.generateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5966. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5967. }
  5968. };
  5969. Engine.prototype.flushFramebuffer = function () {
  5970. this._gl.flush();
  5971. };
  5972. Engine.prototype.restoreDefaultFramebuffer = function () {
  5973. this._currentRenderTarget = null;
  5974. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5975. this.setViewport(this._cachedViewport);
  5976. this.wipeCaches();
  5977. };
  5978. // VBOs
  5979. Engine.prototype._resetVertexBufferBinding = function () {
  5980. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5981. this._cachedVertexBuffers = null;
  5982. };
  5983. Engine.prototype.createVertexBuffer = function (vertices) {
  5984. var vbo = this._gl.createBuffer();
  5985. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5986. if (vertices instanceof Float32Array) {
  5987. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5988. }
  5989. else {
  5990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5991. }
  5992. this._resetVertexBufferBinding();
  5993. vbo.references = 1;
  5994. return vbo;
  5995. };
  5996. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5997. var vbo = this._gl.createBuffer();
  5998. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5999. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6000. this._resetVertexBufferBinding();
  6001. vbo.references = 1;
  6002. return vbo;
  6003. };
  6004. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6005. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6006. if (offset === undefined) {
  6007. offset = 0;
  6008. }
  6009. if (vertices instanceof Float32Array) {
  6010. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6011. }
  6012. else {
  6013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6014. }
  6015. this._resetVertexBufferBinding();
  6016. };
  6017. Engine.prototype._resetIndexBufferBinding = function () {
  6018. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6019. this._cachedIndexBuffer = null;
  6020. };
  6021. Engine.prototype.createIndexBuffer = function (indices) {
  6022. var vbo = this._gl.createBuffer();
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6024. // Check for 32 bits indices
  6025. var arrayBuffer;
  6026. var need32Bits = false;
  6027. if (this._caps.uintIndices) {
  6028. for (var index = 0; index < indices.length; index++) {
  6029. if (indices[index] > 65535) {
  6030. need32Bits = true;
  6031. break;
  6032. }
  6033. }
  6034. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6035. }
  6036. else {
  6037. arrayBuffer = new Uint16Array(indices);
  6038. }
  6039. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6040. this._resetIndexBufferBinding();
  6041. vbo.references = 1;
  6042. vbo.is32Bits = need32Bits;
  6043. return vbo;
  6044. };
  6045. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6046. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6047. this._cachedVertexBuffers = vertexBuffer;
  6048. this._cachedEffectForVertexBuffers = effect;
  6049. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6050. var offset = 0;
  6051. for (var index = 0; index < vertexDeclaration.length; index++) {
  6052. var order = effect.getAttributeLocation(index);
  6053. if (order >= 0) {
  6054. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6055. }
  6056. offset += vertexDeclaration[index] * 4;
  6057. }
  6058. }
  6059. if (this._cachedIndexBuffer !== indexBuffer) {
  6060. this._cachedIndexBuffer = indexBuffer;
  6061. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6062. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6063. }
  6064. };
  6065. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6066. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6067. this._cachedVertexBuffers = vertexBuffers;
  6068. this._cachedEffectForVertexBuffers = effect;
  6069. var attributes = effect.getAttributesNames();
  6070. for (var index = 0; index < attributes.length; index++) {
  6071. var order = effect.getAttributeLocation(index);
  6072. if (order >= 0) {
  6073. var vertexBuffer = vertexBuffers[attributes[index]];
  6074. if (!vertexBuffer) {
  6075. continue;
  6076. }
  6077. var stride = vertexBuffer.getStrideSize();
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6079. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6080. }
  6081. }
  6082. }
  6083. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6084. this._cachedIndexBuffer = indexBuffer;
  6085. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6086. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6087. }
  6088. };
  6089. Engine.prototype._releaseBuffer = function (buffer) {
  6090. buffer.references--;
  6091. if (buffer.references === 0) {
  6092. this._gl.deleteBuffer(buffer);
  6093. return true;
  6094. }
  6095. return false;
  6096. };
  6097. Engine.prototype.createInstancesBuffer = function (capacity) {
  6098. var buffer = this._gl.createBuffer();
  6099. buffer.capacity = capacity;
  6100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6101. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6102. return buffer;
  6103. };
  6104. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6105. this._gl.deleteBuffer(buffer);
  6106. };
  6107. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6108. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6110. for (var index = 0; index < 4; index++) {
  6111. var offsetLocation = offsetLocations[index];
  6112. this._gl.enableVertexAttribArray(offsetLocation);
  6113. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6114. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6115. }
  6116. };
  6117. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6118. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6119. for (var index = 0; index < 4; index++) {
  6120. var offsetLocation = offsetLocations[index];
  6121. this._gl.disableVertexAttribArray(offsetLocation);
  6122. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6123. }
  6124. };
  6125. Engine.prototype.applyStates = function () {
  6126. this._depthCullingState.apply(this._gl);
  6127. this._alphaState.apply(this._gl);
  6128. };
  6129. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6130. // Apply states
  6131. this.applyStates();
  6132. this._drawCalls++;
  6133. // Render
  6134. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6135. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6136. if (instancesCount) {
  6137. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6138. return;
  6139. }
  6140. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6141. };
  6142. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6143. // Apply states
  6144. this.applyStates();
  6145. this._drawCalls++;
  6146. if (instancesCount) {
  6147. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6148. return;
  6149. }
  6150. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6151. };
  6152. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6153. // Apply states
  6154. this.applyStates();
  6155. this._drawCalls++;
  6156. if (instancesCount) {
  6157. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6158. return;
  6159. }
  6160. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6161. };
  6162. // Shaders
  6163. Engine.prototype._releaseEffect = function (effect) {
  6164. if (this._compiledEffects[effect._key]) {
  6165. delete this._compiledEffects[effect._key];
  6166. if (effect.getProgram()) {
  6167. this._gl.deleteProgram(effect.getProgram());
  6168. }
  6169. }
  6170. };
  6171. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6172. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6173. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6174. var name = vertex + "+" + fragment + "@" + defines;
  6175. if (this._compiledEffects[name]) {
  6176. return this._compiledEffects[name];
  6177. }
  6178. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6179. effect._key = name;
  6180. this._compiledEffects[name] = effect;
  6181. return effect;
  6182. };
  6183. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6184. if (uniformsNames === void 0) { uniformsNames = []; }
  6185. if (samplers === void 0) { samplers = []; }
  6186. if (defines === void 0) { defines = ""; }
  6187. return this.createEffect({
  6188. vertex: "particles",
  6189. fragmentElement: fragmentName
  6190. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6191. };
  6192. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6193. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6194. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6195. var shaderProgram = this._gl.createProgram();
  6196. this._gl.attachShader(shaderProgram, vertexShader);
  6197. this._gl.attachShader(shaderProgram, fragmentShader);
  6198. this._gl.linkProgram(shaderProgram);
  6199. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6200. if (!linked) {
  6201. var error = this._gl.getProgramInfoLog(shaderProgram);
  6202. if (error) {
  6203. throw new Error(error);
  6204. }
  6205. }
  6206. this._gl.deleteShader(vertexShader);
  6207. this._gl.deleteShader(fragmentShader);
  6208. return shaderProgram;
  6209. };
  6210. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6211. var results = [];
  6212. for (var index = 0; index < uniformsNames.length; index++) {
  6213. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6214. }
  6215. return results;
  6216. };
  6217. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6218. var results = [];
  6219. for (var index = 0; index < attributesNames.length; index++) {
  6220. try {
  6221. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6222. }
  6223. catch (e) {
  6224. results.push(-1);
  6225. }
  6226. }
  6227. return results;
  6228. };
  6229. Engine.prototype.enableEffect = function (effect) {
  6230. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6231. if (effect && effect.onBind) {
  6232. effect.onBind(effect);
  6233. }
  6234. return;
  6235. }
  6236. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6237. // Use program
  6238. this._gl.useProgram(effect.getProgram());
  6239. for (var i in this._vertexAttribArrays) {
  6240. //make sure this is a number)
  6241. var iAsNumber = +i;
  6242. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6243. continue;
  6244. }
  6245. this._vertexAttribArrays[iAsNumber] = false;
  6246. this._gl.disableVertexAttribArray(iAsNumber);
  6247. }
  6248. var attributesCount = effect.getAttributesCount();
  6249. for (var index = 0; index < attributesCount; index++) {
  6250. // Attributes
  6251. var order = effect.getAttributeLocation(index);
  6252. if (order >= 0) {
  6253. this._vertexAttribArrays[order] = true;
  6254. this._gl.enableVertexAttribArray(order);
  6255. }
  6256. }
  6257. this._currentEffect = effect;
  6258. if (effect.onBind) {
  6259. effect.onBind(effect);
  6260. }
  6261. };
  6262. Engine.prototype.setArray = function (uniform, array) {
  6263. if (!uniform)
  6264. return;
  6265. this._gl.uniform1fv(uniform, array);
  6266. };
  6267. Engine.prototype.setArray2 = function (uniform, array) {
  6268. if (!uniform || array.length % 2 !== 0)
  6269. return;
  6270. this._gl.uniform2fv(uniform, array);
  6271. };
  6272. Engine.prototype.setArray3 = function (uniform, array) {
  6273. if (!uniform || array.length % 3 !== 0)
  6274. return;
  6275. this._gl.uniform3fv(uniform, array);
  6276. };
  6277. Engine.prototype.setArray4 = function (uniform, array) {
  6278. if (!uniform || array.length % 4 !== 0)
  6279. return;
  6280. this._gl.uniform4fv(uniform, array);
  6281. };
  6282. Engine.prototype.setMatrices = function (uniform, matrices) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6286. };
  6287. Engine.prototype.setMatrix = function (uniform, matrix) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6291. };
  6292. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6296. };
  6297. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6301. };
  6302. Engine.prototype.setFloat = function (uniform, value) {
  6303. if (!uniform)
  6304. return;
  6305. this._gl.uniform1f(uniform, value);
  6306. };
  6307. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6308. if (!uniform)
  6309. return;
  6310. this._gl.uniform2f(uniform, x, y);
  6311. };
  6312. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6313. if (!uniform)
  6314. return;
  6315. this._gl.uniform3f(uniform, x, y, z);
  6316. };
  6317. Engine.prototype.setBool = function (uniform, bool) {
  6318. if (!uniform)
  6319. return;
  6320. this._gl.uniform1i(uniform, bool);
  6321. };
  6322. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6323. if (!uniform)
  6324. return;
  6325. this._gl.uniform4f(uniform, x, y, z, w);
  6326. };
  6327. Engine.prototype.setColor3 = function (uniform, color3) {
  6328. if (!uniform)
  6329. return;
  6330. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6331. };
  6332. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6333. if (!uniform)
  6334. return;
  6335. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6336. };
  6337. // States
  6338. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6339. if (zOffset === void 0) { zOffset = 0; }
  6340. if (reverseSide === void 0) { reverseSide = false; }
  6341. // Culling
  6342. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6343. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6344. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6345. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6346. if (culling) {
  6347. this._depthCullingState.cullFace = cullFace;
  6348. this._depthCullingState.cull = true;
  6349. }
  6350. else {
  6351. this._depthCullingState.cull = false;
  6352. }
  6353. }
  6354. // Z offset
  6355. this._depthCullingState.zOffset = zOffset;
  6356. };
  6357. Engine.prototype.setDepthBuffer = function (enable) {
  6358. this._depthCullingState.depthTest = enable;
  6359. };
  6360. Engine.prototype.getDepthWrite = function () {
  6361. return this._depthCullingState.depthMask;
  6362. };
  6363. Engine.prototype.setDepthWrite = function (enable) {
  6364. this._depthCullingState.depthMask = enable;
  6365. };
  6366. Engine.prototype.setColorWrite = function (enable) {
  6367. this._gl.colorMask(enable, enable, enable, enable);
  6368. };
  6369. Engine.prototype.setAlphaMode = function (mode) {
  6370. if (this._alphaMode === mode) {
  6371. return;
  6372. }
  6373. switch (mode) {
  6374. case Engine.ALPHA_DISABLE:
  6375. this.setDepthWrite(true);
  6376. this._alphaState.alphaBlend = false;
  6377. break;
  6378. case Engine.ALPHA_COMBINE:
  6379. this.setDepthWrite(false);
  6380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6381. this._alphaState.alphaBlend = true;
  6382. break;
  6383. case Engine.ALPHA_ONEONE:
  6384. this.setDepthWrite(false);
  6385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6386. this._alphaState.alphaBlend = true;
  6387. break;
  6388. case Engine.ALPHA_ADD:
  6389. this.setDepthWrite(false);
  6390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6391. this._alphaState.alphaBlend = true;
  6392. break;
  6393. case Engine.ALPHA_SUBTRACT:
  6394. this.setDepthWrite(false);
  6395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6396. this._alphaState.alphaBlend = true;
  6397. break;
  6398. case Engine.ALPHA_MULTIPLY:
  6399. this.setDepthWrite(false);
  6400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6401. this._alphaState.alphaBlend = true;
  6402. break;
  6403. case Engine.ALPHA_MAXIMIZED:
  6404. this.setDepthWrite(false);
  6405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6406. this._alphaState.alphaBlend = true;
  6407. break;
  6408. }
  6409. this._alphaMode = mode;
  6410. };
  6411. Engine.prototype.getAlphaMode = function () {
  6412. return this._alphaMode;
  6413. };
  6414. Engine.prototype.setAlphaTesting = function (enable) {
  6415. this._alphaTest = enable;
  6416. };
  6417. Engine.prototype.getAlphaTesting = function () {
  6418. return this._alphaTest;
  6419. };
  6420. // Textures
  6421. Engine.prototype.wipeCaches = function () {
  6422. this.resetTextureCache();
  6423. this._currentEffect = null;
  6424. this._depthCullingState.reset();
  6425. this._alphaState.reset();
  6426. this._cachedVertexBuffers = null;
  6427. this._cachedIndexBuffer = null;
  6428. this._cachedEffectForVertexBuffers = null;
  6429. };
  6430. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6431. var gl = this._gl;
  6432. gl.bindTexture(gl.TEXTURE_2D, texture);
  6433. var magFilter = gl.NEAREST;
  6434. var minFilter = gl.NEAREST;
  6435. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6436. magFilter = gl.LINEAR;
  6437. minFilter = gl.LINEAR;
  6438. }
  6439. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6440. magFilter = gl.LINEAR;
  6441. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6442. }
  6443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6445. gl.bindTexture(gl.TEXTURE_2D, null);
  6446. texture.samplingMode = samplingMode;
  6447. };
  6448. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6449. var _this = this;
  6450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6451. if (onLoad === void 0) { onLoad = null; }
  6452. if (onError === void 0) { onError = null; }
  6453. if (buffer === void 0) { buffer = null; }
  6454. var texture = this._gl.createTexture();
  6455. var extension;
  6456. var fromData = false;
  6457. if (url.substr(0, 5) === "data:") {
  6458. fromData = true;
  6459. }
  6460. if (!fromData)
  6461. extension = url.substr(url.length - 4, 4).toLowerCase();
  6462. else {
  6463. var oldUrl = url;
  6464. fromData = oldUrl.split(':');
  6465. url = oldUrl;
  6466. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6467. }
  6468. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6469. var isTGA = (extension === ".tga");
  6470. scene._addPendingData(texture);
  6471. texture.url = url;
  6472. texture.noMipmap = noMipmap;
  6473. texture.references = 1;
  6474. texture.samplingMode = samplingMode;
  6475. this._loadedTexturesCache.push(texture);
  6476. var onerror = function () {
  6477. scene._removePendingData(texture);
  6478. if (onError) {
  6479. onError();
  6480. }
  6481. };
  6482. var callback;
  6483. if (isTGA) {
  6484. callback = function (arrayBuffer) {
  6485. var data = new Uint8Array(arrayBuffer);
  6486. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6487. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6488. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6489. }, onLoad, samplingMode);
  6490. };
  6491. if (!(fromData instanceof Array))
  6492. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6493. callback(arrayBuffer);
  6494. }, onerror, scene.database, true);
  6495. else
  6496. callback(buffer);
  6497. }
  6498. else if (isDDS) {
  6499. callback = function (data) {
  6500. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6501. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6502. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6503. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6504. }, onLoad, samplingMode);
  6505. };
  6506. if (!(fromData instanceof Array))
  6507. BABYLON.Tools.LoadFile(url, function (data) {
  6508. callback(data);
  6509. }, onerror, scene.database, true);
  6510. else
  6511. callback(buffer);
  6512. }
  6513. else {
  6514. var onload = function (img) {
  6515. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6516. var isPot = (img.width === potWidth && img.height === potHeight);
  6517. if (!isPot) {
  6518. _this._prepareWorkingCanvas();
  6519. _this._workingCanvas.width = potWidth;
  6520. _this._workingCanvas.height = potHeight;
  6521. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6522. _this._workingContext.imageSmoothingEnabled = false;
  6523. _this._workingContext.mozImageSmoothingEnabled = false;
  6524. _this._workingContext.oImageSmoothingEnabled = false;
  6525. _this._workingContext.webkitImageSmoothingEnabled = false;
  6526. _this._workingContext.msImageSmoothingEnabled = false;
  6527. }
  6528. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6529. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6530. _this._workingContext.imageSmoothingEnabled = true;
  6531. _this._workingContext.mozImageSmoothingEnabled = true;
  6532. _this._workingContext.oImageSmoothingEnabled = true;
  6533. _this._workingContext.webkitImageSmoothingEnabled = true;
  6534. _this._workingContext.msImageSmoothingEnabled = true;
  6535. }
  6536. }
  6537. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6538. }, onLoad, samplingMode);
  6539. };
  6540. if (!(fromData instanceof Array))
  6541. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6542. else
  6543. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype._getInternalFormat = function (format) {
  6548. var internalFormat = this._gl.RGBA;
  6549. switch (format) {
  6550. case Engine.TEXTUREFORMAT_ALPHA:
  6551. internalFormat = this._gl.ALPHA;
  6552. break;
  6553. case Engine.TEXTUREFORMAT_LUMINANCE:
  6554. internalFormat = this._gl.LUMINANCE;
  6555. break;
  6556. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6557. internalFormat = this._gl.LUMINANCE_ALPHA;
  6558. break;
  6559. case Engine.TEXTUREFORMAT_RGB:
  6560. internalFormat = this._gl.RGB;
  6561. break;
  6562. case Engine.TEXTUREFORMAT_RGBA:
  6563. internalFormat = this._gl.RGBA;
  6564. break;
  6565. }
  6566. return internalFormat;
  6567. };
  6568. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6569. if (compression === void 0) { compression = null; }
  6570. var internalFormat = this._getInternalFormat(format);
  6571. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6572. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6573. if (compression) {
  6574. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6575. }
  6576. else {
  6577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6578. }
  6579. if (texture.generateMipMaps) {
  6580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6581. }
  6582. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6583. this.resetTextureCache();
  6584. texture.isReady = true;
  6585. };
  6586. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6587. if (compression === void 0) { compression = null; }
  6588. var texture = this._gl.createTexture();
  6589. texture._baseWidth = width;
  6590. texture._baseHeight = height;
  6591. texture._width = width;
  6592. texture._height = height;
  6593. texture.references = 1;
  6594. this.updateRawTexture(texture, data, format, invertY, compression);
  6595. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6596. // Filters
  6597. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6601. texture.samplingMode = samplingMode;
  6602. this._loadedTexturesCache.push(texture);
  6603. return texture;
  6604. };
  6605. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6606. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6607. var texture = this._gl.createTexture();
  6608. texture._baseWidth = width;
  6609. texture._baseHeight = height;
  6610. if (forceExponantOfTwo) {
  6611. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6612. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6613. }
  6614. this.resetTextureCache();
  6615. texture._width = width;
  6616. texture._height = height;
  6617. texture.isReady = false;
  6618. texture.generateMipMaps = generateMipMaps;
  6619. texture.references = 1;
  6620. texture.samplingMode = samplingMode;
  6621. this.updateTextureSamplingMode(samplingMode, texture);
  6622. this._loadedTexturesCache.push(texture);
  6623. return texture;
  6624. };
  6625. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6626. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6627. if (texture.isCube) {
  6628. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6629. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6630. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6631. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6632. }
  6633. else {
  6634. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6637. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6638. }
  6639. };
  6640. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6641. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6642. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6643. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6644. if (texture.generateMipMaps) {
  6645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6646. }
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6648. this.resetTextureCache();
  6649. texture.isReady = true;
  6650. };
  6651. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6652. if (texture._isDisabled) {
  6653. return;
  6654. }
  6655. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6656. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6657. try {
  6658. // Testing video texture support
  6659. if (this._videoTextureSupported === undefined) {
  6660. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6661. if (this._gl.getError() !== 0) {
  6662. this._videoTextureSupported = false;
  6663. }
  6664. else {
  6665. this._videoTextureSupported = true;
  6666. }
  6667. }
  6668. // Copy video through the current working canvas if video texture is not supported
  6669. if (!this._videoTextureSupported) {
  6670. if (!texture._workingCanvas) {
  6671. texture._workingCanvas = document.createElement("canvas");
  6672. texture._workingContext = texture._workingCanvas.getContext("2d");
  6673. texture._workingCanvas.width = texture._width;
  6674. texture._workingCanvas.height = texture._height;
  6675. }
  6676. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6677. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6678. }
  6679. else {
  6680. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6681. }
  6682. if (texture.generateMipMaps) {
  6683. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6684. }
  6685. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6686. this.resetTextureCache();
  6687. texture.isReady = true;
  6688. }
  6689. catch (ex) {
  6690. // Something unexpected
  6691. // Let's disable the texture
  6692. texture._isDisabled = true;
  6693. }
  6694. };
  6695. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6696. // old version had a "generateMipMaps" arg instead of options.
  6697. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6698. // in the same way, generateDepthBuffer is defaulted to true
  6699. var generateMipMaps = false;
  6700. var generateDepthBuffer = true;
  6701. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6702. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6703. if (options !== undefined) {
  6704. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6705. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6706. type = options.type === undefined ? type : options.type;
  6707. if (options.samplingMode !== undefined) {
  6708. samplingMode = options.samplingMode;
  6709. }
  6710. if (type === Engine.TEXTURETYPE_FLOAT) {
  6711. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6712. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6713. }
  6714. }
  6715. var gl = this._gl;
  6716. var texture = gl.createTexture();
  6717. gl.bindTexture(gl.TEXTURE_2D, texture);
  6718. var width = size.width || size;
  6719. var height = size.height || size;
  6720. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6721. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6722. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6723. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6724. }
  6725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6728. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6729. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6730. var depthBuffer;
  6731. // Create the depth buffer
  6732. if (generateDepthBuffer) {
  6733. depthBuffer = gl.createRenderbuffer();
  6734. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6735. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6736. }
  6737. // Create the framebuffer
  6738. var framebuffer = gl.createFramebuffer();
  6739. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6740. if (generateDepthBuffer) {
  6741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6742. }
  6743. if (generateMipMaps) {
  6744. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6745. }
  6746. // Unbind
  6747. gl.bindTexture(gl.TEXTURE_2D, null);
  6748. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6749. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6750. texture._framebuffer = framebuffer;
  6751. if (generateDepthBuffer) {
  6752. texture._depthBuffer = depthBuffer;
  6753. }
  6754. texture._width = width;
  6755. texture._height = height;
  6756. texture.isReady = true;
  6757. texture.generateMipMaps = generateMipMaps;
  6758. texture.references = 1;
  6759. texture.samplingMode = samplingMode;
  6760. this.resetTextureCache();
  6761. this._loadedTexturesCache.push(texture);
  6762. return texture;
  6763. };
  6764. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6765. var gl = this._gl;
  6766. var texture = gl.createTexture();
  6767. var generateMipMaps = true;
  6768. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6769. if (options !== undefined) {
  6770. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6771. if (options.samplingMode !== undefined) {
  6772. samplingMode = options.samplingMode;
  6773. }
  6774. }
  6775. texture.isCube = true;
  6776. texture.references = 1;
  6777. texture.generateMipMaps = generateMipMaps;
  6778. texture.references = 1;
  6779. texture.samplingMode = samplingMode;
  6780. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6781. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6782. for (var face = 0; face < 6; face++) {
  6783. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6784. }
  6785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6789. // Create the depth buffer
  6790. var depthBuffer = gl.createRenderbuffer();
  6791. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6792. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6793. // Create the framebuffer
  6794. var framebuffer = gl.createFramebuffer();
  6795. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6796. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6797. // Mipmaps
  6798. if (texture.generateMipMaps) {
  6799. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6800. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6801. }
  6802. // Unbind
  6803. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6804. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6805. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6806. texture._framebuffer = framebuffer;
  6807. texture._depthBuffer = depthBuffer;
  6808. this.resetTextureCache();
  6809. texture._width = size;
  6810. texture._height = size;
  6811. texture.isReady = true;
  6812. return texture;
  6813. };
  6814. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6815. var _this = this;
  6816. var gl = this._gl;
  6817. var texture = gl.createTexture();
  6818. texture.isCube = true;
  6819. texture.url = rootUrl;
  6820. texture.references = 1;
  6821. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6822. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6823. if (isDDS) {
  6824. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6825. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6826. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6827. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6829. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6830. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6831. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6832. }
  6833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6837. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6838. _this.resetTextureCache();
  6839. texture._width = info.width;
  6840. texture._height = info.height;
  6841. texture.isReady = true;
  6842. }, null, null, true);
  6843. }
  6844. else {
  6845. cascadeLoad(rootUrl, scene, function (imgs) {
  6846. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6847. var height = width;
  6848. _this._prepareWorkingCanvas();
  6849. _this._workingCanvas.width = width;
  6850. _this._workingCanvas.height = height;
  6851. var faces = [
  6852. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6853. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6854. ];
  6855. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6856. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6857. for (var index = 0; index < faces.length; index++) {
  6858. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6859. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6860. }
  6861. if (!noMipmap) {
  6862. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6863. }
  6864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6868. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6869. _this.resetTextureCache();
  6870. texture._width = width;
  6871. texture._height = height;
  6872. texture.isReady = true;
  6873. }, files);
  6874. }
  6875. return texture;
  6876. };
  6877. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6878. var _this = this;
  6879. var gl = this._gl;
  6880. var texture = gl.createTexture();
  6881. scene._addPendingData(texture);
  6882. texture.isCube = true;
  6883. texture.references = 1;
  6884. texture.url = url;
  6885. var internalFormat = this._getInternalFormat(format);
  6886. var textureType = gl.UNSIGNED_BYTE;
  6887. if (type === Engine.TEXTURETYPE_FLOAT) {
  6888. textureType = gl.FLOAT;
  6889. }
  6890. var width = size;
  6891. var height = width;
  6892. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6893. texture._width = width;
  6894. texture._height = height;
  6895. var onerror = function () {
  6896. scene._removePendingData(texture);
  6897. };
  6898. var internalCallback = function (data) {
  6899. var rgbeDataArrays = callback(data);
  6900. var facesIndex = [
  6901. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6902. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6903. ];
  6904. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6905. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6906. for (var index = 0; index < facesIndex.length; index++) {
  6907. var faceData = rgbeDataArrays[index];
  6908. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6909. }
  6910. if (!noMipmap && isPot) {
  6911. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6912. }
  6913. else {
  6914. noMipmap = true;
  6915. }
  6916. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6919. }
  6920. else {
  6921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6923. }
  6924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6926. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6927. texture.isReady = true;
  6928. _this.resetTextureCache();
  6929. scene._removePendingData(texture);
  6930. };
  6931. BABYLON.Tools.LoadFile(url, function (data) {
  6932. internalCallback(data);
  6933. }, onerror, scene.database, true);
  6934. return texture;
  6935. };
  6936. ;
  6937. Engine.prototype._releaseTexture = function (texture) {
  6938. var gl = this._gl;
  6939. if (texture._framebuffer) {
  6940. gl.deleteFramebuffer(texture._framebuffer);
  6941. }
  6942. if (texture._depthBuffer) {
  6943. gl.deleteRenderbuffer(texture._depthBuffer);
  6944. }
  6945. gl.deleteTexture(texture);
  6946. // Unbind channels
  6947. this.unbindAllTextures();
  6948. var index = this._loadedTexturesCache.indexOf(texture);
  6949. if (index !== -1) {
  6950. this._loadedTexturesCache.splice(index, 1);
  6951. }
  6952. };
  6953. Engine.prototype.bindSamplers = function (effect) {
  6954. this._gl.useProgram(effect.getProgram());
  6955. var samplers = effect.getSamplers();
  6956. for (var index = 0; index < samplers.length; index++) {
  6957. var uniform = effect.getUniform(samplers[index]);
  6958. this._gl.uniform1i(uniform, index);
  6959. }
  6960. this._currentEffect = null;
  6961. };
  6962. Engine.prototype._bindTexture = function (channel, texture) {
  6963. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6964. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6965. this._activeTexturesCache[channel] = null;
  6966. };
  6967. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6968. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6969. };
  6970. Engine.prototype.unbindAllTextures = function () {
  6971. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6972. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6973. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6974. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6975. this._activeTexturesCache[channel] = null;
  6976. }
  6977. };
  6978. Engine.prototype.setTexture = function (channel, texture) {
  6979. if (channel < 0) {
  6980. return;
  6981. }
  6982. // Not ready?
  6983. if (!texture || !texture.isReady()) {
  6984. if (this._activeTexturesCache[channel] != null) {
  6985. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6986. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6987. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6988. this._activeTexturesCache[channel] = null;
  6989. }
  6990. return;
  6991. }
  6992. // Video
  6993. var alreadyActivated = false;
  6994. if (texture instanceof BABYLON.VideoTexture) {
  6995. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6996. alreadyActivated = true;
  6997. texture.update();
  6998. }
  6999. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7000. texture.delayLoad();
  7001. return;
  7002. }
  7003. if (this._activeTexturesCache[channel] === texture) {
  7004. return;
  7005. }
  7006. this._activeTexturesCache[channel] = texture;
  7007. var internalTexture = texture.getInternalTexture();
  7008. if (!alreadyActivated) {
  7009. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7010. }
  7011. if (internalTexture.isCube) {
  7012. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7013. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7014. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7015. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7016. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7017. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7018. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7019. }
  7020. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7021. }
  7022. else {
  7023. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7024. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7025. internalTexture._cachedWrapU = texture.wrapU;
  7026. switch (texture.wrapU) {
  7027. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7029. break;
  7030. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7032. break;
  7033. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7034. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7035. break;
  7036. }
  7037. }
  7038. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7039. internalTexture._cachedWrapV = texture.wrapV;
  7040. switch (texture.wrapV) {
  7041. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7042. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7043. break;
  7044. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7045. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7046. break;
  7047. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7049. break;
  7050. }
  7051. }
  7052. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7053. }
  7054. };
  7055. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7056. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7057. var value = texture.anisotropicFilteringLevel;
  7058. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7059. value = 1;
  7060. }
  7061. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7062. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7063. texture._cachedAnisotropicFilteringLevel = value;
  7064. }
  7065. };
  7066. Engine.prototype.readPixels = function (x, y, width, height) {
  7067. var data = new Uint8Array(height * width * 4);
  7068. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7069. return data;
  7070. };
  7071. Engine.prototype.releaseInternalTexture = function (texture) {
  7072. if (!texture) {
  7073. return;
  7074. }
  7075. texture.references--;
  7076. // Final reference ?
  7077. if (texture.references === 0) {
  7078. var texturesCache = this.getLoadedTexturesCache();
  7079. var index = texturesCache.indexOf(texture);
  7080. if (index > -1) {
  7081. texturesCache.splice(index, 1);
  7082. }
  7083. this._releaseTexture(texture);
  7084. }
  7085. };
  7086. // Dispose
  7087. Engine.prototype.dispose = function () {
  7088. this.hideLoadingUI();
  7089. this.stopRenderLoop();
  7090. // Release scenes
  7091. while (this.scenes.length) {
  7092. this.scenes[0].dispose();
  7093. }
  7094. // Release audio engine
  7095. Engine.audioEngine.dispose();
  7096. // Release effects
  7097. for (var name in this._compiledEffects) {
  7098. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7099. }
  7100. // Unbind
  7101. for (var i in this._vertexAttribArrays) {
  7102. //making sure this is a string
  7103. var iAsNumber = +i;
  7104. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7105. continue;
  7106. }
  7107. this._gl.disableVertexAttribArray(iAsNumber);
  7108. }
  7109. this._gl = null;
  7110. // Events
  7111. window.removeEventListener("blur", this._onBlur);
  7112. window.removeEventListener("focus", this._onFocus);
  7113. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7114. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7115. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7116. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7117. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7118. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7119. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7120. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7121. };
  7122. // Loading screen
  7123. Engine.prototype.displayLoadingUI = function () {
  7124. this._loadingScreen.displayLoadingUI();
  7125. };
  7126. Engine.prototype.hideLoadingUI = function () {
  7127. this._loadingScreen.hideLoadingUI();
  7128. };
  7129. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7130. get: function () {
  7131. return this._loadingScreen;
  7132. },
  7133. set: function (loadingScreen) {
  7134. this._loadingScreen = loadingScreen;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7140. set: function (text) {
  7141. this._loadingScreen.loadingUIText = text;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7147. set: function (color) {
  7148. this._loadingScreen.loadingUIBackgroundColor = color;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. // FPS
  7154. Engine.prototype.getFps = function () {
  7155. return this.fps;
  7156. };
  7157. Engine.prototype.getDeltaTime = function () {
  7158. return this.deltaTime;
  7159. };
  7160. Engine.prototype._measureFps = function () {
  7161. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7162. var length = this.previousFramesDuration.length;
  7163. if (length >= 2) {
  7164. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7165. }
  7166. if (length >= this.fpsRange) {
  7167. if (length > this.fpsRange) {
  7168. this.previousFramesDuration.splice(0, 1);
  7169. length = this.previousFramesDuration.length;
  7170. }
  7171. var sum = 0;
  7172. for (var id = 0; id < length - 1; id++) {
  7173. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7174. }
  7175. this.fps = 1000.0 / (sum / (length - 1));
  7176. }
  7177. };
  7178. // Statics
  7179. Engine.isSupported = function () {
  7180. try {
  7181. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7182. if (navigator.isCocoonJS) {
  7183. return true;
  7184. }
  7185. var tempcanvas = document.createElement("canvas");
  7186. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7187. return gl != null && !!window.WebGLRenderingContext;
  7188. }
  7189. catch (e) {
  7190. return false;
  7191. }
  7192. };
  7193. // Const statics
  7194. Engine._ALPHA_DISABLE = 0;
  7195. Engine._ALPHA_ADD = 1;
  7196. Engine._ALPHA_COMBINE = 2;
  7197. Engine._ALPHA_SUBTRACT = 3;
  7198. Engine._ALPHA_MULTIPLY = 4;
  7199. Engine._ALPHA_MAXIMIZED = 5;
  7200. Engine._ALPHA_ONEONE = 6;
  7201. Engine._DELAYLOADSTATE_NONE = 0;
  7202. Engine._DELAYLOADSTATE_LOADED = 1;
  7203. Engine._DELAYLOADSTATE_LOADING = 2;
  7204. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7205. Engine._TEXTUREFORMAT_ALPHA = 0;
  7206. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7207. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7208. Engine._TEXTUREFORMAT_RGB = 4;
  7209. Engine._TEXTUREFORMAT_RGBA = 5;
  7210. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7211. Engine._TEXTURETYPE_FLOAT = 1;
  7212. // Updatable statics so stick with vars here
  7213. Engine.Epsilon = 0.001;
  7214. Engine.CollisionsEpsilon = 0.001;
  7215. Engine.CodeRepository = "src/";
  7216. Engine.ShadersRepository = "src/Shaders/";
  7217. return Engine;
  7218. })();
  7219. BABYLON.Engine = Engine;
  7220. })(BABYLON || (BABYLON = {}));
  7221. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7222. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7223. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7224. 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;
  7225. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7226. };
  7227. var BABYLON;
  7228. (function (BABYLON) {
  7229. /**
  7230. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7231. */
  7232. var Node = (function () {
  7233. /**
  7234. * @constructor
  7235. * @param {string} name - the name and id to be given to this node
  7236. * @param {BABYLON.Scene} the scene this node will be added to
  7237. */
  7238. function Node(name, scene) {
  7239. this.state = "";
  7240. this.animations = new Array();
  7241. this._ranges = {};
  7242. this._childrenFlag = -1;
  7243. this._isEnabled = true;
  7244. this._isReady = true;
  7245. this._currentRenderId = -1;
  7246. this._parentRenderId = -1;
  7247. this.name = name;
  7248. this.id = name;
  7249. this._scene = scene;
  7250. this._initCache();
  7251. }
  7252. Node.prototype.getScene = function () {
  7253. return this._scene;
  7254. };
  7255. Node.prototype.getEngine = function () {
  7256. return this._scene.getEngine();
  7257. };
  7258. // override it in derived class
  7259. Node.prototype.getWorldMatrix = function () {
  7260. return BABYLON.Matrix.Identity();
  7261. };
  7262. // override it in derived class if you add new variables to the cache
  7263. // and call the parent class method
  7264. Node.prototype._initCache = function () {
  7265. this._cache = {};
  7266. this._cache.parent = undefined;
  7267. };
  7268. Node.prototype.updateCache = function (force) {
  7269. if (!force && this.isSynchronized())
  7270. return;
  7271. this._cache.parent = this.parent;
  7272. this._updateCache();
  7273. };
  7274. // override it in derived class if you add new variables to the cache
  7275. // and call the parent class method if !ignoreParentClass
  7276. Node.prototype._updateCache = function (ignoreParentClass) {
  7277. };
  7278. // override it in derived class if you add new variables to the cache
  7279. Node.prototype._isSynchronized = function () {
  7280. return true;
  7281. };
  7282. Node.prototype._markSyncedWithParent = function () {
  7283. this._parentRenderId = this.parent._currentRenderId;
  7284. };
  7285. Node.prototype.isSynchronizedWithParent = function () {
  7286. if (!this.parent) {
  7287. return true;
  7288. }
  7289. if (this._parentRenderId !== this.parent._currentRenderId) {
  7290. return false;
  7291. }
  7292. return this.parent.isSynchronized();
  7293. };
  7294. Node.prototype.isSynchronized = function (updateCache) {
  7295. var check = this.hasNewParent();
  7296. check = check || !this.isSynchronizedWithParent();
  7297. check = check || !this._isSynchronized();
  7298. if (updateCache)
  7299. this.updateCache(true);
  7300. return !check;
  7301. };
  7302. Node.prototype.hasNewParent = function (update) {
  7303. if (this._cache.parent === this.parent)
  7304. return false;
  7305. if (update)
  7306. this._cache.parent = this.parent;
  7307. return true;
  7308. };
  7309. /**
  7310. * Is this node ready to be used/rendered
  7311. * @return {boolean} is it ready
  7312. */
  7313. Node.prototype.isReady = function () {
  7314. return this._isReady;
  7315. };
  7316. /**
  7317. * Is this node enabled.
  7318. * If the node has a parent and is enabled, the parent will be inspected as well.
  7319. * @return {boolean} whether this node (and its parent) is enabled.
  7320. * @see setEnabled
  7321. */
  7322. Node.prototype.isEnabled = function () {
  7323. if (!this._isEnabled) {
  7324. return false;
  7325. }
  7326. if (this.parent) {
  7327. return this.parent.isEnabled();
  7328. }
  7329. return true;
  7330. };
  7331. /**
  7332. * Set the enabled state of this node.
  7333. * @param {boolean} value - the new enabled state
  7334. * @see isEnabled
  7335. */
  7336. Node.prototype.setEnabled = function (value) {
  7337. this._isEnabled = value;
  7338. };
  7339. /**
  7340. * Is this node a descendant of the given node.
  7341. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7342. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7343. * @see parent
  7344. */
  7345. Node.prototype.isDescendantOf = function (ancestor) {
  7346. if (this.parent) {
  7347. if (this.parent === ancestor) {
  7348. return true;
  7349. }
  7350. return this.parent.isDescendantOf(ancestor);
  7351. }
  7352. return false;
  7353. };
  7354. Node.prototype._getDescendants = function (list, results, directDecendantsOnly) {
  7355. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7356. for (var index = 0; index < list.length; index++) {
  7357. var item = list[index];
  7358. if ((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) {
  7359. results.push(item);
  7360. }
  7361. }
  7362. };
  7363. /**
  7364. * Will return all nodes that have this node as parent.
  7365. * @return {BABYLON.Node[]} all children nodes of all types.
  7366. */
  7367. Node.prototype.getDescendants = function (directDecendantsOnly) {
  7368. var results = [];
  7369. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7370. this._getDescendants(this._scene.lights, results, directDecendantsOnly);
  7371. this._getDescendants(this._scene.cameras, results, directDecendantsOnly);
  7372. return results;
  7373. };
  7374. /**
  7375. * @Deprecated, legacy support.
  7376. * use getDecendants instead.
  7377. */
  7378. Node.prototype.getChildren = function () {
  7379. return this.getDescendants(true);
  7380. };
  7381. /**
  7382. * Get all child-meshes of this node.
  7383. */
  7384. Node.prototype.getChildMeshes = function (directDecendantsOnly) {
  7385. var results = [];
  7386. this._getDescendants(this._scene.meshes, results, false);
  7387. return results;
  7388. };
  7389. Node.prototype._setReady = function (state) {
  7390. if (state === this._isReady) {
  7391. return;
  7392. }
  7393. if (!state) {
  7394. this._isReady = false;
  7395. return;
  7396. }
  7397. this._isReady = true;
  7398. if (this.onReady) {
  7399. this.onReady(this);
  7400. }
  7401. };
  7402. Node.prototype.getAnimationByName = function (name) {
  7403. for (var i = 0; i < this.animations.length; i++) {
  7404. var animation = this.animations[i];
  7405. if (animation.name === name) {
  7406. return animation;
  7407. }
  7408. }
  7409. return null;
  7410. };
  7411. Node.prototype.createAnimationRange = function (name, from, to) {
  7412. // check name not already in use
  7413. if (!this._ranges[name]) {
  7414. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7415. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7416. if (this.animations[i]) {
  7417. this.animations[i].createRange(name, from, to);
  7418. }
  7419. }
  7420. }
  7421. };
  7422. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7423. if (deleteFrames === void 0) { deleteFrames = true; }
  7424. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7425. if (this.animations[i]) {
  7426. this.animations[i].deleteRange(name, deleteFrames);
  7427. }
  7428. }
  7429. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7430. };
  7431. Node.prototype.getAnimationRange = function (name) {
  7432. return this._ranges[name];
  7433. };
  7434. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7435. var range = this.getAnimationRange(name);
  7436. if (!range) {
  7437. return null;
  7438. }
  7439. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7440. };
  7441. Node.prototype.serializeAnimationRanges = function () {
  7442. var serializationRanges = [];
  7443. for (var name in this._ranges) {
  7444. var range = {};
  7445. range.name = name;
  7446. range.from = this._ranges[name].from;
  7447. range.to = this._ranges[name].to;
  7448. serializationRanges.push(range);
  7449. }
  7450. return serializationRanges;
  7451. };
  7452. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7453. if (parsedNode.ranges) {
  7454. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7455. var data = parsedNode.ranges[index];
  7456. node.createAnimationRange(data.name, data.from, data.to);
  7457. }
  7458. }
  7459. };
  7460. __decorate([
  7461. BABYLON.serialize()
  7462. ], Node.prototype, "name", void 0);
  7463. __decorate([
  7464. BABYLON.serialize()
  7465. ], Node.prototype, "id", void 0);
  7466. __decorate([
  7467. BABYLON.serialize()
  7468. ], Node.prototype, "uniqueId", void 0);
  7469. __decorate([
  7470. BABYLON.serialize()
  7471. ], Node.prototype, "state", void 0);
  7472. return Node;
  7473. })();
  7474. BABYLON.Node = Node;
  7475. })(BABYLON || (BABYLON = {}));
  7476. var BABYLON;
  7477. (function (BABYLON) {
  7478. var FilesInput = (function () {
  7479. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7480. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7481. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7482. this._engine = p_engine;
  7483. this._canvas = p_canvas;
  7484. this._currentScene = p_scene;
  7485. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7486. this._progressCallback = p_progressCallback;
  7487. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7488. this._textureLoadingCallback = p_textureLoadingCallback;
  7489. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7490. }
  7491. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7492. var _this = this;
  7493. if (p_elementToMonitor) {
  7494. this._elementToMonitor = p_elementToMonitor;
  7495. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7496. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7497. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7498. }
  7499. };
  7500. FilesInput.prototype.renderFunction = function () {
  7501. if (this._additionnalRenderLoopLogicCallback) {
  7502. this._additionnalRenderLoopLogicCallback();
  7503. }
  7504. if (this._currentScene) {
  7505. if (this._textureLoadingCallback) {
  7506. var remaining = this._currentScene.getWaitingItemsCount();
  7507. if (remaining > 0) {
  7508. this._textureLoadingCallback(remaining);
  7509. }
  7510. }
  7511. this._currentScene.render();
  7512. }
  7513. };
  7514. FilesInput.prototype.drag = function (e) {
  7515. e.stopPropagation();
  7516. e.preventDefault();
  7517. };
  7518. FilesInput.prototype.drop = function (eventDrop) {
  7519. eventDrop.stopPropagation();
  7520. eventDrop.preventDefault();
  7521. this.loadFiles(eventDrop);
  7522. };
  7523. FilesInput.prototype.loadFiles = function (event) {
  7524. if (this._startingProcessingFilesCallback)
  7525. this._startingProcessingFilesCallback();
  7526. // Handling data transfer via drag'n'drop
  7527. if (event && event.dataTransfer && event.dataTransfer.files) {
  7528. this._filesToLoad = event.dataTransfer.files;
  7529. }
  7530. // Handling files from input files
  7531. if (event && event.target && event.target.files) {
  7532. this._filesToLoad = event.target.files;
  7533. }
  7534. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7535. for (var i = 0; i < this._filesToLoad.length; i++) {
  7536. switch (this._filesToLoad[i].type) {
  7537. case "image/jpeg":
  7538. case "image/png":
  7539. case "image/bmp":
  7540. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7541. break;
  7542. case "image/targa":
  7543. case "image/vnd.ms-dds":
  7544. case "audio/wav":
  7545. case "audio/x-wav":
  7546. case "audio/mp3":
  7547. case "audio/mpeg":
  7548. case "audio/mpeg3":
  7549. case "audio/x-mpeg-3":
  7550. case "audio/ogg":
  7551. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7552. break;
  7553. default:
  7554. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7555. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7556. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7557. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7558. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7559. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7560. this._sceneFileToLoad = this._filesToLoad[i];
  7561. }
  7562. break;
  7563. }
  7564. }
  7565. this.reload();
  7566. }
  7567. };
  7568. FilesInput.prototype.reload = function () {
  7569. var _this = this;
  7570. var that = this;
  7571. // If a ".babylon" file has been provided
  7572. if (this._sceneFileToLoad) {
  7573. if (this._currentScene) {
  7574. if (BABYLON.Tools.errorsCount > 0) {
  7575. BABYLON.Tools.ClearLogCache();
  7576. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7577. }
  7578. this._engine.stopRenderLoop();
  7579. this._currentScene.dispose();
  7580. }
  7581. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7582. that._currentScene = newScene;
  7583. // Wait for textures and shaders to be ready
  7584. that._currentScene.executeWhenReady(function () {
  7585. // Attach camera to canvas inputs
  7586. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7587. that._currentScene.createDefaultCameraOrLight();
  7588. }
  7589. that._currentScene.activeCamera.attachControl(that._canvas);
  7590. if (that._sceneLoadedCallback) {
  7591. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7592. }
  7593. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7594. });
  7595. }, function (progress) {
  7596. if (_this._progressCallback) {
  7597. _this._progressCallback(progress);
  7598. }
  7599. });
  7600. }
  7601. else {
  7602. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7603. }
  7604. };
  7605. FilesInput.FilesTextures = new Array();
  7606. FilesInput.FilesToLoad = new Array();
  7607. return FilesInput;
  7608. })();
  7609. BABYLON.FilesInput = FilesInput;
  7610. })(BABYLON || (BABYLON = {}));
  7611. var BABYLON;
  7612. (function (BABYLON) {
  7613. var IntersectionInfo = (function () {
  7614. function IntersectionInfo(bu, bv, distance) {
  7615. this.bu = bu;
  7616. this.bv = bv;
  7617. this.distance = distance;
  7618. this.faceId = 0;
  7619. this.subMeshId = 0;
  7620. }
  7621. return IntersectionInfo;
  7622. })();
  7623. BABYLON.IntersectionInfo = IntersectionInfo;
  7624. var PickingInfo = (function () {
  7625. function PickingInfo() {
  7626. this.hit = false;
  7627. this.distance = 0;
  7628. this.pickedPoint = null;
  7629. this.pickedMesh = null;
  7630. this.bu = 0;
  7631. this.bv = 0;
  7632. this.faceId = -1;
  7633. this.subMeshId = 0;
  7634. this.pickedSprite = null;
  7635. }
  7636. // Methods
  7637. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7638. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7639. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7640. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7641. return null;
  7642. }
  7643. var indices = this.pickedMesh.getIndices();
  7644. var result;
  7645. if (useVerticesNormals) {
  7646. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7647. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7648. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7649. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7650. normal0 = normal0.scale(this.bu);
  7651. normal1 = normal1.scale(this.bv);
  7652. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7653. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7654. }
  7655. else {
  7656. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7657. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7658. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7659. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7660. var p1p2 = vertex1.subtract(vertex2);
  7661. var p3p2 = vertex3.subtract(vertex2);
  7662. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7663. }
  7664. if (useWorldCoordinates) {
  7665. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7666. }
  7667. return BABYLON.Vector3.Normalize(result);
  7668. };
  7669. PickingInfo.prototype.getTextureCoordinates = function () {
  7670. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7671. return null;
  7672. }
  7673. var indices = this.pickedMesh.getIndices();
  7674. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7675. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7676. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7677. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7678. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7679. uv1 = uv1.scale(this.bu);
  7680. uv2 = uv2.scale(this.bv);
  7681. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7682. };
  7683. return PickingInfo;
  7684. })();
  7685. BABYLON.PickingInfo = PickingInfo;
  7686. })(BABYLON || (BABYLON = {}));
  7687. var BABYLON;
  7688. (function (BABYLON) {
  7689. var BoundingSphere = (function () {
  7690. function BoundingSphere(minimum, maximum) {
  7691. this.minimum = minimum;
  7692. this.maximum = maximum;
  7693. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7694. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7695. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7696. this.radius = distance * 0.5;
  7697. this.centerWorld = BABYLON.Vector3.Zero();
  7698. this._update(BABYLON.Matrix.Identity());
  7699. }
  7700. // Methods
  7701. BoundingSphere.prototype._update = function (world) {
  7702. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7703. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7704. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7705. };
  7706. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7707. for (var i = 0; i < 6; i++) {
  7708. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7709. return false;
  7710. }
  7711. return true;
  7712. };
  7713. BoundingSphere.prototype.intersectsPoint = function (point) {
  7714. var x = this.centerWorld.x - point.x;
  7715. var y = this.centerWorld.y - point.y;
  7716. var z = this.centerWorld.z - point.z;
  7717. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7718. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7719. return false;
  7720. return true;
  7721. };
  7722. // Statics
  7723. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7724. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7725. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7726. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7727. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7728. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7729. return false;
  7730. return true;
  7731. };
  7732. return BoundingSphere;
  7733. })();
  7734. BABYLON.BoundingSphere = BoundingSphere;
  7735. })(BABYLON || (BABYLON = {}));
  7736. var BABYLON;
  7737. (function (BABYLON) {
  7738. var BoundingBox = (function () {
  7739. function BoundingBox(minimum, maximum) {
  7740. this.minimum = minimum;
  7741. this.maximum = maximum;
  7742. this.vectors = new Array();
  7743. this.vectorsWorld = new Array();
  7744. // Bounding vectors
  7745. this.vectors.push(this.minimum.clone());
  7746. this.vectors.push(this.maximum.clone());
  7747. this.vectors.push(this.minimum.clone());
  7748. this.vectors[2].x = this.maximum.x;
  7749. this.vectors.push(this.minimum.clone());
  7750. this.vectors[3].y = this.maximum.y;
  7751. this.vectors.push(this.minimum.clone());
  7752. this.vectors[4].z = this.maximum.z;
  7753. this.vectors.push(this.maximum.clone());
  7754. this.vectors[5].z = this.minimum.z;
  7755. this.vectors.push(this.maximum.clone());
  7756. this.vectors[6].x = this.minimum.x;
  7757. this.vectors.push(this.maximum.clone());
  7758. this.vectors[7].y = this.minimum.y;
  7759. // OBB
  7760. this.center = this.maximum.add(this.minimum).scale(0.5);
  7761. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7762. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7763. // World
  7764. for (var index = 0; index < this.vectors.length; index++) {
  7765. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7766. }
  7767. this.minimumWorld = BABYLON.Vector3.Zero();
  7768. this.maximumWorld = BABYLON.Vector3.Zero();
  7769. this._update(BABYLON.Matrix.Identity());
  7770. }
  7771. // Methods
  7772. BoundingBox.prototype.getWorldMatrix = function () {
  7773. return this._worldMatrix;
  7774. };
  7775. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7776. this._worldMatrix.copyFrom(matrix);
  7777. return this;
  7778. };
  7779. BoundingBox.prototype._update = function (world) {
  7780. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7781. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7782. for (var index = 0; index < this.vectors.length; index++) {
  7783. var v = this.vectorsWorld[index];
  7784. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7785. if (v.x < this.minimumWorld.x)
  7786. this.minimumWorld.x = v.x;
  7787. if (v.y < this.minimumWorld.y)
  7788. this.minimumWorld.y = v.y;
  7789. if (v.z < this.minimumWorld.z)
  7790. this.minimumWorld.z = v.z;
  7791. if (v.x > this.maximumWorld.x)
  7792. this.maximumWorld.x = v.x;
  7793. if (v.y > this.maximumWorld.y)
  7794. this.maximumWorld.y = v.y;
  7795. if (v.z > this.maximumWorld.z)
  7796. this.maximumWorld.z = v.z;
  7797. }
  7798. // OBB
  7799. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7800. this.center.scaleInPlace(0.5);
  7801. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7802. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7804. this._worldMatrix = world;
  7805. };
  7806. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7807. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7808. };
  7809. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7810. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7811. };
  7812. BoundingBox.prototype.intersectsPoint = function (point) {
  7813. var delta = -BABYLON.Engine.Epsilon;
  7814. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7815. return false;
  7816. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7817. return false;
  7818. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7819. return false;
  7820. return true;
  7821. };
  7822. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7823. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7824. };
  7825. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7826. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7827. return false;
  7828. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7829. return false;
  7830. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7831. return false;
  7832. return true;
  7833. };
  7834. // Statics
  7835. BoundingBox.Intersects = function (box0, box1) {
  7836. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7837. return false;
  7838. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7839. return false;
  7840. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7841. return false;
  7842. return true;
  7843. };
  7844. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7845. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7846. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7847. return (num <= (sphereRadius * sphereRadius));
  7848. };
  7849. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7850. for (var p = 0; p < 6; p++) {
  7851. for (var i = 0; i < 8; i++) {
  7852. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7853. return false;
  7854. }
  7855. }
  7856. }
  7857. return true;
  7858. };
  7859. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7860. for (var p = 0; p < 6; p++) {
  7861. var inCount = 8;
  7862. for (var i = 0; i < 8; i++) {
  7863. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7864. --inCount;
  7865. }
  7866. else {
  7867. break;
  7868. }
  7869. }
  7870. if (inCount === 0)
  7871. return false;
  7872. }
  7873. return true;
  7874. };
  7875. return BoundingBox;
  7876. })();
  7877. BABYLON.BoundingBox = BoundingBox;
  7878. })(BABYLON || (BABYLON = {}));
  7879. var BABYLON;
  7880. (function (BABYLON) {
  7881. var computeBoxExtents = function (axis, box) {
  7882. var p = BABYLON.Vector3.Dot(box.center, axis);
  7883. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7884. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7885. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7886. var r = r0 + r1 + r2;
  7887. return {
  7888. min: p - r,
  7889. max: p + r
  7890. };
  7891. };
  7892. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7893. var axisOverlap = function (axis, box0, box1) {
  7894. var result0 = computeBoxExtents(axis, box0);
  7895. var result1 = computeBoxExtents(axis, box1);
  7896. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7897. };
  7898. var BoundingInfo = (function () {
  7899. function BoundingInfo(minimum, maximum) {
  7900. this.minimum = minimum;
  7901. this.maximum = maximum;
  7902. this._isLocked = false;
  7903. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7904. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7905. }
  7906. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7907. get: function () {
  7908. return this._isLocked;
  7909. },
  7910. set: function (value) {
  7911. this._isLocked = value;
  7912. },
  7913. enumerable: true,
  7914. configurable: true
  7915. });
  7916. // Methods
  7917. BoundingInfo.prototype.update = function (world) {
  7918. if (this._isLocked) {
  7919. return;
  7920. }
  7921. this.boundingBox._update(world);
  7922. this.boundingSphere._update(world);
  7923. };
  7924. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7925. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7926. return false;
  7927. return this.boundingBox.isInFrustum(frustumPlanes);
  7928. };
  7929. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7930. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7931. };
  7932. BoundingInfo.prototype._checkCollision = function (collider) {
  7933. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7934. };
  7935. BoundingInfo.prototype.intersectsPoint = function (point) {
  7936. if (!this.boundingSphere.centerWorld) {
  7937. return false;
  7938. }
  7939. if (!this.boundingSphere.intersectsPoint(point)) {
  7940. return false;
  7941. }
  7942. if (!this.boundingBox.intersectsPoint(point)) {
  7943. return false;
  7944. }
  7945. return true;
  7946. };
  7947. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7948. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7949. return false;
  7950. }
  7951. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7952. return false;
  7953. }
  7954. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7955. return false;
  7956. }
  7957. if (!precise) {
  7958. return true;
  7959. }
  7960. var box0 = this.boundingBox;
  7961. var box1 = boundingInfo.boundingBox;
  7962. if (!axisOverlap(box0.directions[0], box0, box1))
  7963. return false;
  7964. if (!axisOverlap(box0.directions[1], box0, box1))
  7965. return false;
  7966. if (!axisOverlap(box0.directions[2], box0, box1))
  7967. return false;
  7968. if (!axisOverlap(box1.directions[0], box0, box1))
  7969. return false;
  7970. if (!axisOverlap(box1.directions[1], box0, box1))
  7971. return false;
  7972. if (!axisOverlap(box1.directions[2], box0, box1))
  7973. return false;
  7974. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7975. return false;
  7976. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7977. return false;
  7978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7979. return false;
  7980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7981. return false;
  7982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7983. return false;
  7984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7985. return false;
  7986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7987. return false;
  7988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7989. return false;
  7990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7991. return false;
  7992. return true;
  7993. };
  7994. return BoundingInfo;
  7995. })();
  7996. BABYLON.BoundingInfo = BoundingInfo;
  7997. })(BABYLON || (BABYLON = {}));
  7998. var BABYLON;
  7999. (function (BABYLON) {
  8000. var AbstractMesh = (function (_super) {
  8001. __extends(AbstractMesh, _super);
  8002. // Constructor
  8003. function AbstractMesh(name, scene) {
  8004. var _this = this;
  8005. _super.call(this, name, scene);
  8006. // Properties
  8007. this.definedFacingForward = true; // orientation for POV movement & rotation
  8008. this.position = new BABYLON.Vector3(0, 0, 0);
  8009. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8010. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8011. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8012. this.visibility = 1.0;
  8013. this.alphaIndex = Number.MAX_VALUE;
  8014. this.infiniteDistance = false;
  8015. this.isVisible = true;
  8016. this.isPickable = true;
  8017. this.showBoundingBox = false;
  8018. this.showSubMeshesBoundingBox = false;
  8019. this.onDispose = null;
  8020. this.isBlocker = false;
  8021. this.renderingGroupId = 0;
  8022. this.receiveShadows = false;
  8023. this.renderOutline = false;
  8024. this.outlineColor = BABYLON.Color3.Red();
  8025. this.outlineWidth = 0.02;
  8026. this.renderOverlay = false;
  8027. this.overlayColor = BABYLON.Color3.Red();
  8028. this.overlayAlpha = 0.5;
  8029. this.hasVertexAlpha = false;
  8030. this.useVertexColors = true;
  8031. this.applyFog = true;
  8032. this.computeBonesUsingShaders = true;
  8033. this.scalingDeterminant = 1;
  8034. this.numBoneInfluencers = 4;
  8035. this.useOctreeForRenderingSelection = true;
  8036. this.useOctreeForPicking = true;
  8037. this.useOctreeForCollisions = true;
  8038. this.layerMask = 0x0FFFFFFF;
  8039. this.alwaysSelectAsActiveMesh = false;
  8040. // Collisions
  8041. this._checkCollisions = false;
  8042. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8043. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8044. this._collider = new BABYLON.Collider();
  8045. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8046. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8047. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8048. // Edges
  8049. this.edgesWidth = 1;
  8050. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8051. // Cache
  8052. this._localWorld = BABYLON.Matrix.Zero();
  8053. this._worldMatrix = BABYLON.Matrix.Zero();
  8054. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8055. this._absolutePosition = BABYLON.Vector3.Zero();
  8056. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8057. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8058. this._isDirty = false;
  8059. this._pivotMatrix = BABYLON.Matrix.Identity();
  8060. this._isDisposed = false;
  8061. this._renderId = 0;
  8062. this._intersectionsInProgress = new Array();
  8063. this._onAfterWorldMatrixUpdate = new Array();
  8064. this._isWorldMatrixFrozen = false;
  8065. this._unIndexed = false;
  8066. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8067. if (collidedMesh === void 0) { collidedMesh = null; }
  8068. //TODO move this to the collision coordinator!
  8069. if (_this.getScene().workerCollisions)
  8070. newPosition.multiplyInPlace(_this._collider.radius);
  8071. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8072. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8073. _this.position.addInPlace(_this._diffPositionForCollisions);
  8074. }
  8075. if (_this.onCollide && collidedMesh) {
  8076. _this.onCollide(collidedMesh);
  8077. }
  8078. if (_this.onCollisionPositionChange) {
  8079. _this.onCollisionPositionChange(_this.position);
  8080. }
  8081. };
  8082. scene.addMesh(this);
  8083. }
  8084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8085. get: function () {
  8086. return AbstractMesh._BILLBOARDMODE_NONE;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8092. get: function () {
  8093. return AbstractMesh._BILLBOARDMODE_X;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8099. get: function () {
  8100. return AbstractMesh._BILLBOARDMODE_Y;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8106. get: function () {
  8107. return AbstractMesh._BILLBOARDMODE_Z;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8113. get: function () {
  8114. return AbstractMesh._BILLBOARDMODE_ALL;
  8115. },
  8116. enumerable: true,
  8117. configurable: true
  8118. });
  8119. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8120. get: function () {
  8121. return this._skeleton;
  8122. },
  8123. set: function (value) {
  8124. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8125. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8126. }
  8127. if (value && value.needInitialSkinMatrix) {
  8128. value._registerMeshWithPoseMatrix(this);
  8129. }
  8130. this._skeleton = value;
  8131. if (!this._skeleton) {
  8132. this._bonesTransformMatrices = null;
  8133. }
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8139. /**
  8140. * Getting the rotation object.
  8141. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8142. */
  8143. get: function () {
  8144. return this._rotation;
  8145. },
  8146. set: function (newRotation) {
  8147. this._rotation = newRotation;
  8148. },
  8149. enumerable: true,
  8150. configurable: true
  8151. });
  8152. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8153. get: function () {
  8154. return this._scaling;
  8155. },
  8156. set: function (newScaling) {
  8157. this._scaling = newScaling;
  8158. if (this.physicsImpostor) {
  8159. this.physicsImpostor.forceUpdate();
  8160. }
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8166. get: function () {
  8167. return this._rotationQuaternion;
  8168. },
  8169. set: function (quaternion) {
  8170. this._rotationQuaternion = quaternion;
  8171. //reset the rotation vector.
  8172. if (this.rotation.length()) {
  8173. this.rotation.copyFromFloats(0, 0, 0);
  8174. }
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. // Methods
  8180. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8181. this._poseMatrix.copyFrom(matrix);
  8182. };
  8183. AbstractMesh.prototype.getPoseMatrix = function () {
  8184. return this._poseMatrix;
  8185. };
  8186. AbstractMesh.prototype.disableEdgesRendering = function () {
  8187. if (this._edgesRenderer !== undefined) {
  8188. this._edgesRenderer.dispose();
  8189. this._edgesRenderer = undefined;
  8190. }
  8191. };
  8192. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8193. if (epsilon === void 0) { epsilon = 0.95; }
  8194. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8195. this.disableEdgesRendering();
  8196. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8197. };
  8198. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8199. get: function () {
  8200. return false;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. AbstractMesh.prototype.getLOD = function (camera) {
  8206. return this;
  8207. };
  8208. AbstractMesh.prototype.getTotalVertices = function () {
  8209. return 0;
  8210. };
  8211. AbstractMesh.prototype.getIndices = function () {
  8212. return null;
  8213. };
  8214. AbstractMesh.prototype.getVerticesData = function (kind) {
  8215. return null;
  8216. };
  8217. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8218. return false;
  8219. };
  8220. AbstractMesh.prototype.getBoundingInfo = function () {
  8221. if (this._masterMesh) {
  8222. return this._masterMesh.getBoundingInfo();
  8223. }
  8224. if (!this._boundingInfo) {
  8225. this._updateBoundingInfo();
  8226. }
  8227. return this._boundingInfo;
  8228. };
  8229. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8230. get: function () {
  8231. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. AbstractMesh.prototype._preActivate = function () {
  8237. };
  8238. AbstractMesh.prototype._activate = function (renderId) {
  8239. this._renderId = renderId;
  8240. };
  8241. AbstractMesh.prototype.getWorldMatrix = function () {
  8242. if (this._masterMesh) {
  8243. return this._masterMesh.getWorldMatrix();
  8244. }
  8245. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8246. this.computeWorldMatrix();
  8247. }
  8248. return this._worldMatrix;
  8249. };
  8250. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8251. get: function () {
  8252. return this._worldMatrix;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8258. get: function () {
  8259. return this._absolutePosition;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8265. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8266. this.computeWorldMatrix(true);
  8267. this._isWorldMatrixFrozen = true;
  8268. };
  8269. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8270. this._isWorldMatrixFrozen = false;
  8271. this.computeWorldMatrix(true);
  8272. };
  8273. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8274. get: function () {
  8275. return this._isWorldMatrixFrozen;
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8281. axis.normalize();
  8282. if (!this.rotationQuaternion) {
  8283. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8284. this.rotation = BABYLON.Vector3.Zero();
  8285. }
  8286. var rotationQuaternion;
  8287. if (!space || space === BABYLON.Space.LOCAL) {
  8288. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8289. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8290. }
  8291. else {
  8292. if (this.parent) {
  8293. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8294. invertParentWorldMatrix.invert();
  8295. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8296. }
  8297. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8298. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8299. }
  8300. };
  8301. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8302. var displacementVector = axis.scale(distance);
  8303. if (!space || space === BABYLON.Space.LOCAL) {
  8304. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8305. this.setPositionWithLocalVector(tempV3);
  8306. }
  8307. else {
  8308. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8309. }
  8310. };
  8311. AbstractMesh.prototype.getAbsolutePosition = function () {
  8312. this.computeWorldMatrix();
  8313. return this._absolutePosition;
  8314. };
  8315. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8316. if (!absolutePosition) {
  8317. return;
  8318. }
  8319. var absolutePositionX;
  8320. var absolutePositionY;
  8321. var absolutePositionZ;
  8322. if (absolutePosition.x === undefined) {
  8323. if (arguments.length < 3) {
  8324. return;
  8325. }
  8326. absolutePositionX = arguments[0];
  8327. absolutePositionY = arguments[1];
  8328. absolutePositionZ = arguments[2];
  8329. }
  8330. else {
  8331. absolutePositionX = absolutePosition.x;
  8332. absolutePositionY = absolutePosition.y;
  8333. absolutePositionZ = absolutePosition.z;
  8334. }
  8335. if (this.parent) {
  8336. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8337. invertParentWorldMatrix.invert();
  8338. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8339. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8340. }
  8341. else {
  8342. this.position.x = absolutePositionX;
  8343. this.position.y = absolutePositionY;
  8344. this.position.z = absolutePositionZ;
  8345. }
  8346. };
  8347. // ================================== Point of View Movement =================================
  8348. /**
  8349. * Perform relative position change from the point of view of behind the front of the mesh.
  8350. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8351. * Supports definition of mesh facing forward or backward.
  8352. * @param {number} amountRight
  8353. * @param {number} amountUp
  8354. * @param {number} amountForward
  8355. */
  8356. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8357. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8358. };
  8359. /**
  8360. * Calculate relative position change from the point of view of behind the front of the mesh.
  8361. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8362. * Supports definition of mesh facing forward or backward.
  8363. * @param {number} amountRight
  8364. * @param {number} amountUp
  8365. * @param {number} amountForward
  8366. */
  8367. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8368. var rotMatrix = new BABYLON.Matrix();
  8369. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8370. rotQuaternion.toRotationMatrix(rotMatrix);
  8371. var translationDelta = BABYLON.Vector3.Zero();
  8372. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8374. return translationDelta;
  8375. };
  8376. // ================================== Point of View Rotation =================================
  8377. /**
  8378. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8379. * Supports definition of mesh facing forward or backward.
  8380. * @param {number} flipBack
  8381. * @param {number} twirlClockwise
  8382. * @param {number} tiltRight
  8383. */
  8384. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8385. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8386. };
  8387. /**
  8388. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8389. * Supports definition of mesh facing forward or backward.
  8390. * @param {number} flipBack
  8391. * @param {number} twirlClockwise
  8392. * @param {number} tiltRight
  8393. */
  8394. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8395. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8396. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8397. };
  8398. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8399. this._pivotMatrix = matrix;
  8400. this._cache.pivotMatrixUpdated = true;
  8401. };
  8402. AbstractMesh.prototype.getPivotMatrix = function () {
  8403. return this._pivotMatrix;
  8404. };
  8405. AbstractMesh.prototype._isSynchronized = function () {
  8406. if (this._isDirty) {
  8407. return false;
  8408. }
  8409. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8410. return false;
  8411. if (this._cache.pivotMatrixUpdated) {
  8412. return false;
  8413. }
  8414. if (this.infiniteDistance) {
  8415. return false;
  8416. }
  8417. if (!this._cache.position.equals(this.position))
  8418. return false;
  8419. if (this.rotationQuaternion) {
  8420. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8421. return false;
  8422. }
  8423. else {
  8424. if (!this._cache.rotation.equals(this.rotation))
  8425. return false;
  8426. }
  8427. if (!this._cache.scaling.equals(this.scaling))
  8428. return false;
  8429. return true;
  8430. };
  8431. AbstractMesh.prototype._initCache = function () {
  8432. _super.prototype._initCache.call(this);
  8433. this._cache.localMatrixUpdated = false;
  8434. this._cache.position = BABYLON.Vector3.Zero();
  8435. this._cache.scaling = BABYLON.Vector3.Zero();
  8436. this._cache.rotation = BABYLON.Vector3.Zero();
  8437. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8438. this._cache.billboardMode = -1;
  8439. };
  8440. AbstractMesh.prototype.markAsDirty = function (property) {
  8441. if (property === "rotation") {
  8442. this.rotationQuaternion = null;
  8443. }
  8444. this._currentRenderId = Number.MAX_VALUE;
  8445. this._isDirty = true;
  8446. };
  8447. AbstractMesh.prototype._updateBoundingInfo = function () {
  8448. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8449. this._boundingInfo.update(this.worldMatrixFromCache);
  8450. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8451. };
  8452. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8453. if (!this.subMeshes) {
  8454. return;
  8455. }
  8456. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8457. var subMesh = this.subMeshes[subIndex];
  8458. if (!subMesh.IsGlobal) {
  8459. subMesh.updateBoundingInfo(matrix);
  8460. }
  8461. }
  8462. };
  8463. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8464. if (this._isWorldMatrixFrozen) {
  8465. return this._worldMatrix;
  8466. }
  8467. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8468. this._currentRenderId = this.getScene().getRenderId();
  8469. return this._worldMatrix;
  8470. }
  8471. this._cache.position.copyFrom(this.position);
  8472. this._cache.scaling.copyFrom(this.scaling);
  8473. this._cache.pivotMatrixUpdated = false;
  8474. this._cache.billboardMode = this.billboardMode;
  8475. this._currentRenderId = this.getScene().getRenderId();
  8476. this._isDirty = false;
  8477. // Scaling
  8478. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8479. // Rotation
  8480. //rotate, if quaternion is set and rotation was used
  8481. if (this.rotationQuaternion) {
  8482. var len = this.rotation.length();
  8483. if (len) {
  8484. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8485. this.rotation.copyFromFloats(0, 0, 0);
  8486. }
  8487. }
  8488. if (this.rotationQuaternion) {
  8489. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8490. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8491. }
  8492. else {
  8493. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8494. this._cache.rotation.copyFrom(this.rotation);
  8495. }
  8496. // Translation
  8497. if (this.infiniteDistance && !this.parent) {
  8498. var camera = this.getScene().activeCamera;
  8499. if (camera) {
  8500. var cameraWorldMatrix = camera.getWorldMatrix();
  8501. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8502. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8503. }
  8504. }
  8505. else {
  8506. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8507. }
  8508. // Composing transformations
  8509. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8510. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8511. // Billboarding
  8512. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8513. var localPosition = this.position.clone();
  8514. var zero = this.getScene().activeCamera.globalPosition.clone();
  8515. if (this.parent && this.parent.position) {
  8516. localPosition.addInPlace(this.parent.position);
  8517. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8518. }
  8519. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8520. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8521. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8522. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8523. zero.y = localPosition.y + 0.001;
  8524. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8525. zero.z = localPosition.z + 0.001;
  8526. }
  8527. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8528. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8529. BABYLON.Tmp.Matrix[3].invert();
  8530. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8531. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8532. }
  8533. // Local world
  8534. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8535. // Parent
  8536. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8537. this._markSyncedWithParent();
  8538. if (this._meshToBoneReferal) {
  8539. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8540. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8541. }
  8542. else {
  8543. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8544. }
  8545. }
  8546. else {
  8547. this._worldMatrix.copyFrom(this._localWorld);
  8548. }
  8549. // Bounding info
  8550. this._updateBoundingInfo();
  8551. // Absolute position
  8552. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8553. // Callbacks
  8554. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8555. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8556. }
  8557. if (!this._poseMatrix) {
  8558. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8559. }
  8560. return this._worldMatrix;
  8561. };
  8562. /**
  8563. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8564. * @param func: callback function to add
  8565. */
  8566. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8567. this._onAfterWorldMatrixUpdate.push(func);
  8568. };
  8569. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8570. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8571. if (index > -1) {
  8572. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8573. }
  8574. };
  8575. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8576. this.computeWorldMatrix();
  8577. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8578. };
  8579. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8580. this.computeWorldMatrix();
  8581. var invLocalWorldMatrix = this._localWorld.clone();
  8582. invLocalWorldMatrix.invert();
  8583. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8584. };
  8585. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8586. this.computeWorldMatrix(true);
  8587. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8588. };
  8589. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8590. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8591. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8592. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8593. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8594. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8595. /// <returns>Mesh oriented towards targetMesh</returns>
  8596. yawCor = yawCor || 0; // default to zero if undefined
  8597. pitchCor = pitchCor || 0;
  8598. rollCor = rollCor || 0;
  8599. var dv = targetPoint.subtract(this.position);
  8600. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8601. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8602. var pitch = Math.atan2(dv.y, len);
  8603. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8604. };
  8605. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8606. this._meshToBoneReferal = affectedMesh;
  8607. this.parent = bone;
  8608. if (bone.getWorldMatrix().determinant() < 0) {
  8609. this.scalingDeterminant *= -1;
  8610. }
  8611. };
  8612. AbstractMesh.prototype.detachFromBone = function () {
  8613. if (this.parent.getWorldMatrix().determinant() < 0) {
  8614. this.scalingDeterminant *= -1;
  8615. }
  8616. this._meshToBoneReferal = null;
  8617. this.parent = null;
  8618. };
  8619. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8620. return this._boundingInfo.isInFrustum(frustumPlanes);
  8621. };
  8622. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8623. if (!camera) {
  8624. camera = this.getScene().activeCamera;
  8625. }
  8626. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8627. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8628. return false;
  8629. }
  8630. return true;
  8631. };
  8632. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8633. if (!this._boundingInfo || !mesh._boundingInfo) {
  8634. return false;
  8635. }
  8636. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8637. };
  8638. AbstractMesh.prototype.intersectsPoint = function (point) {
  8639. if (!this._boundingInfo) {
  8640. return false;
  8641. }
  8642. return this._boundingInfo.intersectsPoint(point);
  8643. };
  8644. // Physics
  8645. /**
  8646. * @Deprecated. Use new PhysicsImpostor instead.
  8647. * */
  8648. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8649. //legacy support
  8650. if (impostor.impostor) {
  8651. options = impostor;
  8652. impostor = impostor.impostor;
  8653. }
  8654. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8655. return this.physicsImpostor.physicsBody;
  8656. };
  8657. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8658. return this.physicsImpostor;
  8659. };
  8660. /**
  8661. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8662. */
  8663. AbstractMesh.prototype.getPhysicsMass = function () {
  8664. return this.physicsImpostor.getParam("mass");
  8665. };
  8666. /**
  8667. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8668. */
  8669. AbstractMesh.prototype.getPhysicsFriction = function () {
  8670. return this.physicsImpostor.getParam("friction");
  8671. };
  8672. /**
  8673. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8674. */
  8675. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8676. return this.physicsImpostor.getParam("resitution");
  8677. };
  8678. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8679. if (!camera) {
  8680. camera = this.getScene().activeCamera;
  8681. }
  8682. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8683. };
  8684. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8685. if (!camera) {
  8686. camera = this.getScene().activeCamera;
  8687. }
  8688. return this.absolutePosition.subtract(camera.position).length();
  8689. };
  8690. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8691. if (!this.physicsImpostor) {
  8692. return;
  8693. }
  8694. this.physicsImpostor.applyImpulse(force, contactPoint);
  8695. };
  8696. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8697. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8698. return;
  8699. }
  8700. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8701. mainPivot: pivot1,
  8702. connectedPivot: pivot2,
  8703. nativeParams: options
  8704. });
  8705. };
  8706. /**
  8707. * @Deprecated
  8708. */
  8709. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8710. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8711. this.updatePhysicsBody();
  8712. };
  8713. /**
  8714. * @Deprecated
  8715. * Calling this function is not needed anymore.
  8716. * The physics engine takes care of transofmration automatically.
  8717. */
  8718. AbstractMesh.prototype.updatePhysicsBody = function () {
  8719. //Unneeded
  8720. };
  8721. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8722. // Collisions
  8723. get: function () {
  8724. return this._checkCollisions;
  8725. },
  8726. set: function (collisionEnabled) {
  8727. this._checkCollisions = collisionEnabled;
  8728. if (this.getScene().workerCollisions) {
  8729. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8730. }
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8736. var globalPosition = this.getAbsolutePosition();
  8737. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8738. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8739. this._collider.radius = this.ellipsoid;
  8740. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8741. };
  8742. // Submeshes octree
  8743. /**
  8744. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8745. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8746. */
  8747. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8748. if (maxCapacity === void 0) { maxCapacity = 64; }
  8749. if (maxDepth === void 0) { maxDepth = 2; }
  8750. if (!this._submeshesOctree) {
  8751. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8752. }
  8753. this.computeWorldMatrix(true);
  8754. // Update octree
  8755. var bbox = this.getBoundingInfo().boundingBox;
  8756. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8757. return this._submeshesOctree;
  8758. };
  8759. // Collisions
  8760. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8761. this._generatePointsArray();
  8762. // Transformation
  8763. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8764. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8765. subMesh._lastColliderWorldVertices = [];
  8766. subMesh._trianglePlanes = [];
  8767. var start = subMesh.verticesStart;
  8768. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8769. for (var i = start; i < end; i++) {
  8770. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8771. }
  8772. }
  8773. // Collide
  8774. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8775. if (collider.collisionFound) {
  8776. collider.collidedMesh = this;
  8777. }
  8778. };
  8779. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8780. var subMeshes;
  8781. var len;
  8782. // Octrees
  8783. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8784. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8785. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8786. len = intersections.length;
  8787. subMeshes = intersections.data;
  8788. }
  8789. else {
  8790. subMeshes = this.subMeshes;
  8791. len = subMeshes.length;
  8792. }
  8793. for (var index = 0; index < len; index++) {
  8794. var subMesh = subMeshes[index];
  8795. // Bounding test
  8796. if (len > 1 && !subMesh._checkCollision(collider))
  8797. continue;
  8798. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8799. }
  8800. };
  8801. AbstractMesh.prototype._checkCollision = function (collider) {
  8802. // Bounding box test
  8803. if (!this._boundingInfo._checkCollision(collider))
  8804. return;
  8805. // Transformation matrix
  8806. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8807. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8808. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8809. };
  8810. // Picking
  8811. AbstractMesh.prototype._generatePointsArray = function () {
  8812. return false;
  8813. };
  8814. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8815. var pickingInfo = new BABYLON.PickingInfo();
  8816. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8817. return pickingInfo;
  8818. }
  8819. if (!this._generatePointsArray()) {
  8820. return pickingInfo;
  8821. }
  8822. var intersectInfo = null;
  8823. // Octrees
  8824. var subMeshes;
  8825. var len;
  8826. if (this._submeshesOctree && this.useOctreeForPicking) {
  8827. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8828. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8829. len = intersections.length;
  8830. subMeshes = intersections.data;
  8831. }
  8832. else {
  8833. subMeshes = this.subMeshes;
  8834. len = subMeshes.length;
  8835. }
  8836. for (var index = 0; index < len; index++) {
  8837. var subMesh = subMeshes[index];
  8838. // Bounding test
  8839. if (len > 1 && !subMesh.canIntersects(ray))
  8840. continue;
  8841. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8842. if (currentIntersectInfo) {
  8843. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8844. intersectInfo = currentIntersectInfo;
  8845. intersectInfo.subMeshId = index;
  8846. if (fastCheck) {
  8847. break;
  8848. }
  8849. }
  8850. }
  8851. }
  8852. if (intersectInfo) {
  8853. // Get picked point
  8854. var world = this.getWorldMatrix();
  8855. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8856. var direction = ray.direction.clone();
  8857. direction = direction.scale(intersectInfo.distance);
  8858. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8859. var pickedPoint = worldOrigin.add(worldDirection);
  8860. // Return result
  8861. pickingInfo.hit = true;
  8862. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8863. pickingInfo.pickedPoint = pickedPoint;
  8864. pickingInfo.pickedMesh = this;
  8865. pickingInfo.bu = intersectInfo.bu;
  8866. pickingInfo.bv = intersectInfo.bv;
  8867. pickingInfo.faceId = intersectInfo.faceId;
  8868. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8869. return pickingInfo;
  8870. }
  8871. return pickingInfo;
  8872. };
  8873. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8874. return null;
  8875. };
  8876. AbstractMesh.prototype.releaseSubMeshes = function () {
  8877. if (this.subMeshes) {
  8878. while (this.subMeshes.length) {
  8879. this.subMeshes[0].dispose();
  8880. }
  8881. }
  8882. else {
  8883. this.subMeshes = new Array();
  8884. }
  8885. };
  8886. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8887. var index;
  8888. // Action manager
  8889. if (this.actionManager) {
  8890. this.actionManager.dispose();
  8891. this.actionManager = null;
  8892. }
  8893. // Skeleton
  8894. this.skeleton = null;
  8895. // Animations
  8896. this.getScene().stopAnimation(this);
  8897. // Physics
  8898. if (this.physicsImpostor) {
  8899. this.physicsImpostor.dispose(!doNotRecurse);
  8900. }
  8901. // Intersections in progress
  8902. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8903. var other = this._intersectionsInProgress[index];
  8904. var pos = other._intersectionsInProgress.indexOf(this);
  8905. other._intersectionsInProgress.splice(pos, 1);
  8906. }
  8907. this._intersectionsInProgress = [];
  8908. // Edges
  8909. if (this._edgesRenderer) {
  8910. this._edgesRenderer.dispose();
  8911. this._edgesRenderer = null;
  8912. }
  8913. // SubMeshes
  8914. this.releaseSubMeshes();
  8915. // Remove from scene
  8916. this.getScene().removeMesh(this);
  8917. if (!doNotRecurse) {
  8918. // Particles
  8919. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8920. if (this.getScene().particleSystems[index].emitter === this) {
  8921. this.getScene().particleSystems[index].dispose();
  8922. index--;
  8923. }
  8924. }
  8925. // Children
  8926. var objects = this.getScene().meshes.slice(0);
  8927. for (index = 0; index < objects.length; index++) {
  8928. if (objects[index].parent === this) {
  8929. objects[index].dispose();
  8930. }
  8931. }
  8932. }
  8933. else {
  8934. for (index = 0; index < this.getScene().meshes.length; index++) {
  8935. var obj = this.getScene().meshes[index];
  8936. if (obj.parent === this) {
  8937. obj.parent = null;
  8938. obj.computeWorldMatrix(true);
  8939. }
  8940. }
  8941. }
  8942. this._onAfterWorldMatrixUpdate = [];
  8943. this._isDisposed = true;
  8944. // Callback
  8945. if (this.onDispose) {
  8946. this.onDispose();
  8947. }
  8948. };
  8949. // Statics
  8950. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8951. AbstractMesh._BILLBOARDMODE_X = 1;
  8952. AbstractMesh._BILLBOARDMODE_Y = 2;
  8953. AbstractMesh._BILLBOARDMODE_Z = 4;
  8954. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8955. return AbstractMesh;
  8956. })(BABYLON.Node);
  8957. BABYLON.AbstractMesh = AbstractMesh;
  8958. })(BABYLON || (BABYLON = {}));
  8959. var BABYLON;
  8960. (function (BABYLON) {
  8961. var Light = (function (_super) {
  8962. __extends(Light, _super);
  8963. function Light(name, scene) {
  8964. _super.call(this, name, scene);
  8965. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8966. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8967. this.intensity = 1.0;
  8968. this.range = Number.MAX_VALUE;
  8969. this.includeOnlyWithLayerMask = 0;
  8970. this.includedOnlyMeshes = new Array();
  8971. this.excludedMeshes = new Array();
  8972. this.excludeWithLayerMask = 0;
  8973. // PBR Properties.
  8974. this.radius = 0.00001;
  8975. this._excludedMeshesIds = new Array();
  8976. this._includedOnlyMeshesIds = new Array();
  8977. scene.addLight(this);
  8978. }
  8979. Light.prototype.getShadowGenerator = function () {
  8980. return this._shadowGenerator;
  8981. };
  8982. Light.prototype.getAbsolutePosition = function () {
  8983. return BABYLON.Vector3.Zero();
  8984. };
  8985. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8986. };
  8987. Light.prototype._getWorldMatrix = function () {
  8988. return BABYLON.Matrix.Identity();
  8989. };
  8990. Light.prototype.canAffectMesh = function (mesh) {
  8991. if (!mesh) {
  8992. return true;
  8993. }
  8994. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8995. return false;
  8996. }
  8997. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8998. return false;
  8999. }
  9000. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9001. return false;
  9002. }
  9003. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9004. return false;
  9005. }
  9006. return true;
  9007. };
  9008. Light.prototype.getWorldMatrix = function () {
  9009. this._currentRenderId = this.getScene().getRenderId();
  9010. var worldMatrix = this._getWorldMatrix();
  9011. if (this.parent && this.parent.getWorldMatrix) {
  9012. if (!this._parentedWorldMatrix) {
  9013. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9014. }
  9015. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9016. this._markSyncedWithParent();
  9017. return this._parentedWorldMatrix;
  9018. }
  9019. return worldMatrix;
  9020. };
  9021. Light.prototype.dispose = function () {
  9022. if (this._shadowGenerator) {
  9023. this._shadowGenerator.dispose();
  9024. this._shadowGenerator = null;
  9025. }
  9026. // Animations
  9027. this.getScene().stopAnimation(this);
  9028. // Remove from scene
  9029. this.getScene().removeLight(this);
  9030. };
  9031. Light.prototype.getTypeID = function () {
  9032. return 0;
  9033. };
  9034. Light.prototype.clone = function (name) {
  9035. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9036. };
  9037. Light.prototype.serialize = function () {
  9038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9039. // Type
  9040. serializationObject.type = this.getTypeID();
  9041. // Parent
  9042. if (this.parent) {
  9043. serializationObject.parentId = this.parent.id;
  9044. }
  9045. return serializationObject;
  9046. };
  9047. Light.GetConstructorFromName = function (type, name, scene) {
  9048. switch (type) {
  9049. case 0:
  9050. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9051. case 1:
  9052. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9053. case 2:
  9054. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9055. case 3:
  9056. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9057. }
  9058. };
  9059. Light.Parse = function (parsedLight, scene) {
  9060. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9061. // Inclusion / exclusions
  9062. if (parsedLight.excludedMeshesIds) {
  9063. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9064. }
  9065. if (parsedLight.includedOnlyMeshesIds) {
  9066. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9067. }
  9068. // Parent
  9069. if (parsedLight.parentId) {
  9070. light._waitingParentId = parsedLight.parentId;
  9071. }
  9072. // Animations
  9073. if (parsedLight.animations) {
  9074. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9075. var parsedAnimation = parsedLight.animations[animationIndex];
  9076. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9077. }
  9078. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9079. }
  9080. if (parsedLight.autoAnimate) {
  9081. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9082. }
  9083. return light;
  9084. };
  9085. __decorate([
  9086. BABYLON.serializeAsColor3()
  9087. ], Light.prototype, "diffuse", void 0);
  9088. __decorate([
  9089. BABYLON.serializeAsColor3()
  9090. ], Light.prototype, "specular", void 0);
  9091. __decorate([
  9092. BABYLON.serialize()
  9093. ], Light.prototype, "intensity", void 0);
  9094. __decorate([
  9095. BABYLON.serialize()
  9096. ], Light.prototype, "range", void 0);
  9097. __decorate([
  9098. BABYLON.serialize()
  9099. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9100. __decorate([
  9101. BABYLON.serialize()
  9102. ], Light.prototype, "radius", void 0);
  9103. return Light;
  9104. })(BABYLON.Node);
  9105. BABYLON.Light = Light;
  9106. })(BABYLON || (BABYLON = {}));
  9107. var BABYLON;
  9108. (function (BABYLON) {
  9109. var PointLight = (function (_super) {
  9110. __extends(PointLight, _super);
  9111. function PointLight(name, position, scene) {
  9112. _super.call(this, name, scene);
  9113. this.position = position;
  9114. }
  9115. PointLight.prototype.getAbsolutePosition = function () {
  9116. return this.transformedPosition ? this.transformedPosition : this.position;
  9117. };
  9118. PointLight.prototype.computeTransformedPosition = function () {
  9119. if (this.parent && this.parent.getWorldMatrix) {
  9120. if (!this.transformedPosition) {
  9121. this.transformedPosition = BABYLON.Vector3.Zero();
  9122. }
  9123. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9124. return true;
  9125. }
  9126. return false;
  9127. };
  9128. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9129. if (this.parent && this.parent.getWorldMatrix) {
  9130. this.computeTransformedPosition();
  9131. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9132. return;
  9133. }
  9134. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9135. };
  9136. PointLight.prototype.needCube = function () {
  9137. return true;
  9138. };
  9139. PointLight.prototype.supportsVSM = function () {
  9140. return false;
  9141. };
  9142. PointLight.prototype.needRefreshPerFrame = function () {
  9143. return false;
  9144. };
  9145. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9146. switch (faceIndex) {
  9147. case 0:
  9148. return new BABYLON.Vector3(1, 0, 0);
  9149. case 1:
  9150. return new BABYLON.Vector3(-1, 0, 0);
  9151. case 2:
  9152. return new BABYLON.Vector3(0, -1, 0);
  9153. case 3:
  9154. return new BABYLON.Vector3(0, 1, 0);
  9155. case 4:
  9156. return new BABYLON.Vector3(0, 0, 1);
  9157. case 5:
  9158. return new BABYLON.Vector3(0, 0, -1);
  9159. }
  9160. return BABYLON.Vector3.Zero();
  9161. };
  9162. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9163. var activeCamera = this.getScene().activeCamera;
  9164. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9165. };
  9166. PointLight.prototype._getWorldMatrix = function () {
  9167. if (!this._worldMatrix) {
  9168. this._worldMatrix = BABYLON.Matrix.Identity();
  9169. }
  9170. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9171. return this._worldMatrix;
  9172. };
  9173. PointLight.prototype.getTypeID = function () {
  9174. return 0;
  9175. };
  9176. __decorate([
  9177. BABYLON.serializeAsVector3()
  9178. ], PointLight.prototype, "position", void 0);
  9179. return PointLight;
  9180. })(BABYLON.Light);
  9181. BABYLON.PointLight = PointLight;
  9182. })(BABYLON || (BABYLON = {}));
  9183. var BABYLON;
  9184. (function (BABYLON) {
  9185. var SpotLight = (function (_super) {
  9186. __extends(SpotLight, _super);
  9187. function SpotLight(name, position, direction, angle, exponent, scene) {
  9188. _super.call(this, name, scene);
  9189. this.position = position;
  9190. this.direction = direction;
  9191. this.angle = angle;
  9192. this.exponent = exponent;
  9193. }
  9194. SpotLight.prototype.getAbsolutePosition = function () {
  9195. return this.transformedPosition ? this.transformedPosition : this.position;
  9196. };
  9197. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9198. var activeCamera = this.getScene().activeCamera;
  9199. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9200. };
  9201. SpotLight.prototype.needCube = function () {
  9202. return false;
  9203. };
  9204. SpotLight.prototype.supportsVSM = function () {
  9205. return true;
  9206. };
  9207. SpotLight.prototype.needRefreshPerFrame = function () {
  9208. return false;
  9209. };
  9210. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9211. return this.direction;
  9212. };
  9213. SpotLight.prototype.setDirectionToTarget = function (target) {
  9214. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9215. return this.direction;
  9216. };
  9217. SpotLight.prototype.computeTransformedPosition = function () {
  9218. if (this.parent && this.parent.getWorldMatrix) {
  9219. if (!this.transformedPosition) {
  9220. this.transformedPosition = BABYLON.Vector3.Zero();
  9221. }
  9222. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9223. return true;
  9224. }
  9225. return false;
  9226. };
  9227. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9228. var normalizeDirection;
  9229. if (this.parent && this.parent.getWorldMatrix) {
  9230. if (!this._transformedDirection) {
  9231. this._transformedDirection = BABYLON.Vector3.Zero();
  9232. }
  9233. this.computeTransformedPosition();
  9234. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9235. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9236. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9237. }
  9238. else {
  9239. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9240. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9241. }
  9242. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9243. };
  9244. SpotLight.prototype._getWorldMatrix = function () {
  9245. if (!this._worldMatrix) {
  9246. this._worldMatrix = BABYLON.Matrix.Identity();
  9247. }
  9248. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9249. return this._worldMatrix;
  9250. };
  9251. SpotLight.prototype.getTypeID = function () {
  9252. return 2;
  9253. };
  9254. __decorate([
  9255. BABYLON.serializeAsVector3()
  9256. ], SpotLight.prototype, "position", void 0);
  9257. __decorate([
  9258. BABYLON.serializeAsVector3()
  9259. ], SpotLight.prototype, "direction", void 0);
  9260. __decorate([
  9261. BABYLON.serialize()
  9262. ], SpotLight.prototype, "angle", void 0);
  9263. __decorate([
  9264. BABYLON.serialize()
  9265. ], SpotLight.prototype, "exponent", void 0);
  9266. return SpotLight;
  9267. })(BABYLON.Light);
  9268. BABYLON.SpotLight = SpotLight;
  9269. })(BABYLON || (BABYLON = {}));
  9270. var BABYLON;
  9271. (function (BABYLON) {
  9272. var HemisphericLight = (function (_super) {
  9273. __extends(HemisphericLight, _super);
  9274. function HemisphericLight(name, direction, scene) {
  9275. _super.call(this, name, scene);
  9276. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9277. this.direction = direction;
  9278. }
  9279. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9280. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9281. return this.direction;
  9282. };
  9283. HemisphericLight.prototype.getShadowGenerator = function () {
  9284. return null;
  9285. };
  9286. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9287. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9288. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9289. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9290. };
  9291. HemisphericLight.prototype._getWorldMatrix = function () {
  9292. if (!this._worldMatrix) {
  9293. this._worldMatrix = BABYLON.Matrix.Identity();
  9294. }
  9295. return this._worldMatrix;
  9296. };
  9297. HemisphericLight.prototype.getTypeID = function () {
  9298. return 3;
  9299. };
  9300. __decorate([
  9301. BABYLON.serializeAsColor3()
  9302. ], HemisphericLight.prototype, "groundColor", void 0);
  9303. __decorate([
  9304. BABYLON.serializeAsVector3()
  9305. ], HemisphericLight.prototype, "direction", void 0);
  9306. return HemisphericLight;
  9307. })(BABYLON.Light);
  9308. BABYLON.HemisphericLight = HemisphericLight;
  9309. })(BABYLON || (BABYLON = {}));
  9310. var BABYLON;
  9311. (function (BABYLON) {
  9312. var DirectionalLight = (function (_super) {
  9313. __extends(DirectionalLight, _super);
  9314. function DirectionalLight(name, direction, scene) {
  9315. _super.call(this, name, scene);
  9316. this.shadowOrthoScale = 0.5;
  9317. this.autoUpdateExtends = true;
  9318. // Cache
  9319. this._orthoLeft = Number.MAX_VALUE;
  9320. this._orthoRight = Number.MIN_VALUE;
  9321. this._orthoTop = Number.MIN_VALUE;
  9322. this._orthoBottom = Number.MAX_VALUE;
  9323. this.position = direction.scale(-1);
  9324. this.direction = direction;
  9325. }
  9326. DirectionalLight.prototype.getAbsolutePosition = function () {
  9327. return this.transformedPosition ? this.transformedPosition : this.position;
  9328. };
  9329. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9330. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9331. return this.direction;
  9332. };
  9333. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9334. var activeCamera = this.getScene().activeCamera;
  9335. // Check extends
  9336. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9337. var tempVector3 = BABYLON.Vector3.Zero();
  9338. this._orthoLeft = Number.MAX_VALUE;
  9339. this._orthoRight = Number.MIN_VALUE;
  9340. this._orthoTop = Number.MIN_VALUE;
  9341. this._orthoBottom = Number.MAX_VALUE;
  9342. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9343. var mesh = renderList[meshIndex];
  9344. if (!mesh) {
  9345. continue;
  9346. }
  9347. var boundingInfo = mesh.getBoundingInfo();
  9348. if (!boundingInfo) {
  9349. continue;
  9350. }
  9351. var boundingBox = boundingInfo.boundingBox;
  9352. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9353. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9354. if (tempVector3.x < this._orthoLeft)
  9355. this._orthoLeft = tempVector3.x;
  9356. if (tempVector3.y < this._orthoBottom)
  9357. this._orthoBottom = tempVector3.y;
  9358. if (tempVector3.x > this._orthoRight)
  9359. this._orthoRight = tempVector3.x;
  9360. if (tempVector3.y > this._orthoTop)
  9361. this._orthoTop = tempVector3.y;
  9362. }
  9363. }
  9364. }
  9365. var xOffset = this._orthoRight - this._orthoLeft;
  9366. var yOffset = this._orthoTop - this._orthoBottom;
  9367. 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);
  9368. };
  9369. DirectionalLight.prototype.supportsVSM = function () {
  9370. return true;
  9371. };
  9372. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9373. return true;
  9374. };
  9375. DirectionalLight.prototype.needCube = function () {
  9376. return false;
  9377. };
  9378. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9379. return this.direction;
  9380. };
  9381. DirectionalLight.prototype.computeTransformedPosition = function () {
  9382. if (this.parent && this.parent.getWorldMatrix) {
  9383. if (!this.transformedPosition) {
  9384. this.transformedPosition = BABYLON.Vector3.Zero();
  9385. }
  9386. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9387. return true;
  9388. }
  9389. return false;
  9390. };
  9391. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9392. if (this.parent && this.parent.getWorldMatrix) {
  9393. if (!this._transformedDirection) {
  9394. this._transformedDirection = BABYLON.Vector3.Zero();
  9395. }
  9396. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9397. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9398. return;
  9399. }
  9400. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9401. };
  9402. DirectionalLight.prototype._getWorldMatrix = function () {
  9403. if (!this._worldMatrix) {
  9404. this._worldMatrix = BABYLON.Matrix.Identity();
  9405. }
  9406. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9407. return this._worldMatrix;
  9408. };
  9409. DirectionalLight.prototype.getTypeID = function () {
  9410. return 1;
  9411. };
  9412. __decorate([
  9413. BABYLON.serializeAsVector3()
  9414. ], DirectionalLight.prototype, "position", void 0);
  9415. __decorate([
  9416. BABYLON.serializeAsVector3()
  9417. ], DirectionalLight.prototype, "direction", void 0);
  9418. __decorate([
  9419. BABYLON.serialize()
  9420. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9421. __decorate([
  9422. BABYLON.serialize()
  9423. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9424. return DirectionalLight;
  9425. })(BABYLON.Light);
  9426. BABYLON.DirectionalLight = DirectionalLight;
  9427. })(BABYLON || (BABYLON = {}));
  9428. var BABYLON;
  9429. (function (BABYLON) {
  9430. var ShadowGenerator = (function () {
  9431. function ShadowGenerator(mapSize, light) {
  9432. var _this = this;
  9433. // Members
  9434. this._filter = ShadowGenerator.FILTER_NONE;
  9435. this.blurScale = 2;
  9436. this._blurBoxOffset = 0;
  9437. this._bias = 0.00005;
  9438. this._lightDirection = BABYLON.Vector3.Zero();
  9439. this.forceBackFacesOnly = false;
  9440. this._darkness = 0;
  9441. this._transparencyShadow = false;
  9442. this._viewMatrix = BABYLON.Matrix.Zero();
  9443. this._projectionMatrix = BABYLON.Matrix.Zero();
  9444. this._transformMatrix = BABYLON.Matrix.Zero();
  9445. this._worldViewProjection = BABYLON.Matrix.Zero();
  9446. this._currentFaceIndex = 0;
  9447. this._currentFaceIndexCache = 0;
  9448. this._light = light;
  9449. this._scene = light.getScene();
  9450. this._mapSize = mapSize;
  9451. light._shadowGenerator = this;
  9452. // Render target
  9453. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9454. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9455. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9456. this._shadowMap.anisotropicFilteringLevel = 1;
  9457. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9458. this._shadowMap.renderParticles = false;
  9459. this._shadowMap.onBeforeRender = function (faceIndex) {
  9460. _this._currentFaceIndex = faceIndex;
  9461. };
  9462. this._shadowMap.onAfterUnbind = function () {
  9463. if (!_this.useBlurVarianceShadowMap) {
  9464. return;
  9465. }
  9466. if (!_this._shadowMap2) {
  9467. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9468. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9469. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9470. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9471. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9472. _this._downSamplePostprocess.onApply = function (effect) {
  9473. effect.setTexture("textureSampler", _this._shadowMap);
  9474. };
  9475. _this.blurBoxOffset = 1;
  9476. }
  9477. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9478. };
  9479. // Custom render function
  9480. var renderSubMesh = function (subMesh) {
  9481. var mesh = subMesh.getRenderingMesh();
  9482. var scene = _this._scene;
  9483. var engine = scene.getEngine();
  9484. // Culling
  9485. engine.setState(subMesh.getMaterial().backFaceCulling);
  9486. // Managing instances
  9487. var batch = mesh._getInstancesRenderList(subMesh._id);
  9488. if (batch.mustReturn) {
  9489. return;
  9490. }
  9491. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9492. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9493. engine.enableEffect(_this._effect);
  9494. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9495. var material = subMesh.getMaterial();
  9496. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9497. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9498. if (_this.getLight().needCube()) {
  9499. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9500. }
  9501. // Alpha test
  9502. if (material && material.needAlphaTesting()) {
  9503. var alphaTexture = material.getAlphaTestTexture();
  9504. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9505. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9506. }
  9507. // Bones
  9508. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9509. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9510. }
  9511. if (_this.forceBackFacesOnly) {
  9512. engine.setState(true, 0, false, true);
  9513. }
  9514. // Draw
  9515. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9516. if (_this.forceBackFacesOnly) {
  9517. engine.setState(true, 0, false, false);
  9518. }
  9519. }
  9520. else {
  9521. // Need to reset refresh rate of the shadowMap
  9522. _this._shadowMap.resetRefreshCounter();
  9523. }
  9524. };
  9525. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9526. var index;
  9527. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9528. renderSubMesh(opaqueSubMeshes.data[index]);
  9529. }
  9530. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9531. renderSubMesh(alphaTestSubMeshes.data[index]);
  9532. }
  9533. if (_this._transparencyShadow) {
  9534. for (index = 0; index < transparentSubMeshes.length; index++) {
  9535. renderSubMesh(transparentSubMeshes.data[index]);
  9536. }
  9537. }
  9538. };
  9539. this._shadowMap.onClear = function (engine) {
  9540. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9541. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9542. }
  9543. else {
  9544. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9545. }
  9546. };
  9547. }
  9548. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9549. // Static
  9550. get: function () {
  9551. return ShadowGenerator._FILTER_NONE;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9557. get: function () {
  9558. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9564. get: function () {
  9565. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9571. get: function () {
  9572. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9578. get: function () {
  9579. return this._bias;
  9580. },
  9581. set: function (bias) {
  9582. this._bias = bias;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9588. get: function () {
  9589. return this._blurBoxOffset;
  9590. },
  9591. set: function (value) {
  9592. var _this = this;
  9593. if (this._blurBoxOffset === value) {
  9594. return;
  9595. }
  9596. this._blurBoxOffset = value;
  9597. if (this._boxBlurPostprocess) {
  9598. this._boxBlurPostprocess.dispose();
  9599. }
  9600. 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);
  9601. this._boxBlurPostprocess.onApply = function (effect) {
  9602. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9603. };
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9609. get: function () {
  9610. return this._filter;
  9611. },
  9612. set: function (value) {
  9613. if (this._filter === value) {
  9614. return;
  9615. }
  9616. this._filter = value;
  9617. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9618. this._shadowMap.anisotropicFilteringLevel = 16;
  9619. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9620. }
  9621. else {
  9622. this._shadowMap.anisotropicFilteringLevel = 1;
  9623. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9624. }
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9630. get: function () {
  9631. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9632. },
  9633. set: function (value) {
  9634. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9640. get: function () {
  9641. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9642. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9643. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9644. },
  9645. set: function (value) {
  9646. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9652. get: function () {
  9653. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9654. },
  9655. set: function (value) {
  9656. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9662. var defines = [];
  9663. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9664. defines.push("#define VSM");
  9665. }
  9666. if (this.getLight().needCube()) {
  9667. defines.push("#define CUBEMAP");
  9668. }
  9669. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9670. var mesh = subMesh.getMesh();
  9671. var material = subMesh.getMaterial();
  9672. // Alpha test
  9673. if (material && material.needAlphaTesting()) {
  9674. defines.push("#define ALPHATEST");
  9675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9676. attribs.push(BABYLON.VertexBuffer.UVKind);
  9677. defines.push("#define UV1");
  9678. }
  9679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9681. defines.push("#define UV2");
  9682. }
  9683. }
  9684. // Bones
  9685. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9686. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9687. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9688. if (mesh.numBoneInfluencers > 4) {
  9689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9691. }
  9692. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9693. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9694. }
  9695. else {
  9696. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9697. }
  9698. // Instances
  9699. if (useInstances) {
  9700. defines.push("#define INSTANCES");
  9701. attribs.push("world0");
  9702. attribs.push("world1");
  9703. attribs.push("world2");
  9704. attribs.push("world3");
  9705. }
  9706. // Get correct effect
  9707. var join = defines.join("\n");
  9708. if (this._cachedDefines !== join) {
  9709. this._cachedDefines = join;
  9710. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9711. }
  9712. return this._effect.isReady();
  9713. };
  9714. ShadowGenerator.prototype.getShadowMap = function () {
  9715. return this._shadowMap;
  9716. };
  9717. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9718. if (this._shadowMap2) {
  9719. return this._shadowMap2;
  9720. }
  9721. return this._shadowMap;
  9722. };
  9723. ShadowGenerator.prototype.getLight = function () {
  9724. return this._light;
  9725. };
  9726. // Methods
  9727. ShadowGenerator.prototype.getTransformMatrix = function () {
  9728. var scene = this._scene;
  9729. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9730. return this._transformMatrix;
  9731. }
  9732. this._currentRenderID = scene.getRenderId();
  9733. this._currentFaceIndexCache = this._currentFaceIndex;
  9734. var lightPosition = this._light.position;
  9735. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9736. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9737. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9738. }
  9739. if (this._light.computeTransformedPosition()) {
  9740. lightPosition = this._light.transformedPosition;
  9741. }
  9742. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9743. this._cachedPosition = lightPosition.clone();
  9744. this._cachedDirection = this._lightDirection.clone();
  9745. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9746. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9747. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9748. }
  9749. return this._transformMatrix;
  9750. };
  9751. ShadowGenerator.prototype.getDarkness = function () {
  9752. return this._darkness;
  9753. };
  9754. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9755. if (darkness >= 1.0)
  9756. this._darkness = 1.0;
  9757. else if (darkness <= 0.0)
  9758. this._darkness = 0.0;
  9759. else
  9760. this._darkness = darkness;
  9761. };
  9762. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9763. this._transparencyShadow = hasShadow;
  9764. };
  9765. ShadowGenerator.prototype._packHalf = function (depth) {
  9766. var scale = depth * 255.0;
  9767. var fract = scale - Math.floor(scale);
  9768. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9769. };
  9770. ShadowGenerator.prototype.dispose = function () {
  9771. this._shadowMap.dispose();
  9772. if (this._shadowMap2) {
  9773. this._shadowMap2.dispose();
  9774. }
  9775. if (this._downSamplePostprocess) {
  9776. this._downSamplePostprocess.dispose();
  9777. }
  9778. if (this._boxBlurPostprocess) {
  9779. this._boxBlurPostprocess.dispose();
  9780. }
  9781. };
  9782. ShadowGenerator.prototype.serialize = function () {
  9783. var serializationObject = {};
  9784. serializationObject.lightId = this._light.id;
  9785. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9786. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9787. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9788. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9789. serializationObject.renderList = [];
  9790. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9791. var mesh = this.getShadowMap().renderList[meshIndex];
  9792. serializationObject.renderList.push(mesh.id);
  9793. }
  9794. return serializationObject;
  9795. };
  9796. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9797. //casting to point light, as light is missing the position attr and typescript complains.
  9798. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9799. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9800. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9801. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9802. shadowGenerator.getShadowMap().renderList.push(mesh);
  9803. }
  9804. if (parsedShadowGenerator.usePoissonSampling) {
  9805. shadowGenerator.usePoissonSampling = true;
  9806. }
  9807. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9808. shadowGenerator.useVarianceShadowMap = true;
  9809. }
  9810. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9811. shadowGenerator.useBlurVarianceShadowMap = true;
  9812. if (parsedShadowGenerator.blurScale) {
  9813. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9814. }
  9815. if (parsedShadowGenerator.blurBoxOffset) {
  9816. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9817. }
  9818. }
  9819. if (parsedShadowGenerator.bias !== undefined) {
  9820. shadowGenerator.bias = parsedShadowGenerator.bias;
  9821. }
  9822. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9823. return shadowGenerator;
  9824. };
  9825. ShadowGenerator._FILTER_NONE = 0;
  9826. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9827. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9828. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9829. return ShadowGenerator;
  9830. })();
  9831. BABYLON.ShadowGenerator = ShadowGenerator;
  9832. })(BABYLON || (BABYLON = {}));
  9833. var BABYLON;
  9834. (function (BABYLON) {
  9835. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9836. if (boxMin.x > sphereCenter.x + sphereRadius)
  9837. return false;
  9838. if (sphereCenter.x - sphereRadius > boxMax.x)
  9839. return false;
  9840. if (boxMin.y > sphereCenter.y + sphereRadius)
  9841. return false;
  9842. if (sphereCenter.y - sphereRadius > boxMax.y)
  9843. return false;
  9844. if (boxMin.z > sphereCenter.z + sphereRadius)
  9845. return false;
  9846. if (sphereCenter.z - sphereRadius > boxMax.z)
  9847. return false;
  9848. return true;
  9849. };
  9850. var getLowestRoot = function (a, b, c, maxR) {
  9851. var determinant = b * b - 4.0 * a * c;
  9852. var result = { root: 0, found: false };
  9853. if (determinant < 0)
  9854. return result;
  9855. var sqrtD = Math.sqrt(determinant);
  9856. var r1 = (-b - sqrtD) / (2.0 * a);
  9857. var r2 = (-b + sqrtD) / (2.0 * a);
  9858. if (r1 > r2) {
  9859. var temp = r2;
  9860. r2 = r1;
  9861. r1 = temp;
  9862. }
  9863. if (r1 > 0 && r1 < maxR) {
  9864. result.root = r1;
  9865. result.found = true;
  9866. return result;
  9867. }
  9868. if (r2 > 0 && r2 < maxR) {
  9869. result.root = r2;
  9870. result.found = true;
  9871. return result;
  9872. }
  9873. return result;
  9874. };
  9875. var Collider = (function () {
  9876. function Collider() {
  9877. this.radius = new BABYLON.Vector3(1, 1, 1);
  9878. this.retry = 0;
  9879. this.basePointWorld = BABYLON.Vector3.Zero();
  9880. this.velocityWorld = BABYLON.Vector3.Zero();
  9881. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9882. this._collisionPoint = BABYLON.Vector3.Zero();
  9883. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9884. this._tempVector = BABYLON.Vector3.Zero();
  9885. this._tempVector2 = BABYLON.Vector3.Zero();
  9886. this._tempVector3 = BABYLON.Vector3.Zero();
  9887. this._tempVector4 = BABYLON.Vector3.Zero();
  9888. this._edge = BABYLON.Vector3.Zero();
  9889. this._baseToVertex = BABYLON.Vector3.Zero();
  9890. this._destinationPoint = BABYLON.Vector3.Zero();
  9891. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9892. this._displacementVector = BABYLON.Vector3.Zero();
  9893. }
  9894. // Methods
  9895. Collider.prototype._initialize = function (source, dir, e) {
  9896. this.velocity = dir;
  9897. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9898. this.basePoint = source;
  9899. source.multiplyToRef(this.radius, this.basePointWorld);
  9900. dir.multiplyToRef(this.radius, this.velocityWorld);
  9901. this.velocityWorldLength = this.velocityWorld.length();
  9902. this.epsilon = e;
  9903. this.collisionFound = false;
  9904. };
  9905. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9906. pa.subtractToRef(point, this._tempVector);
  9907. pb.subtractToRef(point, this._tempVector2);
  9908. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9909. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9910. if (d < 0)
  9911. return false;
  9912. pc.subtractToRef(point, this._tempVector3);
  9913. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9914. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9915. if (d < 0)
  9916. return false;
  9917. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9918. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9919. return d >= 0;
  9920. };
  9921. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9922. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9923. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9924. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9925. return false;
  9926. }
  9927. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9928. return false;
  9929. return true;
  9930. };
  9931. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9932. var t0;
  9933. var embeddedInPlane = false;
  9934. //defensive programming, actually not needed.
  9935. if (!trianglePlaneArray) {
  9936. trianglePlaneArray = [];
  9937. }
  9938. if (!trianglePlaneArray[faceIndex]) {
  9939. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9940. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9941. }
  9942. var trianglePlane = trianglePlaneArray[faceIndex];
  9943. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9944. return;
  9945. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9946. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9947. if (normalDotVelocity == 0) {
  9948. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9949. return;
  9950. embeddedInPlane = true;
  9951. t0 = 0;
  9952. }
  9953. else {
  9954. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9955. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9956. if (t0 > t1) {
  9957. var temp = t1;
  9958. t1 = t0;
  9959. t0 = temp;
  9960. }
  9961. if (t0 > 1.0 || t1 < 0.0)
  9962. return;
  9963. if (t0 < 0)
  9964. t0 = 0;
  9965. if (t0 > 1.0)
  9966. t0 = 1.0;
  9967. }
  9968. this._collisionPoint.copyFromFloats(0, 0, 0);
  9969. var found = false;
  9970. var t = 1.0;
  9971. if (!embeddedInPlane) {
  9972. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9973. this.velocity.scaleToRef(t0, this._tempVector);
  9974. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9975. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9976. found = true;
  9977. t = t0;
  9978. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9979. }
  9980. }
  9981. if (!found) {
  9982. var velocitySquaredLength = this.velocity.lengthSquared();
  9983. var a = velocitySquaredLength;
  9984. this.basePoint.subtractToRef(p1, this._tempVector);
  9985. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9986. var c = this._tempVector.lengthSquared() - 1.0;
  9987. var lowestRoot = getLowestRoot(a, b, c, t);
  9988. if (lowestRoot.found) {
  9989. t = lowestRoot.root;
  9990. found = true;
  9991. this._collisionPoint.copyFrom(p1);
  9992. }
  9993. this.basePoint.subtractToRef(p2, this._tempVector);
  9994. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9995. c = this._tempVector.lengthSquared() - 1.0;
  9996. lowestRoot = getLowestRoot(a, b, c, t);
  9997. if (lowestRoot.found) {
  9998. t = lowestRoot.root;
  9999. found = true;
  10000. this._collisionPoint.copyFrom(p2);
  10001. }
  10002. this.basePoint.subtractToRef(p3, this._tempVector);
  10003. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10004. c = this._tempVector.lengthSquared() - 1.0;
  10005. lowestRoot = getLowestRoot(a, b, c, t);
  10006. if (lowestRoot.found) {
  10007. t = lowestRoot.root;
  10008. found = true;
  10009. this._collisionPoint.copyFrom(p3);
  10010. }
  10011. p2.subtractToRef(p1, this._edge);
  10012. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10013. var edgeSquaredLength = this._edge.lengthSquared();
  10014. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10015. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10016. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10017. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10018. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10019. lowestRoot = getLowestRoot(a, b, c, t);
  10020. if (lowestRoot.found) {
  10021. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10022. if (f >= 0.0 && f <= 1.0) {
  10023. t = lowestRoot.root;
  10024. found = true;
  10025. this._edge.scaleInPlace(f);
  10026. p1.addToRef(this._edge, this._collisionPoint);
  10027. }
  10028. }
  10029. p3.subtractToRef(p2, this._edge);
  10030. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10031. edgeSquaredLength = this._edge.lengthSquared();
  10032. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10033. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10034. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10035. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10036. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10037. lowestRoot = getLowestRoot(a, b, c, t);
  10038. if (lowestRoot.found) {
  10039. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10040. if (f >= 0.0 && f <= 1.0) {
  10041. t = lowestRoot.root;
  10042. found = true;
  10043. this._edge.scaleInPlace(f);
  10044. p2.addToRef(this._edge, this._collisionPoint);
  10045. }
  10046. }
  10047. p1.subtractToRef(p3, this._edge);
  10048. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10049. edgeSquaredLength = this._edge.lengthSquared();
  10050. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10051. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10052. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10053. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10054. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10055. lowestRoot = getLowestRoot(a, b, c, t);
  10056. if (lowestRoot.found) {
  10057. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10058. if (f >= 0.0 && f <= 1.0) {
  10059. t = lowestRoot.root;
  10060. found = true;
  10061. this._edge.scaleInPlace(f);
  10062. p3.addToRef(this._edge, this._collisionPoint);
  10063. }
  10064. }
  10065. }
  10066. if (found) {
  10067. var distToCollision = t * this.velocity.length();
  10068. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10069. if (!this.intersectionPoint) {
  10070. this.intersectionPoint = this._collisionPoint.clone();
  10071. }
  10072. else {
  10073. this.intersectionPoint.copyFrom(this._collisionPoint);
  10074. }
  10075. this.nearestDistance = distToCollision;
  10076. this.collisionFound = true;
  10077. }
  10078. }
  10079. };
  10080. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10081. for (var i = indexStart; i < indexEnd; i += 3) {
  10082. var p1 = pts[indices[i] - decal];
  10083. var p2 = pts[indices[i + 1] - decal];
  10084. var p3 = pts[indices[i + 2] - decal];
  10085. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10086. }
  10087. };
  10088. Collider.prototype._getResponse = function (pos, vel) {
  10089. pos.addToRef(vel, this._destinationPoint);
  10090. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10091. this.basePoint.addToRef(vel, pos);
  10092. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10093. this._slidePlaneNormal.normalize();
  10094. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10095. pos.addInPlace(this._displacementVector);
  10096. this.intersectionPoint.addInPlace(this._displacementVector);
  10097. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10098. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10099. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10100. };
  10101. return Collider;
  10102. })();
  10103. BABYLON.Collider = Collider;
  10104. })(BABYLON || (BABYLON = {}));
  10105. var BABYLON;
  10106. (function (BABYLON) {
  10107. //WebWorker code will be inserted to this variable.
  10108. BABYLON.CollisionWorker = "";
  10109. (function (WorkerTaskType) {
  10110. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10111. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10112. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10113. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10114. var WorkerTaskType = BABYLON.WorkerTaskType;
  10115. (function (WorkerReplyType) {
  10116. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10117. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10118. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10119. var WorkerReplyType = BABYLON.WorkerReplyType;
  10120. var CollisionCoordinatorWorker = (function () {
  10121. function CollisionCoordinatorWorker() {
  10122. var _this = this;
  10123. this._scaledPosition = BABYLON.Vector3.Zero();
  10124. this._scaledVelocity = BABYLON.Vector3.Zero();
  10125. this.onMeshUpdated = function (mesh) {
  10126. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10127. };
  10128. this.onGeometryUpdated = function (geometry) {
  10129. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10130. };
  10131. this._afterRender = function () {
  10132. if (!_this._init)
  10133. return;
  10134. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10135. return;
  10136. }
  10137. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10138. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10139. if (_this._runningUpdated > 4) {
  10140. return;
  10141. }
  10142. ++_this._runningUpdated;
  10143. var payload = {
  10144. updatedMeshes: _this._addUpdateMeshesList,
  10145. updatedGeometries: _this._addUpdateGeometriesList,
  10146. removedGeometries: _this._toRemoveGeometryArray,
  10147. removedMeshes: _this._toRemoveMeshesArray
  10148. };
  10149. var message = {
  10150. payload: payload,
  10151. taskType: WorkerTaskType.UPDATE
  10152. };
  10153. var serializable = [];
  10154. for (var id in payload.updatedGeometries) {
  10155. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10156. //prepare transferables
  10157. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10158. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10159. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10160. }
  10161. }
  10162. _this._worker.postMessage(message, serializable);
  10163. _this._addUpdateMeshesList = {};
  10164. _this._addUpdateGeometriesList = {};
  10165. _this._toRemoveGeometryArray = [];
  10166. _this._toRemoveMeshesArray = [];
  10167. };
  10168. this._onMessageFromWorker = function (e) {
  10169. var returnData = e.data;
  10170. if (returnData.error != WorkerReplyType.SUCCESS) {
  10171. //TODO what errors can be returned from the worker?
  10172. BABYLON.Tools.Warn("error returned from worker!");
  10173. return;
  10174. }
  10175. switch (returnData.taskType) {
  10176. case WorkerTaskType.INIT:
  10177. _this._init = true;
  10178. //Update the worked with ALL of the scene's current state
  10179. _this._scene.meshes.forEach(function (mesh) {
  10180. _this.onMeshAdded(mesh);
  10181. });
  10182. _this._scene.getGeometries().forEach(function (geometry) {
  10183. _this.onGeometryAdded(geometry);
  10184. });
  10185. break;
  10186. case WorkerTaskType.UPDATE:
  10187. _this._runningUpdated--;
  10188. break;
  10189. case WorkerTaskType.COLLIDE:
  10190. _this._runningCollisionTask = false;
  10191. var returnPayload = returnData.payload;
  10192. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10193. return;
  10194. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10195. //cleanup
  10196. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10197. break;
  10198. }
  10199. };
  10200. this._collisionsCallbackArray = [];
  10201. this._init = false;
  10202. this._runningUpdated = 0;
  10203. this._runningCollisionTask = false;
  10204. this._addUpdateMeshesList = {};
  10205. this._addUpdateGeometriesList = {};
  10206. this._toRemoveGeometryArray = [];
  10207. this._toRemoveMeshesArray = [];
  10208. }
  10209. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10210. if (!this._init)
  10211. return;
  10212. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10213. return;
  10214. position.divideToRef(collider.radius, this._scaledPosition);
  10215. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10216. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10217. var payload = {
  10218. collider: {
  10219. position: this._scaledPosition.asArray(),
  10220. velocity: this._scaledVelocity.asArray(),
  10221. radius: collider.radius.asArray()
  10222. },
  10223. collisionId: collisionIndex,
  10224. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10225. maximumRetry: maximumRetry
  10226. };
  10227. var message = {
  10228. payload: payload,
  10229. taskType: WorkerTaskType.COLLIDE
  10230. };
  10231. this._worker.postMessage(message);
  10232. };
  10233. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10234. this._scene = scene;
  10235. this._scene.registerAfterRender(this._afterRender);
  10236. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10237. this._worker = new Worker(workerUrl);
  10238. this._worker.onmessage = this._onMessageFromWorker;
  10239. var message = {
  10240. payload: {},
  10241. taskType: WorkerTaskType.INIT
  10242. };
  10243. this._worker.postMessage(message);
  10244. };
  10245. CollisionCoordinatorWorker.prototype.destroy = function () {
  10246. this._scene.unregisterAfterRender(this._afterRender);
  10247. this._worker.terminate();
  10248. };
  10249. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10250. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10251. this.onMeshUpdated(mesh);
  10252. };
  10253. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10254. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10255. };
  10256. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10257. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10258. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10259. this.onGeometryUpdated(geometry);
  10260. };
  10261. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10262. this._toRemoveGeometryArray.push(geometry.id);
  10263. };
  10264. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10265. var submeshes = [];
  10266. if (mesh.subMeshes) {
  10267. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10268. return {
  10269. position: idx,
  10270. verticesStart: sm.verticesStart,
  10271. verticesCount: sm.verticesCount,
  10272. indexStart: sm.indexStart,
  10273. indexCount: sm.indexCount,
  10274. hasMaterial: !!sm.getMaterial(),
  10275. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10276. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10277. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10278. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10279. };
  10280. });
  10281. }
  10282. var geometryId = null;
  10283. if (mesh instanceof BABYLON.Mesh) {
  10284. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10285. }
  10286. else if (mesh instanceof BABYLON.InstancedMesh) {
  10287. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10288. }
  10289. return {
  10290. uniqueId: mesh.uniqueId,
  10291. id: mesh.id,
  10292. name: mesh.name,
  10293. geometryId: geometryId,
  10294. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10295. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10296. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10297. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10298. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10299. subMeshes: submeshes,
  10300. checkCollisions: mesh.checkCollisions
  10301. };
  10302. };
  10303. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10304. return {
  10305. id: geometry.id,
  10306. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10307. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10308. indices: new Int32Array(geometry.getIndices() || []),
  10309. };
  10310. };
  10311. return CollisionCoordinatorWorker;
  10312. })();
  10313. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10314. var CollisionCoordinatorLegacy = (function () {
  10315. function CollisionCoordinatorLegacy() {
  10316. this._scaledPosition = BABYLON.Vector3.Zero();
  10317. this._scaledVelocity = BABYLON.Vector3.Zero();
  10318. this._finalPosition = BABYLON.Vector3.Zero();
  10319. }
  10320. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10321. position.divideToRef(collider.radius, this._scaledPosition);
  10322. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10323. collider.collidedMesh = null;
  10324. collider.retry = 0;
  10325. collider.initialVelocity = this._scaledVelocity;
  10326. collider.initialPosition = this._scaledPosition;
  10327. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10328. this._finalPosition.multiplyInPlace(collider.radius);
  10329. //run the callback
  10330. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10331. };
  10332. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10333. this._scene = scene;
  10334. };
  10335. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10336. //Legacy need no destruction method.
  10337. };
  10338. //No update in legacy mode
  10339. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10340. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10341. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10342. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10343. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10344. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10345. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10346. if (excludedMesh === void 0) { excludedMesh = null; }
  10347. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10348. if (collider.retry >= maximumRetry) {
  10349. finalPosition.copyFrom(position);
  10350. return;
  10351. }
  10352. collider._initialize(position, velocity, closeDistance);
  10353. // Check all meshes
  10354. for (var index = 0; index < this._scene.meshes.length; index++) {
  10355. var mesh = this._scene.meshes[index];
  10356. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10357. mesh._checkCollision(collider);
  10358. }
  10359. }
  10360. if (!collider.collisionFound) {
  10361. position.addToRef(velocity, finalPosition);
  10362. return;
  10363. }
  10364. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10365. collider._getResponse(position, velocity);
  10366. }
  10367. if (velocity.length() <= closeDistance) {
  10368. finalPosition.copyFrom(position);
  10369. return;
  10370. }
  10371. collider.retry++;
  10372. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10373. };
  10374. return CollisionCoordinatorLegacy;
  10375. })();
  10376. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10377. })(BABYLON || (BABYLON = {}));
  10378. var BABYLON;
  10379. (function (BABYLON) {
  10380. var Camera = (function (_super) {
  10381. __extends(Camera, _super);
  10382. function Camera(name, position, scene) {
  10383. _super.call(this, name, scene);
  10384. this.upVector = BABYLON.Vector3.Up();
  10385. this.orthoLeft = null;
  10386. this.orthoRight = null;
  10387. this.orthoBottom = null;
  10388. this.orthoTop = null;
  10389. this.fov = 0.8;
  10390. this.minZ = 1.0;
  10391. this.maxZ = 10000.0;
  10392. this.inertia = 0.9;
  10393. this.mode = Camera.PERSPECTIVE_CAMERA;
  10394. this.isIntermediate = false;
  10395. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10396. this.layerMask = 0x0FFFFFFF;
  10397. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10398. // Camera rig members
  10399. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10400. this._rigCameras = new Array();
  10401. // Cache
  10402. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10403. this._projectionMatrix = new BABYLON.Matrix();
  10404. this._postProcesses = new Array();
  10405. this._postProcessesTakenIndices = [];
  10406. this._activeMeshes = new BABYLON.SmartArray(256);
  10407. this._globalPosition = BABYLON.Vector3.Zero();
  10408. scene.addCamera(this);
  10409. if (!scene.activeCamera) {
  10410. scene.activeCamera = this;
  10411. }
  10412. this.position = position;
  10413. }
  10414. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10415. get: function () {
  10416. return Camera._PERSPECTIVE_CAMERA;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10422. get: function () {
  10423. return Camera._ORTHOGRAPHIC_CAMERA;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10429. get: function () {
  10430. return Camera._FOVMODE_VERTICAL_FIXED;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10436. get: function () {
  10437. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10443. get: function () {
  10444. return Camera._RIG_MODE_NONE;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10450. get: function () {
  10451. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10457. get: function () {
  10458. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10459. },
  10460. enumerable: true,
  10461. configurable: true
  10462. });
  10463. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10464. get: function () {
  10465. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10466. },
  10467. enumerable: true,
  10468. configurable: true
  10469. });
  10470. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10471. get: function () {
  10472. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10473. },
  10474. enumerable: true,
  10475. configurable: true
  10476. });
  10477. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10478. get: function () {
  10479. return Camera._RIG_MODE_VR;
  10480. },
  10481. enumerable: true,
  10482. configurable: true
  10483. });
  10484. Object.defineProperty(Camera.prototype, "globalPosition", {
  10485. get: function () {
  10486. return this._globalPosition;
  10487. },
  10488. enumerable: true,
  10489. configurable: true
  10490. });
  10491. Camera.prototype.getActiveMeshes = function () {
  10492. return this._activeMeshes;
  10493. };
  10494. Camera.prototype.isActiveMesh = function (mesh) {
  10495. return (this._activeMeshes.indexOf(mesh) !== -1);
  10496. };
  10497. //Cache
  10498. Camera.prototype._initCache = function () {
  10499. _super.prototype._initCache.call(this);
  10500. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10501. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10502. this._cache.mode = undefined;
  10503. this._cache.minZ = undefined;
  10504. this._cache.maxZ = undefined;
  10505. this._cache.fov = undefined;
  10506. this._cache.aspectRatio = undefined;
  10507. this._cache.orthoLeft = undefined;
  10508. this._cache.orthoRight = undefined;
  10509. this._cache.orthoBottom = undefined;
  10510. this._cache.orthoTop = undefined;
  10511. this._cache.renderWidth = undefined;
  10512. this._cache.renderHeight = undefined;
  10513. };
  10514. Camera.prototype._updateCache = function (ignoreParentClass) {
  10515. if (!ignoreParentClass) {
  10516. _super.prototype._updateCache.call(this);
  10517. }
  10518. var engine = this.getEngine();
  10519. this._cache.position.copyFrom(this.position);
  10520. this._cache.upVector.copyFrom(this.upVector);
  10521. this._cache.mode = this.mode;
  10522. this._cache.minZ = this.minZ;
  10523. this._cache.maxZ = this.maxZ;
  10524. this._cache.fov = this.fov;
  10525. this._cache.aspectRatio = engine.getAspectRatio(this);
  10526. this._cache.orthoLeft = this.orthoLeft;
  10527. this._cache.orthoRight = this.orthoRight;
  10528. this._cache.orthoBottom = this.orthoBottom;
  10529. this._cache.orthoTop = this.orthoTop;
  10530. this._cache.renderWidth = engine.getRenderWidth();
  10531. this._cache.renderHeight = engine.getRenderHeight();
  10532. };
  10533. Camera.prototype._updateFromScene = function () {
  10534. this.updateCache();
  10535. this._update();
  10536. };
  10537. // Synchronized
  10538. Camera.prototype._isSynchronized = function () {
  10539. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10540. };
  10541. Camera.prototype._isSynchronizedViewMatrix = function () {
  10542. if (!_super.prototype._isSynchronized.call(this))
  10543. return false;
  10544. return this._cache.position.equals(this.position)
  10545. && this._cache.upVector.equals(this.upVector)
  10546. && this.isSynchronizedWithParent();
  10547. };
  10548. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10549. var check = this._cache.mode === this.mode
  10550. && this._cache.minZ === this.minZ
  10551. && this._cache.maxZ === this.maxZ;
  10552. if (!check) {
  10553. return false;
  10554. }
  10555. var engine = this.getEngine();
  10556. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10557. check = this._cache.fov === this.fov
  10558. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10559. }
  10560. else {
  10561. check = this._cache.orthoLeft === this.orthoLeft
  10562. && this._cache.orthoRight === this.orthoRight
  10563. && this._cache.orthoBottom === this.orthoBottom
  10564. && this._cache.orthoTop === this.orthoTop
  10565. && this._cache.renderWidth === engine.getRenderWidth()
  10566. && this._cache.renderHeight === engine.getRenderHeight();
  10567. }
  10568. return check;
  10569. };
  10570. // Controls
  10571. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10572. };
  10573. Camera.prototype.detachControl = function (element) {
  10574. };
  10575. Camera.prototype._update = function () {
  10576. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10577. this._updateRigCameras();
  10578. }
  10579. this._checkInputs();
  10580. };
  10581. Camera.prototype._checkInputs = function () {
  10582. };
  10583. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10584. if (insertAt === void 0) { insertAt = null; }
  10585. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10586. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10587. return 0;
  10588. }
  10589. if (insertAt == null || insertAt < 0) {
  10590. this._postProcesses.push(postProcess);
  10591. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10592. return this._postProcesses.length - 1;
  10593. }
  10594. var add = 0;
  10595. var i;
  10596. var start;
  10597. if (this._postProcesses[insertAt]) {
  10598. start = this._postProcesses.length - 1;
  10599. for (i = start; i >= insertAt + 1; --i) {
  10600. this._postProcesses[i + 1] = this._postProcesses[i];
  10601. }
  10602. add = 1;
  10603. }
  10604. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10605. if (this._postProcessesTakenIndices[i] < insertAt) {
  10606. continue;
  10607. }
  10608. start = this._postProcessesTakenIndices.length - 1;
  10609. for (var j = start; j >= i; --j) {
  10610. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10611. }
  10612. this._postProcessesTakenIndices[i] = insertAt;
  10613. break;
  10614. }
  10615. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10616. this._postProcessesTakenIndices.push(insertAt);
  10617. }
  10618. var result = insertAt + add;
  10619. this._postProcesses[result] = postProcess;
  10620. return result;
  10621. };
  10622. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10623. if (atIndices === void 0) { atIndices = null; }
  10624. var result = [];
  10625. var i;
  10626. var index;
  10627. if (!atIndices) {
  10628. var length = this._postProcesses.length;
  10629. for (i = 0; i < length; i++) {
  10630. if (this._postProcesses[i] !== postProcess) {
  10631. continue;
  10632. }
  10633. delete this._postProcesses[i];
  10634. index = this._postProcessesTakenIndices.indexOf(i);
  10635. this._postProcessesTakenIndices.splice(index, 1);
  10636. }
  10637. }
  10638. else {
  10639. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10640. for (i = 0; i < atIndices.length; i++) {
  10641. var foundPostProcess = this._postProcesses[atIndices[i]];
  10642. if (foundPostProcess !== postProcess) {
  10643. result.push(i);
  10644. continue;
  10645. }
  10646. delete this._postProcesses[atIndices[i]];
  10647. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10648. this._postProcessesTakenIndices.splice(index, 1);
  10649. }
  10650. }
  10651. return result;
  10652. };
  10653. Camera.prototype.getWorldMatrix = function () {
  10654. if (!this._worldMatrix) {
  10655. this._worldMatrix = BABYLON.Matrix.Identity();
  10656. }
  10657. var viewMatrix = this.getViewMatrix();
  10658. viewMatrix.invertToRef(this._worldMatrix);
  10659. return this._worldMatrix;
  10660. };
  10661. Camera.prototype._getViewMatrix = function () {
  10662. return BABYLON.Matrix.Identity();
  10663. };
  10664. Camera.prototype.getViewMatrix = function (force) {
  10665. this._computedViewMatrix = this._computeViewMatrix(force);
  10666. if (!force && this._isSynchronizedViewMatrix()) {
  10667. return this._computedViewMatrix;
  10668. }
  10669. if (!this.parent || !this.parent.getWorldMatrix) {
  10670. this._globalPosition.copyFrom(this.position);
  10671. }
  10672. else {
  10673. if (!this._worldMatrix) {
  10674. this._worldMatrix = BABYLON.Matrix.Identity();
  10675. }
  10676. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10677. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10678. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10679. this._computedViewMatrix.invert();
  10680. this._markSyncedWithParent();
  10681. }
  10682. this._currentRenderId = this.getScene().getRenderId();
  10683. return this._computedViewMatrix;
  10684. };
  10685. Camera.prototype._computeViewMatrix = function (force) {
  10686. if (!force && this._isSynchronizedViewMatrix()) {
  10687. return this._computedViewMatrix;
  10688. }
  10689. this._computedViewMatrix = this._getViewMatrix();
  10690. this._currentRenderId = this.getScene().getRenderId();
  10691. return this._computedViewMatrix;
  10692. };
  10693. Camera.prototype.getProjectionMatrix = function (force) {
  10694. if (!force && this._isSynchronizedProjectionMatrix()) {
  10695. return this._projectionMatrix;
  10696. }
  10697. var engine = this.getEngine();
  10698. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10699. if (this.minZ <= 0) {
  10700. this.minZ = 0.1;
  10701. }
  10702. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10703. return this._projectionMatrix;
  10704. }
  10705. var halfWidth = engine.getRenderWidth() / 2.0;
  10706. var halfHeight = engine.getRenderHeight() / 2.0;
  10707. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10708. return this._projectionMatrix;
  10709. };
  10710. Camera.prototype.dispose = function () {
  10711. // Animations
  10712. this.getScene().stopAnimation(this);
  10713. // Remove from scene
  10714. this.getScene().removeCamera(this);
  10715. while (this._rigCameras.length > 0) {
  10716. this._rigCameras.pop().dispose();
  10717. }
  10718. // Postprocesses
  10719. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10720. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10721. }
  10722. };
  10723. // ---- Camera rigs section ----
  10724. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10725. while (this._rigCameras.length > 0) {
  10726. this._rigCameras.pop().dispose();
  10727. }
  10728. this.cameraRigMode = mode;
  10729. this._cameraRigParams = {};
  10730. switch (this.cameraRigMode) {
  10731. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10732. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10733. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10734. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10735. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10736. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10737. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10738. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10739. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10740. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10741. break;
  10742. }
  10743. var postProcesses = new Array();
  10744. switch (this.cameraRigMode) {
  10745. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10746. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10747. this._rigCameras[0].isIntermediate = true;
  10748. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10749. postProcesses[1].onApply = function (effect) {
  10750. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10751. };
  10752. break;
  10753. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10754. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10755. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10756. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10757. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10758. var secondCamIndex = 1 - firstCamIndex;
  10759. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10760. this._rigCameras[firstCamIndex].isIntermediate = true;
  10761. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10762. break;
  10763. case Camera.RIG_MODE_VR:
  10764. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10765. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10766. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10767. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10768. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10769. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10770. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10771. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10772. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10773. if (metrics.compensateDistortion) {
  10774. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10775. }
  10776. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10777. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10778. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10779. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10780. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10781. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10782. if (metrics.compensateDistortion) {
  10783. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10784. }
  10785. break;
  10786. }
  10787. this._update();
  10788. };
  10789. Camera.prototype._getVRProjectionMatrix = function () {
  10790. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10791. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10792. return this._projectionMatrix;
  10793. };
  10794. Camera.prototype.setCameraRigParameter = function (name, value) {
  10795. this._cameraRigParams[name] = value;
  10796. //provisionnally:
  10797. if (name === "interaxialDistance") {
  10798. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10799. }
  10800. };
  10801. /**
  10802. * May needs to be overridden by children so sub has required properties to be copied
  10803. */
  10804. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10805. return null;
  10806. };
  10807. /**
  10808. * May needs to be overridden by children
  10809. */
  10810. Camera.prototype._updateRigCameras = function () {
  10811. for (var i = 0; i < this._rigCameras.length; i++) {
  10812. this._rigCameras[i].minZ = this.minZ;
  10813. this._rigCameras[i].maxZ = this.maxZ;
  10814. this._rigCameras[i].fov = this.fov;
  10815. }
  10816. // only update viewport when ANAGLYPH
  10817. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10818. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10819. }
  10820. };
  10821. Camera.prototype.serialize = function () {
  10822. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10823. // Type
  10824. serializationObject.type = this.getTypeName();
  10825. // Parent
  10826. if (this.parent) {
  10827. serializationObject.parentId = this.parent.id;
  10828. }
  10829. // Animations
  10830. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10831. serializationObject.ranges = this.serializeAnimationRanges();
  10832. return serializationObject;
  10833. };
  10834. Camera.prototype.getTypeName = function () {
  10835. return "Camera";
  10836. };
  10837. Camera.prototype.clone = function (name) {
  10838. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10839. };
  10840. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10841. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10842. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10843. switch (type) {
  10844. case "ArcRotateCamera":
  10845. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10846. case "DeviceOrientationCamera":
  10847. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10848. case "FollowCamera":
  10849. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10850. case "ArcFollowCamera":
  10851. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10852. case "GamepadCamera":
  10853. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10854. case "TouchCamera":
  10855. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10856. case "VirtualJoysticksCamera":
  10857. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10858. case "WebVRFreeCamera":
  10859. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10860. case "VRDeviceOrientationFreeCamera":
  10861. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10862. case "AnaglyphArcRotateCamera":
  10863. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10864. case "AnaglyphFreeCamera":
  10865. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10866. case "AnaglyphGamepadCamera":
  10867. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10868. case "AnaglyphUniversalCamera":
  10869. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10870. case "StereoscopicArcRotateCamera":
  10871. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10872. case "StereoscopicFreeCamera":
  10873. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10874. case "StereoscopicGamepadCamera":
  10875. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10876. case "StereoscopicUniversalCamera":
  10877. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10878. case "FreeCamera":
  10879. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10880. default:
  10881. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10882. }
  10883. };
  10884. Camera.Parse = function (parsedCamera, scene) {
  10885. var type = parsedCamera.type;
  10886. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10887. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10888. // Parent
  10889. if (parsedCamera.parentId) {
  10890. camera._waitingParentId = parsedCamera.parentId;
  10891. }
  10892. // Target
  10893. if (parsedCamera.target) {
  10894. if (camera.setTarget) {
  10895. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10896. }
  10897. }
  10898. // Apply 3d rig, when found
  10899. if (parsedCamera.cameraRigMode) {
  10900. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10901. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10902. }
  10903. // Animations
  10904. if (parsedCamera.animations) {
  10905. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10906. var parsedAnimation = parsedCamera.animations[animationIndex];
  10907. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10908. }
  10909. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10910. }
  10911. if (parsedCamera.autoAnimate) {
  10912. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10913. }
  10914. return camera;
  10915. };
  10916. // Statics
  10917. Camera._PERSPECTIVE_CAMERA = 0;
  10918. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10919. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10920. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10921. Camera._RIG_MODE_NONE = 0;
  10922. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10923. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10924. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10925. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10926. Camera._RIG_MODE_VR = 20;
  10927. __decorate([
  10928. BABYLON.serializeAsVector3()
  10929. ], Camera.prototype, "position", void 0);
  10930. __decorate([
  10931. BABYLON.serialize()
  10932. ], Camera.prototype, "upVector", void 0);
  10933. __decorate([
  10934. BABYLON.serialize()
  10935. ], Camera.prototype, "orthoLeft", void 0);
  10936. __decorate([
  10937. BABYLON.serialize()
  10938. ], Camera.prototype, "orthoRight", void 0);
  10939. __decorate([
  10940. BABYLON.serialize()
  10941. ], Camera.prototype, "orthoBottom", void 0);
  10942. __decorate([
  10943. BABYLON.serialize()
  10944. ], Camera.prototype, "orthoTop", void 0);
  10945. __decorate([
  10946. BABYLON.serialize()
  10947. ], Camera.prototype, "fov", void 0);
  10948. __decorate([
  10949. BABYLON.serialize()
  10950. ], Camera.prototype, "minZ", void 0);
  10951. __decorate([
  10952. BABYLON.serialize()
  10953. ], Camera.prototype, "maxZ", void 0);
  10954. __decorate([
  10955. BABYLON.serialize()
  10956. ], Camera.prototype, "inertia", void 0);
  10957. __decorate([
  10958. BABYLON.serialize()
  10959. ], Camera.prototype, "mode", void 0);
  10960. __decorate([
  10961. BABYLON.serialize()
  10962. ], Camera.prototype, "layerMask", void 0);
  10963. __decorate([
  10964. BABYLON.serialize()
  10965. ], Camera.prototype, "fovMode", void 0);
  10966. __decorate([
  10967. BABYLON.serialize()
  10968. ], Camera.prototype, "cameraRigMode", void 0);
  10969. __decorate([
  10970. BABYLON.serialize()
  10971. ], Camera.prototype, "interaxialDistance", void 0);
  10972. __decorate([
  10973. BABYLON.serialize()
  10974. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10975. return Camera;
  10976. })(BABYLON.Node);
  10977. BABYLON.Camera = Camera;
  10978. })(BABYLON || (BABYLON = {}));
  10979. var BABYLON;
  10980. (function (BABYLON) {
  10981. var TargetCamera = (function (_super) {
  10982. __extends(TargetCamera, _super);
  10983. function TargetCamera(name, position, scene) {
  10984. _super.call(this, name, position, scene);
  10985. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10986. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10987. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10988. this.speed = 2.0;
  10989. this.noRotationConstraint = false;
  10990. this.lockedTarget = null;
  10991. this._currentTarget = BABYLON.Vector3.Zero();
  10992. this._viewMatrix = BABYLON.Matrix.Zero();
  10993. this._camMatrix = BABYLON.Matrix.Zero();
  10994. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10995. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10996. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10997. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10998. this._lookAtTemp = BABYLON.Matrix.Zero();
  10999. this._tempMatrix = BABYLON.Matrix.Zero();
  11000. }
  11001. TargetCamera.prototype.getFrontPosition = function (distance) {
  11002. var direction = this.getTarget().subtract(this.position);
  11003. direction.normalize();
  11004. direction.scaleInPlace(distance);
  11005. return this.globalPosition.add(direction);
  11006. };
  11007. TargetCamera.prototype._getLockedTargetPosition = function () {
  11008. if (!this.lockedTarget) {
  11009. return null;
  11010. }
  11011. return this.lockedTarget.position || this.lockedTarget;
  11012. };
  11013. // Cache
  11014. TargetCamera.prototype._initCache = function () {
  11015. _super.prototype._initCache.call(this);
  11016. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11017. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11018. };
  11019. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11020. if (!ignoreParentClass) {
  11021. _super.prototype._updateCache.call(this);
  11022. }
  11023. var lockedTargetPosition = this._getLockedTargetPosition();
  11024. if (!lockedTargetPosition) {
  11025. this._cache.lockedTarget = null;
  11026. }
  11027. else {
  11028. if (!this._cache.lockedTarget) {
  11029. this._cache.lockedTarget = lockedTargetPosition.clone();
  11030. }
  11031. else {
  11032. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11033. }
  11034. }
  11035. this._cache.rotation.copyFrom(this.rotation);
  11036. };
  11037. // Synchronized
  11038. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11039. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11040. return false;
  11041. }
  11042. var lockedTargetPosition = this._getLockedTargetPosition();
  11043. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11044. && this._cache.rotation.equals(this.rotation);
  11045. };
  11046. // Methods
  11047. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11048. var engine = this.getEngine();
  11049. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11050. };
  11051. // Target
  11052. TargetCamera.prototype.setTarget = function (target) {
  11053. this.upVector.normalize();
  11054. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11055. this._camMatrix.invert();
  11056. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11057. var vDir = target.subtract(this.position);
  11058. if (vDir.x >= 0.0) {
  11059. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11060. }
  11061. else {
  11062. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11063. }
  11064. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11065. if (isNaN(this.rotation.x)) {
  11066. this.rotation.x = 0;
  11067. }
  11068. if (isNaN(this.rotation.y)) {
  11069. this.rotation.y = 0;
  11070. }
  11071. if (isNaN(this.rotation.z)) {
  11072. this.rotation.z = 0;
  11073. }
  11074. };
  11075. TargetCamera.prototype.getTarget = function () {
  11076. return this._currentTarget;
  11077. };
  11078. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11079. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11080. };
  11081. TargetCamera.prototype._updatePosition = function () {
  11082. this.position.addInPlace(this.cameraDirection);
  11083. };
  11084. TargetCamera.prototype._checkInputs = function () {
  11085. var needToMove = this._decideIfNeedsToMove();
  11086. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11087. // Move
  11088. if (needToMove) {
  11089. this._updatePosition();
  11090. }
  11091. // Rotate
  11092. if (needToRotate) {
  11093. this.rotation.x += this.cameraRotation.x;
  11094. this.rotation.y += this.cameraRotation.y;
  11095. if (!this.noRotationConstraint) {
  11096. var limit = (Math.PI / 2) * 0.95;
  11097. if (this.rotation.x > limit)
  11098. this.rotation.x = limit;
  11099. if (this.rotation.x < -limit)
  11100. this.rotation.x = -limit;
  11101. }
  11102. }
  11103. // Inertia
  11104. if (needToMove) {
  11105. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11106. this.cameraDirection.x = 0;
  11107. }
  11108. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11109. this.cameraDirection.y = 0;
  11110. }
  11111. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11112. this.cameraDirection.z = 0;
  11113. }
  11114. this.cameraDirection.scaleInPlace(this.inertia);
  11115. }
  11116. if (needToRotate) {
  11117. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11118. this.cameraRotation.x = 0;
  11119. }
  11120. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11121. this.cameraRotation.y = 0;
  11122. }
  11123. this.cameraRotation.scaleInPlace(this.inertia);
  11124. }
  11125. _super.prototype._checkInputs.call(this);
  11126. };
  11127. TargetCamera.prototype._getViewMatrix = function () {
  11128. if (!this.lockedTarget) {
  11129. // Compute
  11130. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11131. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11132. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11133. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11134. this._lookAtTemp.invert();
  11135. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11136. }
  11137. else {
  11138. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11139. }
  11140. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11141. // Computing target and final matrix
  11142. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11143. }
  11144. else {
  11145. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11146. }
  11147. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11148. return this._viewMatrix;
  11149. };
  11150. TargetCamera.prototype._getVRViewMatrix = function () {
  11151. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11152. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11153. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11154. // Computing target and final matrix
  11155. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11156. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11157. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11158. return this._viewMatrix;
  11159. };
  11160. /**
  11161. * @override
  11162. * Override Camera.createRigCamera
  11163. */
  11164. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11165. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11166. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11167. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11168. rigCamera._cameraRigParams = {};
  11169. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11170. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11171. }
  11172. return rigCamera;
  11173. }
  11174. return null;
  11175. };
  11176. /**
  11177. * @override
  11178. * Override Camera._updateRigCameras
  11179. */
  11180. TargetCamera.prototype._updateRigCameras = function () {
  11181. switch (this.cameraRigMode) {
  11182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11186. case BABYLON.Camera.RIG_MODE_VR:
  11187. var camLeft = this._rigCameras[0];
  11188. var camRight = this._rigCameras[1];
  11189. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11190. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11191. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11192. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11193. camLeft.position.copyFrom(this.position);
  11194. camRight.position.copyFrom(this.position);
  11195. }
  11196. else {
  11197. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11198. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11199. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11200. camLeft.setTarget(this.getTarget());
  11201. camRight.setTarget(this.getTarget());
  11202. }
  11203. break;
  11204. }
  11205. _super.prototype._updateRigCameras.call(this);
  11206. };
  11207. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11208. if (!this._rigCamTransformMatrix) {
  11209. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11210. }
  11211. var target = this.getTarget();
  11212. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11213. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11215. };
  11216. TargetCamera.prototype.getTypeName = function () {
  11217. return "TargetCamera";
  11218. };
  11219. __decorate([
  11220. BABYLON.serializeAsVector3()
  11221. ], TargetCamera.prototype, "rotation", void 0);
  11222. __decorate([
  11223. BABYLON.serialize()
  11224. ], TargetCamera.prototype, "speed", void 0);
  11225. __decorate([
  11226. BABYLON.serializeAsMeshReference("lockedTargetId")
  11227. ], TargetCamera.prototype, "lockedTarget", void 0);
  11228. return TargetCamera;
  11229. })(BABYLON.Camera);
  11230. BABYLON.TargetCamera = TargetCamera;
  11231. })(BABYLON || (BABYLON = {}));
  11232. var BABYLON;
  11233. (function (BABYLON) {
  11234. var FreeCamera = (function (_super) {
  11235. __extends(FreeCamera, _super);
  11236. function FreeCamera(name, position, scene) {
  11237. var _this = this;
  11238. _super.call(this, name, position, scene);
  11239. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11240. this.keysUp = [38];
  11241. this.keysDown = [40];
  11242. this.keysLeft = [37];
  11243. this.keysRight = [39];
  11244. this.checkCollisions = false;
  11245. this.applyGravity = false;
  11246. this.angularSensibility = 2000.0;
  11247. this._keys = [];
  11248. this._collider = new BABYLON.Collider();
  11249. this._needMoveForGravity = false;
  11250. this._oldPosition = BABYLON.Vector3.Zero();
  11251. this._diffPosition = BABYLON.Vector3.Zero();
  11252. this._newPosition = BABYLON.Vector3.Zero();
  11253. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11254. if (collidedMesh === void 0) { collidedMesh = null; }
  11255. //TODO move this to the collision coordinator!
  11256. if (_this.getScene().workerCollisions)
  11257. newPosition.multiplyInPlace(_this._collider.radius);
  11258. var updatePosition = function (newPos) {
  11259. _this._newPosition.copyFrom(newPos);
  11260. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11261. var oldPosition = _this.position.clone();
  11262. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11263. _this.position.addInPlace(_this._diffPosition);
  11264. if (_this.onCollide && collidedMesh) {
  11265. _this.onCollide(collidedMesh);
  11266. }
  11267. }
  11268. };
  11269. updatePosition(newPosition);
  11270. };
  11271. }
  11272. FreeCamera.prototype._onLostFocus = function (e) {
  11273. this._keys = [];
  11274. };
  11275. // Controls
  11276. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11277. var _this = this;
  11278. var previousPosition;
  11279. var engine = this.getEngine();
  11280. if (this._attachedElement) {
  11281. return;
  11282. }
  11283. this._attachedElement = element;
  11284. if (this._onMouseDown === undefined) {
  11285. this._onMouseDown = function (evt) {
  11286. previousPosition = {
  11287. x: evt.clientX,
  11288. y: evt.clientY
  11289. };
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onMouseUp = function (evt) {
  11295. previousPosition = null;
  11296. if (!noPreventDefault) {
  11297. evt.preventDefault();
  11298. }
  11299. };
  11300. this._onMouseOut = function (evt) {
  11301. previousPosition = null;
  11302. _this._keys = [];
  11303. if (!noPreventDefault) {
  11304. evt.preventDefault();
  11305. }
  11306. };
  11307. this._onMouseMove = function (evt) {
  11308. if (!previousPosition && !engine.isPointerLock) {
  11309. return;
  11310. }
  11311. var offsetX;
  11312. var offsetY;
  11313. if (!engine.isPointerLock) {
  11314. offsetX = evt.clientX - previousPosition.x;
  11315. offsetY = evt.clientY - previousPosition.y;
  11316. }
  11317. else {
  11318. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11319. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11320. }
  11321. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11322. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11323. previousPosition = {
  11324. x: evt.clientX,
  11325. y: evt.clientY
  11326. };
  11327. if (!noPreventDefault) {
  11328. evt.preventDefault();
  11329. }
  11330. };
  11331. this._onKeyDown = function (evt) {
  11332. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11333. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11334. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11335. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11336. var index = _this._keys.indexOf(evt.keyCode);
  11337. if (index === -1) {
  11338. _this._keys.push(evt.keyCode);
  11339. }
  11340. if (!noPreventDefault) {
  11341. evt.preventDefault();
  11342. }
  11343. }
  11344. };
  11345. this._onKeyUp = function (evt) {
  11346. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11347. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11348. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11349. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11350. var index = _this._keys.indexOf(evt.keyCode);
  11351. if (index >= 0) {
  11352. _this._keys.splice(index, 1);
  11353. }
  11354. if (!noPreventDefault) {
  11355. evt.preventDefault();
  11356. }
  11357. }
  11358. };
  11359. this._reset = function () {
  11360. _this._keys = [];
  11361. previousPosition = null;
  11362. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11363. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11364. };
  11365. }
  11366. element.addEventListener("mousedown", this._onMouseDown, false);
  11367. element.addEventListener("mouseup", this._onMouseUp, false);
  11368. element.addEventListener("mouseout", this._onMouseOut, false);
  11369. element.addEventListener("mousemove", this._onMouseMove, false);
  11370. BABYLON.Tools.RegisterTopRootEvents([
  11371. { name: "keydown", handler: this._onKeyDown },
  11372. { name: "keyup", handler: this._onKeyUp },
  11373. { name: "blur", handler: this._onLostFocus }
  11374. ]);
  11375. };
  11376. FreeCamera.prototype.detachControl = function (element) {
  11377. if (this._attachedElement !== element) {
  11378. return;
  11379. }
  11380. element.removeEventListener("mousedown", this._onMouseDown);
  11381. element.removeEventListener("mouseup", this._onMouseUp);
  11382. element.removeEventListener("mouseout", this._onMouseOut);
  11383. element.removeEventListener("mousemove", this._onMouseMove);
  11384. BABYLON.Tools.UnregisterTopRootEvents([
  11385. { name: "keydown", handler: this._onKeyDown },
  11386. { name: "keyup", handler: this._onKeyUp },
  11387. { name: "blur", handler: this._onLostFocus }
  11388. ]);
  11389. this._attachedElement = null;
  11390. if (this._reset) {
  11391. this._reset();
  11392. }
  11393. };
  11394. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11395. var globalPosition;
  11396. if (this.parent) {
  11397. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11398. }
  11399. else {
  11400. globalPosition = this.position;
  11401. }
  11402. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11403. this._collider.radius = this.ellipsoid;
  11404. //no need for clone, as long as gravity is not on.
  11405. var actualVelocity = velocity;
  11406. //add gravity to the velocity to prevent the dual-collision checking
  11407. if (this.applyGravity) {
  11408. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11409. actualVelocity = velocity.add(this.getScene().gravity);
  11410. }
  11411. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11412. };
  11413. FreeCamera.prototype._checkInputs = function () {
  11414. if (!this._localDirection) {
  11415. this._localDirection = BABYLON.Vector3.Zero();
  11416. this._transformedDirection = BABYLON.Vector3.Zero();
  11417. }
  11418. // Keyboard
  11419. for (var index = 0; index < this._keys.length; index++) {
  11420. var keyCode = this._keys[index];
  11421. var speed = this._computeLocalCameraSpeed();
  11422. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11423. this._localDirection.copyFromFloats(-speed, 0, 0);
  11424. }
  11425. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11426. this._localDirection.copyFromFloats(0, 0, speed);
  11427. }
  11428. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11429. this._localDirection.copyFromFloats(speed, 0, 0);
  11430. }
  11431. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11432. this._localDirection.copyFromFloats(0, 0, -speed);
  11433. }
  11434. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11435. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11436. this.cameraDirection.addInPlace(this._transformedDirection);
  11437. }
  11438. _super.prototype._checkInputs.call(this);
  11439. };
  11440. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11441. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11442. };
  11443. FreeCamera.prototype._updatePosition = function () {
  11444. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11445. this._collideWithWorld(this.cameraDirection);
  11446. }
  11447. else {
  11448. this.position.addInPlace(this.cameraDirection);
  11449. }
  11450. };
  11451. FreeCamera.prototype.getTypeName = function () {
  11452. return "FreeCamera";
  11453. };
  11454. __decorate([
  11455. BABYLON.serializeAsVector3()
  11456. ], FreeCamera.prototype, "ellipsoid", void 0);
  11457. __decorate([
  11458. BABYLON.serialize()
  11459. ], FreeCamera.prototype, "keysUp", void 0);
  11460. __decorate([
  11461. BABYLON.serialize()
  11462. ], FreeCamera.prototype, "keysDown", void 0);
  11463. __decorate([
  11464. BABYLON.serialize()
  11465. ], FreeCamera.prototype, "keysLeft", void 0);
  11466. __decorate([
  11467. BABYLON.serialize()
  11468. ], FreeCamera.prototype, "keysRight", void 0);
  11469. __decorate([
  11470. BABYLON.serialize()
  11471. ], FreeCamera.prototype, "checkCollisions", void 0);
  11472. __decorate([
  11473. BABYLON.serialize()
  11474. ], FreeCamera.prototype, "applyGravity", void 0);
  11475. __decorate([
  11476. BABYLON.serialize()
  11477. ], FreeCamera.prototype, "angularSensibility", void 0);
  11478. return FreeCamera;
  11479. })(BABYLON.TargetCamera);
  11480. BABYLON.FreeCamera = FreeCamera;
  11481. })(BABYLON || (BABYLON = {}));
  11482. var BABYLON;
  11483. (function (BABYLON) {
  11484. var FollowCamera = (function (_super) {
  11485. __extends(FollowCamera, _super);
  11486. function FollowCamera(name, position, scene, target) {
  11487. _super.call(this, name, position, scene);
  11488. this.radius = 12;
  11489. this.rotationOffset = 0;
  11490. this.heightOffset = 4;
  11491. this.cameraAcceleration = 0.05;
  11492. this.maxCameraSpeed = 20;
  11493. this.target = target;
  11494. }
  11495. FollowCamera.prototype.getRadians = function (degrees) {
  11496. return degrees * Math.PI / 180;
  11497. };
  11498. FollowCamera.prototype.follow = function (cameraTarget) {
  11499. if (!cameraTarget)
  11500. return;
  11501. var yRotation;
  11502. if (cameraTarget.rotationQuaternion) {
  11503. var rotMatrix = new BABYLON.Matrix();
  11504. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11505. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11506. }
  11507. else {
  11508. yRotation = cameraTarget.rotation.y;
  11509. }
  11510. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11511. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11512. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11513. var dx = targetX - this.position.x;
  11514. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11515. var dz = (targetZ) - this.position.z;
  11516. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11517. var vy = dy * this.cameraAcceleration;
  11518. var vz = dz * this.cameraAcceleration * 2;
  11519. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11520. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11521. }
  11522. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11523. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11524. }
  11525. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11526. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11527. }
  11528. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11529. this.setTarget(cameraTarget.position);
  11530. };
  11531. FollowCamera.prototype._checkInputs = function () {
  11532. _super.prototype._checkInputs.call(this);
  11533. this.follow(this.target);
  11534. };
  11535. FollowCamera.prototype.getTypeName = function () {
  11536. return "FollowCamera";
  11537. };
  11538. __decorate([
  11539. BABYLON.serialize()
  11540. ], FollowCamera.prototype, "radius", void 0);
  11541. __decorate([
  11542. BABYLON.serialize()
  11543. ], FollowCamera.prototype, "rotationOffset", void 0);
  11544. __decorate([
  11545. BABYLON.serialize()
  11546. ], FollowCamera.prototype, "heightOffset", void 0);
  11547. __decorate([
  11548. BABYLON.serialize()
  11549. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11550. __decorate([
  11551. BABYLON.serialize()
  11552. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11553. __decorate([
  11554. BABYLON.serializeAsMeshReference("lockedTargetId")
  11555. ], FollowCamera.prototype, "target", void 0);
  11556. return FollowCamera;
  11557. })(BABYLON.TargetCamera);
  11558. BABYLON.FollowCamera = FollowCamera;
  11559. var ArcFollowCamera = (function (_super) {
  11560. __extends(ArcFollowCamera, _super);
  11561. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11562. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11563. this.alpha = alpha;
  11564. this.beta = beta;
  11565. this.radius = radius;
  11566. this.target = target;
  11567. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11568. this.follow();
  11569. }
  11570. ArcFollowCamera.prototype.follow = function () {
  11571. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11572. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11573. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11574. this.position = this.target.position.add(this._cartesianCoordinates);
  11575. this.setTarget(this.target.position);
  11576. };
  11577. ArcFollowCamera.prototype._checkInputs = function () {
  11578. _super.prototype._checkInputs.call(this);
  11579. this.follow();
  11580. };
  11581. ArcFollowCamera.prototype.getTypeName = function () {
  11582. return "ArcFollowCamera";
  11583. };
  11584. return ArcFollowCamera;
  11585. })(BABYLON.TargetCamera);
  11586. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11587. })(BABYLON || (BABYLON = {}));
  11588. var BABYLON;
  11589. (function (BABYLON) {
  11590. // We're mainly based on the logic defined into the FreeCamera code
  11591. var TouchCamera = (function (_super) {
  11592. __extends(TouchCamera, _super);
  11593. function TouchCamera(name, position, scene) {
  11594. _super.call(this, name, position, scene);
  11595. this._offsetX = null;
  11596. this._offsetY = null;
  11597. this._pointerCount = 0;
  11598. this._pointerPressed = [];
  11599. this.touchAngularSensibility = 200000.0;
  11600. this.touchMoveSensibility = 250.0;
  11601. }
  11602. TouchCamera.prototype._onLostFocus = function (e) {
  11603. this._offsetX = null;
  11604. this._offsetY = null;
  11605. _super.prototype._onLostFocus.call(this, e);
  11606. };
  11607. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11608. var _this = this;
  11609. var previousPosition;
  11610. if (this._attachedCanvas) {
  11611. return;
  11612. }
  11613. if (this._onPointerDown === undefined) {
  11614. this._onPointerDown = function (evt) {
  11615. if (evt.pointerType === "mouse") {
  11616. return;
  11617. }
  11618. if (!noPreventDefault) {
  11619. evt.preventDefault();
  11620. }
  11621. _this._pointerPressed.push(evt.pointerId);
  11622. if (_this._pointerPressed.length !== 1) {
  11623. return;
  11624. }
  11625. previousPosition = {
  11626. x: evt.clientX,
  11627. y: evt.clientY
  11628. };
  11629. };
  11630. this._onPointerUp = function (evt) {
  11631. if (evt.pointerType === "mouse") {
  11632. return;
  11633. }
  11634. if (!noPreventDefault) {
  11635. evt.preventDefault();
  11636. }
  11637. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11638. if (index === -1) {
  11639. return;
  11640. }
  11641. _this._pointerPressed.splice(index, 1);
  11642. if (index != 0) {
  11643. return;
  11644. }
  11645. previousPosition = null;
  11646. _this._offsetX = null;
  11647. _this._offsetY = null;
  11648. };
  11649. this._onPointerMove = function (evt) {
  11650. if (evt.pointerType === "mouse") {
  11651. return;
  11652. }
  11653. if (!noPreventDefault) {
  11654. evt.preventDefault();
  11655. }
  11656. if (!previousPosition) {
  11657. return;
  11658. }
  11659. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11660. if (index != 0) {
  11661. return;
  11662. }
  11663. _this._offsetX = evt.clientX - previousPosition.x;
  11664. _this._offsetY = -(evt.clientY - previousPosition.y);
  11665. };
  11666. }
  11667. canvas.addEventListener("pointerdown", this._onPointerDown);
  11668. canvas.addEventListener("pointerup", this._onPointerUp);
  11669. canvas.addEventListener("pointerout", this._onPointerUp);
  11670. canvas.addEventListener("pointermove", this._onPointerMove);
  11671. _super.prototype.attachControl.call(this, canvas);
  11672. };
  11673. TouchCamera.prototype.detachControl = function (canvas) {
  11674. if (this._attachedCanvas !== canvas) {
  11675. return;
  11676. }
  11677. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11678. canvas.removeEventListener("pointerup", this._onPointerUp);
  11679. canvas.removeEventListener("pointerout", this._onPointerUp);
  11680. canvas.removeEventListener("pointermove", this._onPointerMove);
  11681. _super.prototype.detachControl.call(this, canvas);
  11682. };
  11683. TouchCamera.prototype._checkInputs = function () {
  11684. if (this._offsetX) {
  11685. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11686. if (this._pointerPressed.length > 1) {
  11687. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11688. }
  11689. else {
  11690. var speed = this._computeLocalCameraSpeed();
  11691. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11692. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11693. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11694. }
  11695. }
  11696. _super.prototype._checkInputs.call(this);
  11697. };
  11698. TouchCamera.prototype.getTypeName = function () {
  11699. return "TouchCamera";
  11700. };
  11701. __decorate([
  11702. BABYLON.serialize()
  11703. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11704. __decorate([
  11705. BABYLON.serialize()
  11706. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11707. return TouchCamera;
  11708. })(BABYLON.FreeCamera);
  11709. BABYLON.TouchCamera = TouchCamera;
  11710. })(BABYLON || (BABYLON = {}));
  11711. var BABYLON;
  11712. (function (BABYLON) {
  11713. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11714. var ArcRotateCamera = (function (_super) {
  11715. __extends(ArcRotateCamera, _super);
  11716. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11717. var _this = this;
  11718. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11719. this.inertialAlphaOffset = 0;
  11720. this.inertialBetaOffset = 0;
  11721. this.inertialRadiusOffset = 0;
  11722. this.lowerAlphaLimit = null;
  11723. this.upperAlphaLimit = null;
  11724. this.lowerBetaLimit = 0.01;
  11725. this.upperBetaLimit = Math.PI;
  11726. this.lowerRadiusLimit = null;
  11727. this.upperRadiusLimit = null;
  11728. this.angularSensibilityX = 1000.0;
  11729. this.angularSensibilityY = 1000.0;
  11730. this.wheelPrecision = 3.0;
  11731. this.pinchPrecision = 2.0;
  11732. this.panningSensibility = 50.0;
  11733. this.inertialPanningX = 0;
  11734. this.inertialPanningY = 0;
  11735. this.keysUp = [38];
  11736. this.keysDown = [40];
  11737. this.keysLeft = [37];
  11738. this.keysRight = [39];
  11739. this.zoomOnFactor = 1;
  11740. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11741. this.pinchInwards = true;
  11742. this.allowUpsideDown = true;
  11743. this._keys = [];
  11744. this._viewMatrix = new BABYLON.Matrix();
  11745. // Panning
  11746. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11747. this._isRightClick = false;
  11748. this._isCtrlPushed = false;
  11749. this.checkCollisions = false;
  11750. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11751. this._collider = new BABYLON.Collider();
  11752. this._previousPosition = BABYLON.Vector3.Zero();
  11753. this._collisionVelocity = BABYLON.Vector3.Zero();
  11754. this._newPosition = BABYLON.Vector3.Zero();
  11755. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11756. if (collidedMesh === void 0) { collidedMesh = null; }
  11757. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11758. newPosition.multiplyInPlace(_this._collider.radius);
  11759. }
  11760. if (!collidedMesh) {
  11761. _this._previousPosition.copyFrom(_this.position);
  11762. }
  11763. else {
  11764. _this.setPosition(newPosition);
  11765. if (_this.onCollide) {
  11766. _this.onCollide(collidedMesh);
  11767. }
  11768. }
  11769. // Recompute because of constraints
  11770. var cosa = Math.cos(_this.alpha);
  11771. var sina = Math.sin(_this.alpha);
  11772. var cosb = Math.cos(_this.beta);
  11773. var sinb = Math.sin(_this.beta);
  11774. if (sinb === 0) {
  11775. sinb = 0.0001;
  11776. }
  11777. var target = _this._getTargetPosition();
  11778. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11779. _this.position.copyFrom(_this._newPosition);
  11780. var up = _this.upVector;
  11781. if (_this.allowUpsideDown && _this.beta < 0) {
  11782. up = up.clone();
  11783. up = up.negate();
  11784. }
  11785. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11786. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11787. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11788. _this._collisionTriggered = false;
  11789. };
  11790. if (!target) {
  11791. this.target = BABYLON.Vector3.Zero();
  11792. }
  11793. else {
  11794. this.target = target;
  11795. }
  11796. this.alpha = alpha;
  11797. this.beta = beta;
  11798. this.radius = radius;
  11799. this.getViewMatrix();
  11800. }
  11801. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11802. //deprecated angularSensibility support
  11803. get: function () {
  11804. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11805. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11806. },
  11807. //deprecated angularSensibility support
  11808. set: function (value) {
  11809. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11810. this.angularSensibilityX = value;
  11811. this.angularSensibilityY = value;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. // Cache
  11817. ArcRotateCamera.prototype._initCache = function () {
  11818. _super.prototype._initCache.call(this);
  11819. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11820. this._cache.alpha = undefined;
  11821. this._cache.beta = undefined;
  11822. this._cache.radius = undefined;
  11823. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11824. };
  11825. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11826. if (!ignoreParentClass) {
  11827. _super.prototype._updateCache.call(this);
  11828. }
  11829. this._cache.target.copyFrom(this._getTargetPosition());
  11830. this._cache.alpha = this.alpha;
  11831. this._cache.beta = this.beta;
  11832. this._cache.radius = this.radius;
  11833. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11834. };
  11835. ArcRotateCamera.prototype._getTargetPosition = function () {
  11836. if (this.target.getAbsolutePosition) {
  11837. return this.target.getAbsolutePosition();
  11838. }
  11839. return this.target;
  11840. };
  11841. // Synchronized
  11842. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11843. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11844. return false;
  11845. return this._cache.target.equals(this.target)
  11846. && this._cache.alpha === this.alpha
  11847. && this._cache.beta === this.beta
  11848. && this._cache.radius === this.radius
  11849. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11850. };
  11851. // Methods
  11852. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11853. var _this = this;
  11854. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11855. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11856. var previousPinchDistance = 0;
  11857. var pointers = new BABYLON.SmartCollection();
  11858. if (this._attachedElement) {
  11859. return;
  11860. }
  11861. this._attachedElement = element;
  11862. var engine = this.getEngine();
  11863. if (this._onPointerDown === undefined) {
  11864. this._onPointerDown = function (evt) {
  11865. // Manage panning with right click
  11866. _this._isRightClick = evt.button === 2;
  11867. // manage pointers
  11868. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11869. cacheSoloPointer = pointers.item(evt.pointerId);
  11870. if (!noPreventDefault) {
  11871. evt.preventDefault();
  11872. }
  11873. };
  11874. this._onPointerUp = function (evt) {
  11875. cacheSoloPointer = null;
  11876. previousPinchDistance = 0;
  11877. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11878. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11879. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11880. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11881. pointers.empty();
  11882. if (!noPreventDefault) {
  11883. evt.preventDefault();
  11884. }
  11885. };
  11886. this._onContextMenu = function (evt) {
  11887. evt.preventDefault();
  11888. };
  11889. this._onPointerMove = function (evt) {
  11890. if (!noPreventDefault) {
  11891. evt.preventDefault();
  11892. }
  11893. switch (pointers.count) {
  11894. case 1:
  11895. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11896. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11897. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11898. }
  11899. else {
  11900. var offsetX = evt.clientX - cacheSoloPointer.x;
  11901. var offsetY = evt.clientY - cacheSoloPointer.y;
  11902. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11903. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11904. }
  11905. cacheSoloPointer.x = evt.clientX;
  11906. cacheSoloPointer.y = evt.clientY;
  11907. break;
  11908. case 2:
  11909. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11910. pointers.item(evt.pointerId).x = evt.clientX;
  11911. pointers.item(evt.pointerId).y = evt.clientY;
  11912. var direction = _this.pinchInwards ? 1 : -1;
  11913. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11914. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11915. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11916. if (previousPinchDistance === 0) {
  11917. previousPinchDistance = pinchSquaredDistance;
  11918. return;
  11919. }
  11920. if (pinchSquaredDistance !== previousPinchDistance) {
  11921. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11922. previousPinchDistance = pinchSquaredDistance;
  11923. }
  11924. break;
  11925. default:
  11926. if (pointers.item(evt.pointerId)) {
  11927. pointers.item(evt.pointerId).x = evt.clientX;
  11928. pointers.item(evt.pointerId).y = evt.clientY;
  11929. }
  11930. }
  11931. };
  11932. this._onMouseMove = function (evt) {
  11933. if (!engine.isPointerLock) {
  11934. return;
  11935. }
  11936. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11937. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11938. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11939. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11940. if (!noPreventDefault) {
  11941. evt.preventDefault();
  11942. }
  11943. };
  11944. this._wheel = function (event) {
  11945. var delta = 0;
  11946. if (event.wheelDelta) {
  11947. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11948. }
  11949. else if (event.detail) {
  11950. delta = -event.detail / _this.wheelPrecision;
  11951. }
  11952. if (delta)
  11953. _this.inertialRadiusOffset += delta;
  11954. if (event.preventDefault) {
  11955. if (!noPreventDefault) {
  11956. event.preventDefault();
  11957. }
  11958. }
  11959. };
  11960. this._onKeyDown = function (evt) {
  11961. _this._isCtrlPushed = evt.ctrlKey;
  11962. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11963. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11964. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11965. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11966. var index = _this._keys.indexOf(evt.keyCode);
  11967. if (index === -1) {
  11968. _this._keys.push(evt.keyCode);
  11969. }
  11970. if (evt.preventDefault) {
  11971. if (!noPreventDefault) {
  11972. evt.preventDefault();
  11973. }
  11974. }
  11975. }
  11976. };
  11977. this._onKeyUp = function (evt) {
  11978. _this._isCtrlPushed = evt.ctrlKey;
  11979. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11980. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11981. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11982. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11983. var index = _this._keys.indexOf(evt.keyCode);
  11984. if (index >= 0) {
  11985. _this._keys.splice(index, 1);
  11986. }
  11987. if (evt.preventDefault) {
  11988. if (!noPreventDefault) {
  11989. evt.preventDefault();
  11990. }
  11991. }
  11992. }
  11993. };
  11994. this._onLostFocus = function () {
  11995. _this._keys = [];
  11996. pointers.empty();
  11997. previousPinchDistance = 0;
  11998. cacheSoloPointer = null;
  11999. };
  12000. this._onGestureStart = function (e) {
  12001. if (window.MSGesture === undefined) {
  12002. return;
  12003. }
  12004. if (!_this._MSGestureHandler) {
  12005. _this._MSGestureHandler = new MSGesture();
  12006. _this._MSGestureHandler.target = element;
  12007. }
  12008. _this._MSGestureHandler.addPointer(e.pointerId);
  12009. };
  12010. this._onGesture = function (e) {
  12011. _this.radius *= e.scale;
  12012. if (e.preventDefault) {
  12013. if (!noPreventDefault) {
  12014. e.stopPropagation();
  12015. e.preventDefault();
  12016. }
  12017. }
  12018. };
  12019. this._reset = function () {
  12020. _this._keys = [];
  12021. _this.inertialAlphaOffset = 0;
  12022. _this.inertialBetaOffset = 0;
  12023. _this.inertialRadiusOffset = 0;
  12024. pointers.empty();
  12025. previousPinchDistance = 0;
  12026. cacheSoloPointer = null;
  12027. };
  12028. }
  12029. if (!useCtrlForPanning) {
  12030. element.addEventListener("contextmenu", this._onContextMenu, false);
  12031. }
  12032. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12033. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12034. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12035. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12036. element.addEventListener("mousemove", this._onMouseMove, false);
  12037. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12038. element.addEventListener("MSGestureChange", this._onGesture, false);
  12039. element.addEventListener('mousewheel', this._wheel, false);
  12040. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12041. BABYLON.Tools.RegisterTopRootEvents([
  12042. { name: "keydown", handler: this._onKeyDown },
  12043. { name: "keyup", handler: this._onKeyUp },
  12044. { name: "blur", handler: this._onLostFocus }
  12045. ]);
  12046. };
  12047. ArcRotateCamera.prototype.detachControl = function (element) {
  12048. if (this._attachedElement !== element) {
  12049. return;
  12050. }
  12051. element.removeEventListener("contextmenu", this._onContextMenu);
  12052. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12053. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12054. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12055. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12056. element.removeEventListener("mousemove", this._onMouseMove);
  12057. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12058. element.removeEventListener("MSGestureChange", this._onGesture);
  12059. element.removeEventListener('mousewheel', this._wheel);
  12060. element.removeEventListener('DOMMouseScroll', this._wheel);
  12061. BABYLON.Tools.UnregisterTopRootEvents([
  12062. { name: "keydown", handler: this._onKeyDown },
  12063. { name: "keyup", handler: this._onKeyUp },
  12064. { name: "blur", handler: this._onLostFocus }
  12065. ]);
  12066. this._MSGestureHandler = null;
  12067. this._attachedElement = null;
  12068. if (this._reset) {
  12069. this._reset();
  12070. }
  12071. };
  12072. ArcRotateCamera.prototype._checkInputs = function () {
  12073. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12074. if (this._collisionTriggered) {
  12075. return;
  12076. }
  12077. // Keyboard
  12078. for (var index = 0; index < this._keys.length; index++) {
  12079. var keyCode = this._keys[index];
  12080. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12081. this.inertialAlphaOffset -= 0.01;
  12082. }
  12083. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12084. this.inertialBetaOffset -= 0.01;
  12085. }
  12086. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12087. this.inertialAlphaOffset += 0.01;
  12088. }
  12089. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12090. this.inertialBetaOffset += 0.01;
  12091. }
  12092. }
  12093. // Inertia
  12094. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12095. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12096. this.beta += this.inertialBetaOffset;
  12097. this.radius -= this.inertialRadiusOffset;
  12098. this.inertialAlphaOffset *= this.inertia;
  12099. this.inertialBetaOffset *= this.inertia;
  12100. this.inertialRadiusOffset *= this.inertia;
  12101. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12102. this.inertialAlphaOffset = 0;
  12103. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12104. this.inertialBetaOffset = 0;
  12105. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12106. this.inertialRadiusOffset = 0;
  12107. }
  12108. // Panning inertia
  12109. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12110. if (!this._localDirection) {
  12111. this._localDirection = BABYLON.Vector3.Zero();
  12112. this._transformedDirection = BABYLON.Vector3.Zero();
  12113. }
  12114. this.inertialPanningX *= this.inertia;
  12115. this.inertialPanningY *= this.inertia;
  12116. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12117. this.inertialPanningX = 0;
  12118. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12119. this.inertialPanningY = 0;
  12120. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12121. this._localDirection.multiplyInPlace(this.panningAxis);
  12122. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12123. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12124. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12125. if (!this.panningAxis.y) {
  12126. this._transformedDirection.y = 0;
  12127. }
  12128. this.target.addInPlace(this._transformedDirection);
  12129. }
  12130. // Limits
  12131. this._checkLimits();
  12132. _super.prototype._checkInputs.call(this);
  12133. };
  12134. ArcRotateCamera.prototype._checkLimits = function () {
  12135. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12136. if (this.allowUpsideDown && this.beta > Math.PI) {
  12137. this.beta = this.beta - (2 * Math.PI);
  12138. }
  12139. }
  12140. else {
  12141. if (this.beta < this.lowerBetaLimit) {
  12142. this.beta = this.lowerBetaLimit;
  12143. }
  12144. }
  12145. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12146. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12147. this.beta = this.beta + (2 * Math.PI);
  12148. }
  12149. }
  12150. else {
  12151. if (this.beta > this.upperBetaLimit) {
  12152. this.beta = this.upperBetaLimit;
  12153. }
  12154. }
  12155. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12156. this.alpha = this.lowerAlphaLimit;
  12157. }
  12158. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12159. this.alpha = this.upperAlphaLimit;
  12160. }
  12161. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12162. this.radius = this.lowerRadiusLimit;
  12163. }
  12164. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12165. this.radius = this.upperRadiusLimit;
  12166. }
  12167. };
  12168. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12169. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12170. this.radius = radiusv3.length();
  12171. // Alpha
  12172. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12173. if (radiusv3.z < 0) {
  12174. this.alpha = 2 * Math.PI - this.alpha;
  12175. }
  12176. // Beta
  12177. this.beta = Math.acos(radiusv3.y / this.radius);
  12178. this._checkLimits();
  12179. };
  12180. ArcRotateCamera.prototype.setPosition = function (position) {
  12181. if (this.position.equals(position)) {
  12182. return;
  12183. }
  12184. this.position = position;
  12185. this.rebuildAnglesAndRadius();
  12186. };
  12187. ArcRotateCamera.prototype.setTarget = function (target) {
  12188. if (this._getTargetPosition().equals(target)) {
  12189. return;
  12190. }
  12191. this.target = target;
  12192. this.rebuildAnglesAndRadius();
  12193. };
  12194. ArcRotateCamera.prototype._getViewMatrix = function () {
  12195. // Compute
  12196. var cosa = Math.cos(this.alpha);
  12197. var sina = Math.sin(this.alpha);
  12198. var cosb = Math.cos(this.beta);
  12199. var sinb = Math.sin(this.beta);
  12200. if (sinb === 0) {
  12201. sinb = 0.0001;
  12202. }
  12203. var target = this._getTargetPosition();
  12204. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12205. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12206. this._collider.radius = this.collisionRadius;
  12207. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12208. this._collisionTriggered = true;
  12209. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12210. }
  12211. else {
  12212. this.position.copyFrom(this._newPosition);
  12213. var up = this.upVector;
  12214. if (this.allowUpsideDown && this.beta < 0) {
  12215. up = up.clone();
  12216. up = up.negate();
  12217. }
  12218. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12219. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12220. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12221. }
  12222. return this._viewMatrix;
  12223. };
  12224. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12225. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12226. meshes = meshes || this.getScene().meshes;
  12227. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12228. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12229. this.radius = distance * this.zoomOnFactor;
  12230. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12231. };
  12232. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12233. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12234. var meshesOrMinMaxVector;
  12235. var distance;
  12236. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12237. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12238. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12239. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12240. }
  12241. else {
  12242. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12243. distance = meshesOrMinMaxVectorAndDistance.distance;
  12244. }
  12245. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12246. if (!doNotUpdateMaxZ) {
  12247. this.maxZ = distance * 2;
  12248. }
  12249. };
  12250. /**
  12251. * @override
  12252. * Override Camera.createRigCamera
  12253. */
  12254. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12255. switch (this.cameraRigMode) {
  12256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12260. case BABYLON.Camera.RIG_MODE_VR:
  12261. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12262. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12263. }
  12264. return null;
  12265. };
  12266. /**
  12267. * @override
  12268. * Override Camera._updateRigCameras
  12269. */
  12270. ArcRotateCamera.prototype._updateRigCameras = function () {
  12271. switch (this.cameraRigMode) {
  12272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12276. case BABYLON.Camera.RIG_MODE_VR:
  12277. var camLeft = this._rigCameras[0];
  12278. var camRight = this._rigCameras[1];
  12279. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12280. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12281. camLeft.beta = camRight.beta = this.beta;
  12282. camLeft.radius = camRight.radius = this.radius;
  12283. break;
  12284. }
  12285. _super.prototype._updateRigCameras.call(this);
  12286. };
  12287. ArcRotateCamera.prototype.getTypeName = function () {
  12288. return "ArcRotateCamera";
  12289. };
  12290. __decorate([
  12291. BABYLON.serialize()
  12292. ], ArcRotateCamera.prototype, "alpha", void 0);
  12293. __decorate([
  12294. BABYLON.serialize()
  12295. ], ArcRotateCamera.prototype, "beta", void 0);
  12296. __decorate([
  12297. BABYLON.serialize()
  12298. ], ArcRotateCamera.prototype, "radius", void 0);
  12299. __decorate([
  12300. BABYLON.serializeAsVector3()
  12301. ], ArcRotateCamera.prototype, "target", void 0);
  12302. __decorate([
  12303. BABYLON.serialize()
  12304. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12305. __decorate([
  12306. BABYLON.serialize()
  12307. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12308. __decorate([
  12309. BABYLON.serialize()
  12310. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12311. __decorate([
  12312. BABYLON.serialize()
  12313. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12314. __decorate([
  12315. BABYLON.serialize()
  12316. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12317. __decorate([
  12318. BABYLON.serialize()
  12319. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12320. __decorate([
  12321. BABYLON.serialize()
  12322. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12323. __decorate([
  12324. BABYLON.serialize()
  12325. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12326. __decorate([
  12327. BABYLON.serialize()
  12328. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12329. __decorate([
  12330. BABYLON.serialize()
  12331. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12332. __decorate([
  12333. BABYLON.serialize()
  12334. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12335. __decorate([
  12336. BABYLON.serialize()
  12337. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12338. __decorate([
  12339. BABYLON.serialize()
  12340. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12341. __decorate([
  12342. BABYLON.serialize()
  12343. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12356. __decorate([
  12357. BABYLON.serialize()
  12358. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12359. __decorate([
  12360. BABYLON.serialize()
  12361. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12362. __decorate([
  12363. BABYLON.serialize()
  12364. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12368. return ArcRotateCamera;
  12369. })(BABYLON.TargetCamera);
  12370. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12371. })(BABYLON || (BABYLON = {}));
  12372. var BABYLON;
  12373. (function (BABYLON) {
  12374. var RenderingManager = (function () {
  12375. function RenderingManager(scene) {
  12376. this._renderingGroups = new Array();
  12377. this._scene = scene;
  12378. }
  12379. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12380. if (this._scene._activeParticleSystems.length === 0) {
  12381. return;
  12382. }
  12383. // Particles
  12384. var activeCamera = this._scene.activeCamera;
  12385. var beforeParticlesDate = BABYLON.Tools.Now;
  12386. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12387. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12388. if (particleSystem.renderingGroupId !== index) {
  12389. continue;
  12390. }
  12391. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12392. continue;
  12393. }
  12394. this._clearDepthBuffer();
  12395. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12396. this._scene._activeParticles += particleSystem.render();
  12397. }
  12398. }
  12399. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12400. };
  12401. RenderingManager.prototype._renderSprites = function (index) {
  12402. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12403. return;
  12404. }
  12405. // Sprites
  12406. var activeCamera = this._scene.activeCamera;
  12407. var beforeSpritessDate = BABYLON.Tools.Now;
  12408. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12409. var spriteManager = this._scene.spriteManagers[id];
  12410. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12411. this._clearDepthBuffer();
  12412. spriteManager.render();
  12413. }
  12414. }
  12415. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12416. };
  12417. RenderingManager.prototype._clearDepthBuffer = function () {
  12418. if (this._depthBufferAlreadyCleaned) {
  12419. return;
  12420. }
  12421. this._scene.getEngine().clear(0, false, true);
  12422. this._depthBufferAlreadyCleaned = true;
  12423. };
  12424. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12425. if (this._currentRenderSprites) {
  12426. this._renderSprites(this._currentIndex);
  12427. }
  12428. if (this._currentRenderParticles) {
  12429. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12430. }
  12431. };
  12432. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12433. this._currentActiveMeshes = activeMeshes;
  12434. this._currentRenderParticles = renderParticles;
  12435. this._currentRenderSprites = renderSprites;
  12436. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12437. this._depthBufferAlreadyCleaned = index == 0;
  12438. var renderingGroup = this._renderingGroups[index];
  12439. var needToStepBack = false;
  12440. this._currentIndex = index;
  12441. if (renderingGroup) {
  12442. this._clearDepthBuffer();
  12443. if (!renderingGroup.onBeforeTransparentRendering) {
  12444. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12445. }
  12446. if (!renderingGroup.render(customRenderFunction)) {
  12447. this._renderingGroups.splice(index, 1);
  12448. needToStepBack = true;
  12449. this._renderSpritesAndParticles();
  12450. }
  12451. }
  12452. else {
  12453. this._renderSpritesAndParticles();
  12454. }
  12455. if (needToStepBack) {
  12456. index--;
  12457. }
  12458. }
  12459. };
  12460. RenderingManager.prototype.reset = function () {
  12461. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12462. if (renderingGroup) {
  12463. renderingGroup.prepare();
  12464. }
  12465. });
  12466. };
  12467. RenderingManager.prototype.dispatch = function (subMesh) {
  12468. var mesh = subMesh.getMesh();
  12469. var renderingGroupId = mesh.renderingGroupId || 0;
  12470. if (!this._renderingGroups[renderingGroupId]) {
  12471. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12472. }
  12473. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12474. };
  12475. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12476. return RenderingManager;
  12477. })();
  12478. BABYLON.RenderingManager = RenderingManager;
  12479. })(BABYLON || (BABYLON = {}));
  12480. var BABYLON;
  12481. (function (BABYLON) {
  12482. var RenderingGroup = (function () {
  12483. function RenderingGroup(index, scene) {
  12484. this.index = index;
  12485. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12486. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12487. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12488. this._scene = scene;
  12489. }
  12490. RenderingGroup.prototype.render = function (customRenderFunction) {
  12491. if (customRenderFunction) {
  12492. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12493. return true;
  12494. }
  12495. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12496. if (this.onBeforeTransparentRendering) {
  12497. this.onBeforeTransparentRendering();
  12498. }
  12499. return false;
  12500. }
  12501. var engine = this._scene.getEngine();
  12502. // Opaque
  12503. var subIndex;
  12504. var submesh;
  12505. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12506. submesh = this._opaqueSubMeshes.data[subIndex];
  12507. submesh.render(false);
  12508. }
  12509. // Alpha test
  12510. engine.setAlphaTesting(true);
  12511. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12512. submesh = this._alphaTestSubMeshes.data[subIndex];
  12513. submesh.render(false);
  12514. }
  12515. engine.setAlphaTesting(false);
  12516. if (this.onBeforeTransparentRendering) {
  12517. this.onBeforeTransparentRendering();
  12518. }
  12519. // Transparent
  12520. if (this._transparentSubMeshes.length) {
  12521. // Sorting
  12522. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12523. submesh = this._transparentSubMeshes.data[subIndex];
  12524. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12525. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12526. }
  12527. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12528. sortedArray.sort(function (a, b) {
  12529. // Alpha index first
  12530. if (a._alphaIndex > b._alphaIndex) {
  12531. return 1;
  12532. }
  12533. if (a._alphaIndex < b._alphaIndex) {
  12534. return -1;
  12535. }
  12536. // Then distance to camera
  12537. if (a._distanceToCamera < b._distanceToCamera) {
  12538. return 1;
  12539. }
  12540. if (a._distanceToCamera > b._distanceToCamera) {
  12541. return -1;
  12542. }
  12543. return 0;
  12544. });
  12545. // Rendering
  12546. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12547. submesh = sortedArray[subIndex];
  12548. submesh.render(true);
  12549. }
  12550. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12551. }
  12552. return true;
  12553. };
  12554. RenderingGroup.prototype.prepare = function () {
  12555. this._opaqueSubMeshes.reset();
  12556. this._transparentSubMeshes.reset();
  12557. this._alphaTestSubMeshes.reset();
  12558. };
  12559. RenderingGroup.prototype.dispatch = function (subMesh) {
  12560. var material = subMesh.getMaterial();
  12561. var mesh = subMesh.getMesh();
  12562. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12563. this._transparentSubMeshes.push(subMesh);
  12564. }
  12565. else if (material.needAlphaTesting()) {
  12566. this._alphaTestSubMeshes.push(subMesh);
  12567. }
  12568. else {
  12569. this._opaqueSubMeshes.push(subMesh); // Opaque
  12570. }
  12571. };
  12572. return RenderingGroup;
  12573. })();
  12574. BABYLON.RenderingGroup = RenderingGroup;
  12575. })(BABYLON || (BABYLON = {}));
  12576. var BABYLON;
  12577. (function (BABYLON) {
  12578. /**
  12579. * Represents a scene to be rendered by the engine.
  12580. * @see http://doc.babylonjs.com/page.php?p=21911
  12581. */
  12582. var Scene = (function () {
  12583. /**
  12584. * @constructor
  12585. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12586. */
  12587. function Scene(engine) {
  12588. // Members
  12589. this.autoClear = true;
  12590. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12591. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12592. this.forceWireframe = false;
  12593. this.forcePointsCloud = false;
  12594. this.forceShowBoundingBoxes = false;
  12595. this.animationsEnabled = true;
  12596. this.constantlyUpdateMeshUnderPointer = false;
  12597. // Animations
  12598. this.animations = [];
  12599. 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
  12600. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12601. this._startingPointerTime = 0;
  12602. // Fog
  12603. /**
  12604. * is fog enabled on this scene.
  12605. * @type {boolean}
  12606. */
  12607. this.fogEnabled = true;
  12608. this.fogMode = Scene.FOGMODE_NONE;
  12609. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12610. this.fogDensity = 0.1;
  12611. this.fogStart = 0;
  12612. this.fogEnd = 1000.0;
  12613. // Lights
  12614. /**
  12615. * is shadow enabled on this scene.
  12616. * @type {boolean}
  12617. */
  12618. this.shadowsEnabled = true;
  12619. /**
  12620. * is light enabled on this scene.
  12621. * @type {boolean}
  12622. */
  12623. this.lightsEnabled = true;
  12624. /**
  12625. * All of the lights added to this scene.
  12626. * @see BABYLON.Light
  12627. * @type {BABYLON.Light[]}
  12628. */
  12629. this.lights = new Array();
  12630. // Cameras
  12631. /**
  12632. * All of the cameras added to this scene.
  12633. * @see BABYLON.Camera
  12634. * @type {BABYLON.Camera[]}
  12635. */
  12636. this.cameras = new Array();
  12637. this.activeCameras = new Array();
  12638. // Meshes
  12639. /**
  12640. * All of the (abstract) meshes added to this scene.
  12641. * @see BABYLON.AbstractMesh
  12642. * @type {BABYLON.AbstractMesh[]}
  12643. */
  12644. this.meshes = new Array();
  12645. // Geometries
  12646. this._geometries = new Array();
  12647. this.materials = new Array();
  12648. this.multiMaterials = new Array();
  12649. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12650. // Textures
  12651. this.texturesEnabled = true;
  12652. this.textures = new Array();
  12653. // Particles
  12654. this.particlesEnabled = true;
  12655. this.particleSystems = new Array();
  12656. // Sprites
  12657. this.spritesEnabled = true;
  12658. this.spriteManagers = new Array();
  12659. // Layers
  12660. this.layers = new Array();
  12661. // Skeletons
  12662. this.skeletonsEnabled = true;
  12663. this.skeletons = new Array();
  12664. // Lens flares
  12665. this.lensFlaresEnabled = true;
  12666. this.lensFlareSystems = new Array();
  12667. // Collisions
  12668. this.collisionsEnabled = true;
  12669. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12670. // Postprocesses
  12671. this.postProcessesEnabled = true;
  12672. // Customs render targets
  12673. this.renderTargetsEnabled = true;
  12674. this.dumpNextRenderTargets = false;
  12675. this.customRenderTargets = new Array();
  12676. // Imported meshes
  12677. this.importedMeshesFiles = new Array();
  12678. // Probes
  12679. this.probesEnabled = true;
  12680. this.reflectionProbes = new Array();
  12681. this._actionManagers = new Array();
  12682. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12683. // Procedural textures
  12684. this.proceduralTexturesEnabled = true;
  12685. this._proceduralTextures = new Array();
  12686. this.soundTracks = new Array();
  12687. this._audioEnabled = true;
  12688. this._headphone = false;
  12689. this._totalVertices = 0;
  12690. this._activeIndices = 0;
  12691. this._activeParticles = 0;
  12692. this._lastFrameDuration = 0;
  12693. this._evaluateActiveMeshesDuration = 0;
  12694. this._renderTargetsDuration = 0;
  12695. this._particlesDuration = 0;
  12696. this._renderDuration = 0;
  12697. this._spritesDuration = 0;
  12698. this._animationRatio = 0;
  12699. this._renderId = 0;
  12700. this._executeWhenReadyTimeoutId = -1;
  12701. this._toBeDisposed = new BABYLON.SmartArray(256);
  12702. this._onReadyCallbacks = new Array();
  12703. this._pendingData = []; //ANY
  12704. this._onBeforeRenderCallbacks = new Array();
  12705. this._onAfterRenderCallbacks = new Array();
  12706. this._activeMeshes = new BABYLON.SmartArray(256);
  12707. this._processedMaterials = new BABYLON.SmartArray(256);
  12708. this._renderTargets = new BABYLON.SmartArray(256);
  12709. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12710. this._activeSkeletons = new BABYLON.SmartArray(32);
  12711. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12712. this._activeBones = 0;
  12713. this._activeAnimatables = new Array();
  12714. this._transformMatrix = BABYLON.Matrix.Zero();
  12715. this._edgesRenderers = new BABYLON.SmartArray(16);
  12716. this._uniqueIdCounter = 0;
  12717. this._engine = engine;
  12718. engine.scenes.push(this);
  12719. this._renderingManager = new BABYLON.RenderingManager(this);
  12720. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12721. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12722. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12723. if (BABYLON.OutlineRenderer) {
  12724. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12725. }
  12726. this.attachControl();
  12727. this._debugLayer = new BABYLON.DebugLayer(this);
  12728. if (BABYLON.SoundTrack) {
  12729. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12730. }
  12731. //simplification queue
  12732. if (BABYLON.SimplificationQueue) {
  12733. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12734. }
  12735. //collision coordinator initialization. For now legacy per default.
  12736. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12737. }
  12738. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12739. get: function () {
  12740. return Scene._FOGMODE_NONE;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12746. get: function () {
  12747. return Scene._FOGMODE_EXP;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12753. get: function () {
  12754. return Scene._FOGMODE_EXP2;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12760. get: function () {
  12761. return Scene._FOGMODE_LINEAR;
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(Scene.prototype, "debugLayer", {
  12767. // Properties
  12768. get: function () {
  12769. return this._debugLayer;
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12775. get: function () {
  12776. return this._workerCollisions;
  12777. },
  12778. set: function (enabled) {
  12779. enabled = (enabled && !!Worker);
  12780. this._workerCollisions = enabled;
  12781. if (this.collisionCoordinator) {
  12782. this.collisionCoordinator.destroy();
  12783. }
  12784. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12785. this.collisionCoordinator.init(this);
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12791. get: function () {
  12792. return this._selectionOctree;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12798. /**
  12799. * The mesh that is currently under the pointer.
  12800. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12801. */
  12802. get: function () {
  12803. return this._pointerOverMesh;
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Object.defineProperty(Scene.prototype, "pointerX", {
  12809. /**
  12810. * Current on-screen X position of the pointer
  12811. * @return {number} X position of the pointer
  12812. */
  12813. get: function () {
  12814. return this._pointerX;
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(Scene.prototype, "pointerY", {
  12820. /**
  12821. * Current on-screen Y position of the pointer
  12822. * @return {number} Y position of the pointer
  12823. */
  12824. get: function () {
  12825. return this._pointerY;
  12826. },
  12827. enumerable: true,
  12828. configurable: true
  12829. });
  12830. Scene.prototype.getCachedMaterial = function () {
  12831. return this._cachedMaterial;
  12832. };
  12833. Scene.prototype.getBoundingBoxRenderer = function () {
  12834. return this._boundingBoxRenderer;
  12835. };
  12836. Scene.prototype.getOutlineRenderer = function () {
  12837. return this._outlineRenderer;
  12838. };
  12839. Scene.prototype.getEngine = function () {
  12840. return this._engine;
  12841. };
  12842. Scene.prototype.getTotalVertices = function () {
  12843. return this._totalVertices;
  12844. };
  12845. Scene.prototype.getActiveIndices = function () {
  12846. return this._activeIndices;
  12847. };
  12848. Scene.prototype.getActiveParticles = function () {
  12849. return this._activeParticles;
  12850. };
  12851. Scene.prototype.getActiveBones = function () {
  12852. return this._activeBones;
  12853. };
  12854. // Stats
  12855. Scene.prototype.getLastFrameDuration = function () {
  12856. return this._lastFrameDuration;
  12857. };
  12858. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12859. return this._evaluateActiveMeshesDuration;
  12860. };
  12861. Scene.prototype.getActiveMeshes = function () {
  12862. return this._activeMeshes;
  12863. };
  12864. Scene.prototype.getRenderTargetsDuration = function () {
  12865. return this._renderTargetsDuration;
  12866. };
  12867. Scene.prototype.getRenderDuration = function () {
  12868. return this._renderDuration;
  12869. };
  12870. Scene.prototype.getParticlesDuration = function () {
  12871. return this._particlesDuration;
  12872. };
  12873. Scene.prototype.getSpritesDuration = function () {
  12874. return this._spritesDuration;
  12875. };
  12876. Scene.prototype.getAnimationRatio = function () {
  12877. return this._animationRatio;
  12878. };
  12879. Scene.prototype.getRenderId = function () {
  12880. return this._renderId;
  12881. };
  12882. Scene.prototype.incrementRenderId = function () {
  12883. this._renderId++;
  12884. };
  12885. Scene.prototype._updatePointerPosition = function (evt) {
  12886. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12887. this._pointerX = evt.clientX - canvasRect.left;
  12888. this._pointerY = evt.clientY - canvasRect.top;
  12889. this._unTranslatedPointerX = this._pointerX;
  12890. this._unTranslatedPointerY = this._pointerY;
  12891. if (this.cameraToUseForPointers) {
  12892. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12893. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12894. }
  12895. };
  12896. // Pointers handling
  12897. Scene.prototype.attachControl = function () {
  12898. var _this = this;
  12899. var spritePredicate = function (sprite) {
  12900. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12901. };
  12902. this._onPointerMove = function (evt) {
  12903. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12904. return;
  12905. }
  12906. var canvas = _this._engine.getRenderingCanvas();
  12907. _this._updatePointerPosition(evt);
  12908. // Meshes
  12909. 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);
  12910. if (pickResult.hit && pickResult.pickedMesh) {
  12911. _this.setPointerOverSprite(null);
  12912. _this.setPointerOverMesh(pickResult.pickedMesh);
  12913. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12914. canvas.style.cursor = "pointer";
  12915. }
  12916. else {
  12917. canvas.style.cursor = "";
  12918. }
  12919. }
  12920. else {
  12921. _this.setPointerOverMesh(null);
  12922. // Sprites
  12923. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12924. if (pickResult.hit && pickResult.pickedSprite) {
  12925. canvas.style.cursor = "pointer";
  12926. _this.setPointerOverSprite(pickResult.pickedSprite);
  12927. }
  12928. else {
  12929. _this.setPointerOverSprite(null);
  12930. // Restore pointer
  12931. canvas.style.cursor = "";
  12932. }
  12933. }
  12934. if (_this.onPointerMove) {
  12935. _this.onPointerMove(evt, pickResult);
  12936. }
  12937. };
  12938. this._onPointerDown = function (evt) {
  12939. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12940. return;
  12941. }
  12942. _this._updatePointerPosition(evt);
  12943. _this._startingPointerPosition.x = _this._pointerX;
  12944. _this._startingPointerPosition.y = _this._pointerY;
  12945. _this._startingPointerTime = new Date().getTime();
  12946. var predicate = null;
  12947. // Meshes
  12948. _this._pickedDownMesh = null;
  12949. if (!_this.onPointerDown && !_this.onPointerPick) {
  12950. predicate = function (mesh) {
  12951. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12952. };
  12953. }
  12954. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12955. if (pickResult.hit && pickResult.pickedMesh) {
  12956. if (pickResult.pickedMesh.actionManager) {
  12957. _this._pickedDownMesh = pickResult.pickedMesh;
  12958. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12959. switch (evt.button) {
  12960. case 0:
  12961. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12962. break;
  12963. case 1:
  12964. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12965. break;
  12966. case 2:
  12967. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12968. break;
  12969. }
  12970. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12971. }
  12972. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12973. var that = _this;
  12974. window.setTimeout(function () {
  12975. 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);
  12976. if (pickResult.hit && pickResult.pickedMesh) {
  12977. if (pickResult.pickedMesh.actionManager) {
  12978. 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)) {
  12979. that._startingPointerTime = 0;
  12980. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12981. }
  12982. }
  12983. }
  12984. }, BABYLON.ActionManager.LongPressDelay);
  12985. }
  12986. }
  12987. }
  12988. if (_this.onPointerDown) {
  12989. _this.onPointerDown(evt, pickResult);
  12990. }
  12991. // Sprites
  12992. _this._pickedDownSprite = null;
  12993. if (_this.spriteManagers.length > 0) {
  12994. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12995. if (pickResult.hit && pickResult.pickedSprite) {
  12996. if (pickResult.pickedSprite.actionManager) {
  12997. _this._pickedDownSprite = pickResult.pickedSprite;
  12998. switch (evt.button) {
  12999. case 0:
  13000. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13001. break;
  13002. case 1:
  13003. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13004. break;
  13005. case 2:
  13006. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13007. break;
  13008. }
  13009. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13010. }
  13011. }
  13012. }
  13013. };
  13014. this._onPointerUp = function (evt) {
  13015. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13016. return;
  13017. }
  13018. var predicate = null;
  13019. _this._updatePointerPosition(evt);
  13020. if (!_this.onPointerUp && !_this.onPointerPick) {
  13021. predicate = function (mesh) {
  13022. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  13023. };
  13024. }
  13025. // Meshes
  13026. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  13027. if (pickResult.hit && pickResult.pickedMesh) {
  13028. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13029. _this.onPointerPick(evt, pickResult);
  13030. }
  13031. if (pickResult.pickedMesh.actionManager) {
  13032. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13033. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13034. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13035. }
  13036. }
  13037. }
  13038. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13039. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13040. }
  13041. if (_this.onPointerUp) {
  13042. _this.onPointerUp(evt, pickResult);
  13043. }
  13044. _this._startingPointerTime = 0;
  13045. // Sprites
  13046. if (_this.spriteManagers.length > 0) {
  13047. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13048. if (pickResult.hit && pickResult.pickedSprite) {
  13049. if (pickResult.pickedSprite.actionManager) {
  13050. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13051. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13052. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13053. }
  13054. }
  13055. }
  13056. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13057. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13058. }
  13059. }
  13060. };
  13061. this._onKeyDown = function (evt) {
  13062. if (_this.actionManager) {
  13063. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13064. }
  13065. };
  13066. this._onKeyUp = function (evt) {
  13067. if (_this.actionManager) {
  13068. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13069. }
  13070. };
  13071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13072. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13073. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13074. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13075. // Wheel
  13076. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13077. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13078. BABYLON.Tools.RegisterTopRootEvents([
  13079. { name: "keydown", handler: this._onKeyDown },
  13080. { name: "keyup", handler: this._onKeyUp }
  13081. ]);
  13082. };
  13083. Scene.prototype.detachControl = function () {
  13084. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13085. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13086. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13087. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13088. // Wheel
  13089. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13090. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13091. BABYLON.Tools.UnregisterTopRootEvents([
  13092. { name: "keydown", handler: this._onKeyDown },
  13093. { name: "keyup", handler: this._onKeyUp }
  13094. ]);
  13095. };
  13096. // Ready
  13097. Scene.prototype.isReady = function () {
  13098. if (this._pendingData.length > 0) {
  13099. return false;
  13100. }
  13101. var index;
  13102. for (index = 0; index < this._geometries.length; index++) {
  13103. var geometry = this._geometries[index];
  13104. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13105. return false;
  13106. }
  13107. }
  13108. for (index = 0; index < this.meshes.length; index++) {
  13109. var mesh = this.meshes[index];
  13110. if (!mesh.isReady()) {
  13111. return false;
  13112. }
  13113. var mat = mesh.material;
  13114. if (mat) {
  13115. if (!mat.isReady(mesh)) {
  13116. return false;
  13117. }
  13118. }
  13119. }
  13120. return true;
  13121. };
  13122. Scene.prototype.resetCachedMaterial = function () {
  13123. this._cachedMaterial = null;
  13124. };
  13125. Scene.prototype.registerBeforeRender = function (func) {
  13126. this._onBeforeRenderCallbacks.push(func);
  13127. };
  13128. Scene.prototype.unregisterBeforeRender = function (func) {
  13129. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13130. if (index > -1) {
  13131. this._onBeforeRenderCallbacks.splice(index, 1);
  13132. }
  13133. };
  13134. Scene.prototype.registerAfterRender = function (func) {
  13135. this._onAfterRenderCallbacks.push(func);
  13136. };
  13137. Scene.prototype.unregisterAfterRender = function (func) {
  13138. var index = this._onAfterRenderCallbacks.indexOf(func);
  13139. if (index > -1) {
  13140. this._onAfterRenderCallbacks.splice(index, 1);
  13141. }
  13142. };
  13143. Scene.prototype._addPendingData = function (data) {
  13144. this._pendingData.push(data);
  13145. };
  13146. Scene.prototype._removePendingData = function (data) {
  13147. var index = this._pendingData.indexOf(data);
  13148. if (index !== -1) {
  13149. this._pendingData.splice(index, 1);
  13150. }
  13151. };
  13152. Scene.prototype.getWaitingItemsCount = function () {
  13153. return this._pendingData.length;
  13154. };
  13155. /**
  13156. * Registers a function to be executed when the scene is ready.
  13157. * @param {Function} func - the function to be executed.
  13158. */
  13159. Scene.prototype.executeWhenReady = function (func) {
  13160. var _this = this;
  13161. this._onReadyCallbacks.push(func);
  13162. if (this._executeWhenReadyTimeoutId !== -1) {
  13163. return;
  13164. }
  13165. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13166. _this._checkIsReady();
  13167. }, 150);
  13168. };
  13169. Scene.prototype._checkIsReady = function () {
  13170. var _this = this;
  13171. if (this.isReady()) {
  13172. this._onReadyCallbacks.forEach(function (func) {
  13173. func();
  13174. });
  13175. this._onReadyCallbacks = [];
  13176. this._executeWhenReadyTimeoutId = -1;
  13177. return;
  13178. }
  13179. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13180. _this._checkIsReady();
  13181. }, 150);
  13182. };
  13183. // Animations
  13184. /**
  13185. * Will start the animation sequence of a given target
  13186. * @param target - the target
  13187. * @param {number} from - from which frame should animation start
  13188. * @param {number} to - till which frame should animation run.
  13189. * @param {boolean} [loop] - should the animation loop
  13190. * @param {number} [speedRatio] - the speed in which to run the animation
  13191. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13192. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13193. * @return {BABYLON.Animatable} the animatable object created for this animation
  13194. * @see BABYLON.Animatable
  13195. * @see http://doc.babylonjs.com/page.php?p=22081
  13196. */
  13197. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13198. if (speedRatio === void 0) { speedRatio = 1.0; }
  13199. this.stopAnimation(target);
  13200. if (!animatable) {
  13201. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13202. }
  13203. // Local animations
  13204. if (target.animations) {
  13205. animatable.appendAnimations(target, target.animations);
  13206. }
  13207. // Children animations
  13208. if (target.getAnimatables) {
  13209. var animatables = target.getAnimatables();
  13210. for (var index = 0; index < animatables.length; index++) {
  13211. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13212. }
  13213. }
  13214. return animatable;
  13215. };
  13216. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13217. if (speedRatio === undefined) {
  13218. speedRatio = 1.0;
  13219. }
  13220. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13221. return animatable;
  13222. };
  13223. Scene.prototype.getAnimatableByTarget = function (target) {
  13224. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13225. if (this._activeAnimatables[index].target === target) {
  13226. return this._activeAnimatables[index];
  13227. }
  13228. }
  13229. return null;
  13230. };
  13231. Object.defineProperty(Scene.prototype, "Animatables", {
  13232. get: function () {
  13233. return this._activeAnimatables;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. /**
  13239. * Will stop the animation of the given target
  13240. * @param target - the target
  13241. * @see beginAnimation
  13242. */
  13243. Scene.prototype.stopAnimation = function (target) {
  13244. var animatable = this.getAnimatableByTarget(target);
  13245. if (animatable) {
  13246. animatable.stop();
  13247. }
  13248. };
  13249. Scene.prototype._animate = function () {
  13250. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13251. return;
  13252. }
  13253. if (!this._animationStartDate) {
  13254. if (this._pendingData.length > 0) {
  13255. return;
  13256. }
  13257. this._animationStartDate = BABYLON.Tools.Now;
  13258. }
  13259. // Getting time
  13260. var now = BABYLON.Tools.Now;
  13261. var delay = now - this._animationStartDate;
  13262. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13263. this._activeAnimatables[index]._animate(delay);
  13264. }
  13265. };
  13266. // Matrix
  13267. Scene.prototype.getViewMatrix = function () {
  13268. return this._viewMatrix;
  13269. };
  13270. Scene.prototype.getProjectionMatrix = function () {
  13271. return this._projectionMatrix;
  13272. };
  13273. Scene.prototype.getTransformMatrix = function () {
  13274. return this._transformMatrix;
  13275. };
  13276. Scene.prototype.setTransformMatrix = function (view, projection) {
  13277. this._viewMatrix = view;
  13278. this._projectionMatrix = projection;
  13279. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13280. };
  13281. // Methods
  13282. Scene.prototype.addMesh = function (newMesh) {
  13283. newMesh.uniqueId = this._uniqueIdCounter++;
  13284. var position = this.meshes.push(newMesh);
  13285. //notify the collision coordinator
  13286. this.collisionCoordinator.onMeshAdded(newMesh);
  13287. if (this.onNewMeshAdded) {
  13288. this.onNewMeshAdded(newMesh, position, this);
  13289. }
  13290. };
  13291. Scene.prototype.removeMesh = function (toRemove) {
  13292. var index = this.meshes.indexOf(toRemove);
  13293. if (index !== -1) {
  13294. // Remove from the scene if mesh found
  13295. this.meshes.splice(index, 1);
  13296. }
  13297. //notify the collision coordinator
  13298. this.collisionCoordinator.onMeshRemoved(toRemove);
  13299. if (this.onMeshRemoved) {
  13300. this.onMeshRemoved(toRemove);
  13301. }
  13302. return index;
  13303. };
  13304. Scene.prototype.removeSkeleton = function (toRemove) {
  13305. var index = this.skeletons.indexOf(toRemove);
  13306. if (index !== -1) {
  13307. // Remove from the scene if mesh found
  13308. this.skeletons.splice(index, 1);
  13309. }
  13310. return index;
  13311. };
  13312. Scene.prototype.removeLight = function (toRemove) {
  13313. var index = this.lights.indexOf(toRemove);
  13314. if (index !== -1) {
  13315. // Remove from the scene if mesh found
  13316. this.lights.splice(index, 1);
  13317. }
  13318. if (this.onLightRemoved) {
  13319. this.onLightRemoved(toRemove);
  13320. }
  13321. return index;
  13322. };
  13323. Scene.prototype.removeCamera = function (toRemove) {
  13324. var index = this.cameras.indexOf(toRemove);
  13325. if (index !== -1) {
  13326. // Remove from the scene if mesh found
  13327. this.cameras.splice(index, 1);
  13328. }
  13329. // Remove from activeCameras
  13330. var index2 = this.activeCameras.indexOf(toRemove);
  13331. if (index2 !== -1) {
  13332. // Remove from the scene if mesh found
  13333. this.activeCameras.splice(index2, 1);
  13334. }
  13335. // Reset the activeCamera
  13336. if (this.activeCamera === toRemove) {
  13337. if (this.cameras.length > 0) {
  13338. this.activeCamera = this.cameras[0];
  13339. }
  13340. else {
  13341. this.activeCamera = null;
  13342. }
  13343. }
  13344. if (this.onCameraRemoved) {
  13345. this.onCameraRemoved(toRemove);
  13346. }
  13347. return index;
  13348. };
  13349. Scene.prototype.addLight = function (newLight) {
  13350. newLight.uniqueId = this._uniqueIdCounter++;
  13351. var position = this.lights.push(newLight);
  13352. if (this.onNewLightAdded) {
  13353. this.onNewLightAdded(newLight, position, this);
  13354. }
  13355. };
  13356. Scene.prototype.addCamera = function (newCamera) {
  13357. newCamera.uniqueId = this._uniqueIdCounter++;
  13358. var position = this.cameras.push(newCamera);
  13359. if (this.onNewCameraAdded) {
  13360. this.onNewCameraAdded(newCamera, position, this);
  13361. }
  13362. };
  13363. /**
  13364. * Switch active camera
  13365. * @param {Camera} newCamera - new active camera
  13366. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13367. */
  13368. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13369. if (attachControl === void 0) { attachControl = true; }
  13370. var canvas = this._engine.getRenderingCanvas();
  13371. this.activeCamera.detachControl(canvas);
  13372. this.activeCamera = newCamera;
  13373. if (attachControl) {
  13374. newCamera.attachControl(canvas);
  13375. }
  13376. };
  13377. /**
  13378. * sets the active camera of the scene using its ID
  13379. * @param {string} id - the camera's ID
  13380. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13381. * @see activeCamera
  13382. */
  13383. Scene.prototype.setActiveCameraByID = function (id) {
  13384. var camera = this.getCameraByID(id);
  13385. if (camera) {
  13386. this.activeCamera = camera;
  13387. return camera;
  13388. }
  13389. return null;
  13390. };
  13391. /**
  13392. * sets the active camera of the scene using its name
  13393. * @param {string} name - the camera's name
  13394. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13395. * @see activeCamera
  13396. */
  13397. Scene.prototype.setActiveCameraByName = function (name) {
  13398. var camera = this.getCameraByName(name);
  13399. if (camera) {
  13400. this.activeCamera = camera;
  13401. return camera;
  13402. }
  13403. return null;
  13404. };
  13405. /**
  13406. * get a material using its id
  13407. * @param {string} the material's ID
  13408. * @return {BABYLON.Material|null} the material or null if none found.
  13409. */
  13410. Scene.prototype.getMaterialByID = function (id) {
  13411. for (var index = 0; index < this.materials.length; index++) {
  13412. if (this.materials[index].id === id) {
  13413. return this.materials[index];
  13414. }
  13415. }
  13416. return null;
  13417. };
  13418. /**
  13419. * get a material using its name
  13420. * @param {string} the material's name
  13421. * @return {BABYLON.Material|null} the material or null if none found.
  13422. */
  13423. Scene.prototype.getMaterialByName = function (name) {
  13424. for (var index = 0; index < this.materials.length; index++) {
  13425. if (this.materials[index].name === name) {
  13426. return this.materials[index];
  13427. }
  13428. }
  13429. return null;
  13430. };
  13431. Scene.prototype.getLensFlareSystemByName = function (name) {
  13432. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13433. if (this.lensFlareSystems[index].name === name) {
  13434. return this.lensFlareSystems[index];
  13435. }
  13436. }
  13437. return null;
  13438. };
  13439. Scene.prototype.getCameraByID = function (id) {
  13440. for (var index = 0; index < this.cameras.length; index++) {
  13441. if (this.cameras[index].id === id) {
  13442. return this.cameras[index];
  13443. }
  13444. }
  13445. return null;
  13446. };
  13447. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13448. for (var index = 0; index < this.cameras.length; index++) {
  13449. if (this.cameras[index].uniqueId === uniqueId) {
  13450. return this.cameras[index];
  13451. }
  13452. }
  13453. return null;
  13454. };
  13455. /**
  13456. * get a camera using its name
  13457. * @param {string} the camera's name
  13458. * @return {BABYLON.Camera|null} the camera or null if none found.
  13459. */
  13460. Scene.prototype.getCameraByName = function (name) {
  13461. for (var index = 0; index < this.cameras.length; index++) {
  13462. if (this.cameras[index].name === name) {
  13463. return this.cameras[index];
  13464. }
  13465. }
  13466. return null;
  13467. };
  13468. /**
  13469. * get a bone using its id
  13470. * @param {string} the bone's id
  13471. * @return {BABYLON.Bone|null} the bone or null if not found
  13472. */
  13473. Scene.prototype.getBoneByID = function (id) {
  13474. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13475. var skeleton = this.skeletons[skeletonIndex];
  13476. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13477. if (skeleton.bones[boneIndex].id === id) {
  13478. return skeleton.bones[boneIndex];
  13479. }
  13480. }
  13481. }
  13482. return null;
  13483. };
  13484. /**
  13485. * get a bone using its id
  13486. * @param {string} the bone's name
  13487. * @return {BABYLON.Bone|null} the bone or null if not found
  13488. */
  13489. Scene.prototype.getBoneByName = function (name) {
  13490. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13491. var skeleton = this.skeletons[skeletonIndex];
  13492. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13493. if (skeleton.bones[boneIndex].name === name) {
  13494. return skeleton.bones[boneIndex];
  13495. }
  13496. }
  13497. }
  13498. return null;
  13499. };
  13500. /**
  13501. * get a light node using its name
  13502. * @param {string} the light's name
  13503. * @return {BABYLON.Light|null} the light or null if none found.
  13504. */
  13505. Scene.prototype.getLightByName = function (name) {
  13506. for (var index = 0; index < this.lights.length; index++) {
  13507. if (this.lights[index].name === name) {
  13508. return this.lights[index];
  13509. }
  13510. }
  13511. return null;
  13512. };
  13513. /**
  13514. * get a light node using its ID
  13515. * @param {string} the light's id
  13516. * @return {BABYLON.Light|null} the light or null if none found.
  13517. */
  13518. Scene.prototype.getLightByID = function (id) {
  13519. for (var index = 0; index < this.lights.length; index++) {
  13520. if (this.lights[index].id === id) {
  13521. return this.lights[index];
  13522. }
  13523. }
  13524. return null;
  13525. };
  13526. /**
  13527. * get a light node using its scene-generated unique ID
  13528. * @param {number} the light's unique id
  13529. * @return {BABYLON.Light|null} the light or null if none found.
  13530. */
  13531. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13532. for (var index = 0; index < this.lights.length; index++) {
  13533. if (this.lights[index].uniqueId === uniqueId) {
  13534. return this.lights[index];
  13535. }
  13536. }
  13537. return null;
  13538. };
  13539. /**
  13540. * get a particle system by id
  13541. * @param id {number} the particle system id
  13542. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13543. */
  13544. Scene.prototype.getParticleSystemByID = function (id) {
  13545. for (var index = 0; index < this.particleSystems.length; index++) {
  13546. if (this.particleSystems[index].id === id) {
  13547. return this.particleSystems[index];
  13548. }
  13549. }
  13550. return null;
  13551. };
  13552. /**
  13553. * get a geometry using its ID
  13554. * @param {string} the geometry's id
  13555. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13556. */
  13557. Scene.prototype.getGeometryByID = function (id) {
  13558. for (var index = 0; index < this._geometries.length; index++) {
  13559. if (this._geometries[index].id === id) {
  13560. return this._geometries[index];
  13561. }
  13562. }
  13563. return null;
  13564. };
  13565. /**
  13566. * add a new geometry to this scene.
  13567. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13568. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13569. * @return {boolean} was the geometry added or not
  13570. */
  13571. Scene.prototype.pushGeometry = function (geometry, force) {
  13572. if (!force && this.getGeometryByID(geometry.id)) {
  13573. return false;
  13574. }
  13575. this._geometries.push(geometry);
  13576. //notify the collision coordinator
  13577. this.collisionCoordinator.onGeometryAdded(geometry);
  13578. if (this.onGeometryAdded) {
  13579. this.onGeometryAdded(geometry);
  13580. }
  13581. return true;
  13582. };
  13583. /**
  13584. * Removes an existing geometry
  13585. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13586. * @return {boolean} was the geometry removed or not
  13587. */
  13588. Scene.prototype.removeGeometry = function (geometry) {
  13589. var index = this._geometries.indexOf(geometry);
  13590. if (index > -1) {
  13591. this._geometries.splice(index, 1);
  13592. //notify the collision coordinator
  13593. this.collisionCoordinator.onGeometryDeleted(geometry);
  13594. if (this.onGeometryRemoved) {
  13595. this.onGeometryRemoved(geometry);
  13596. }
  13597. return true;
  13598. }
  13599. return false;
  13600. };
  13601. Scene.prototype.getGeometries = function () {
  13602. return this._geometries;
  13603. };
  13604. /**
  13605. * Get the first added mesh found of a given ID
  13606. * @param {string} id - the id to search for
  13607. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13608. */
  13609. Scene.prototype.getMeshByID = function (id) {
  13610. for (var index = 0; index < this.meshes.length; index++) {
  13611. if (this.meshes[index].id === id) {
  13612. return this.meshes[index];
  13613. }
  13614. }
  13615. return null;
  13616. };
  13617. /**
  13618. * Get a mesh with its auto-generated unique id
  13619. * @param {number} uniqueId - the unique id to search for
  13620. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13621. */
  13622. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13623. for (var index = 0; index < this.meshes.length; index++) {
  13624. if (this.meshes[index].uniqueId === uniqueId) {
  13625. return this.meshes[index];
  13626. }
  13627. }
  13628. return null;
  13629. };
  13630. /**
  13631. * Get a the last added mesh found of a given ID
  13632. * @param {string} id - the id to search for
  13633. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13634. */
  13635. Scene.prototype.getLastMeshByID = function (id) {
  13636. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13637. if (this.meshes[index].id === id) {
  13638. return this.meshes[index];
  13639. }
  13640. }
  13641. return null;
  13642. };
  13643. /**
  13644. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13645. * @param {string} id - the id to search for
  13646. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13647. */
  13648. Scene.prototype.getLastEntryByID = function (id) {
  13649. var index;
  13650. for (index = this.meshes.length - 1; index >= 0; index--) {
  13651. if (this.meshes[index].id === id) {
  13652. return this.meshes[index];
  13653. }
  13654. }
  13655. for (index = this.cameras.length - 1; index >= 0; index--) {
  13656. if (this.cameras[index].id === id) {
  13657. return this.cameras[index];
  13658. }
  13659. }
  13660. for (index = this.lights.length - 1; index >= 0; index--) {
  13661. if (this.lights[index].id === id) {
  13662. return this.lights[index];
  13663. }
  13664. }
  13665. return null;
  13666. };
  13667. Scene.prototype.getNodeByID = function (id) {
  13668. var mesh = this.getMeshByID(id);
  13669. if (mesh) {
  13670. return mesh;
  13671. }
  13672. var light = this.getLightByID(id);
  13673. if (light) {
  13674. return light;
  13675. }
  13676. var camera = this.getCameraByID(id);
  13677. if (camera) {
  13678. return camera;
  13679. }
  13680. var bone = this.getBoneByID(id);
  13681. return bone;
  13682. };
  13683. Scene.prototype.getNodeByName = function (name) {
  13684. var mesh = this.getMeshByName(name);
  13685. if (mesh) {
  13686. return mesh;
  13687. }
  13688. var light = this.getLightByName(name);
  13689. if (light) {
  13690. return light;
  13691. }
  13692. var camera = this.getCameraByName(name);
  13693. if (camera) {
  13694. return camera;
  13695. }
  13696. var bone = this.getBoneByName(name);
  13697. return bone;
  13698. };
  13699. Scene.prototype.getMeshByName = function (name) {
  13700. for (var index = 0; index < this.meshes.length; index++) {
  13701. if (this.meshes[index].name === name) {
  13702. return this.meshes[index];
  13703. }
  13704. }
  13705. return null;
  13706. };
  13707. Scene.prototype.getSoundByName = function (name) {
  13708. var index;
  13709. if (BABYLON.AudioEngine) {
  13710. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13711. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13712. return this.mainSoundTrack.soundCollection[index];
  13713. }
  13714. }
  13715. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13716. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13717. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13718. return this.soundTracks[sdIndex].soundCollection[index];
  13719. }
  13720. }
  13721. }
  13722. }
  13723. return null;
  13724. };
  13725. Scene.prototype.getLastSkeletonByID = function (id) {
  13726. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13727. if (this.skeletons[index].id === id) {
  13728. return this.skeletons[index];
  13729. }
  13730. }
  13731. return null;
  13732. };
  13733. Scene.prototype.getSkeletonById = function (id) {
  13734. for (var index = 0; index < this.skeletons.length; index++) {
  13735. if (this.skeletons[index].id === id) {
  13736. return this.skeletons[index];
  13737. }
  13738. }
  13739. return null;
  13740. };
  13741. Scene.prototype.getSkeletonByName = function (name) {
  13742. for (var index = 0; index < this.skeletons.length; index++) {
  13743. if (this.skeletons[index].name === name) {
  13744. return this.skeletons[index];
  13745. }
  13746. }
  13747. return null;
  13748. };
  13749. Scene.prototype.isActiveMesh = function (mesh) {
  13750. return (this._activeMeshes.indexOf(mesh) !== -1);
  13751. };
  13752. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13753. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13754. var material = subMesh.getMaterial();
  13755. if (mesh.showSubMeshesBoundingBox) {
  13756. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13757. }
  13758. if (material) {
  13759. // Render targets
  13760. if (material.getRenderTargetTextures) {
  13761. if (this._processedMaterials.indexOf(material) === -1) {
  13762. this._processedMaterials.push(material);
  13763. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13764. }
  13765. }
  13766. // Dispatch
  13767. this._activeIndices += subMesh.indexCount;
  13768. this._renderingManager.dispatch(subMesh);
  13769. }
  13770. }
  13771. };
  13772. Scene.prototype._evaluateActiveMeshes = function () {
  13773. this.activeCamera._activeMeshes.reset();
  13774. this._activeMeshes.reset();
  13775. this._renderingManager.reset();
  13776. this._processedMaterials.reset();
  13777. this._activeParticleSystems.reset();
  13778. this._activeSkeletons.reset();
  13779. this._softwareSkinnedMeshes.reset();
  13780. this._boundingBoxRenderer.reset();
  13781. this._edgesRenderers.reset();
  13782. if (!this._frustumPlanes) {
  13783. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13784. }
  13785. else {
  13786. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13787. }
  13788. // Meshes
  13789. var meshes;
  13790. var len;
  13791. if (this._selectionOctree) {
  13792. var selection = this._selectionOctree.select(this._frustumPlanes);
  13793. meshes = selection.data;
  13794. len = selection.length;
  13795. }
  13796. else {
  13797. len = this.meshes.length;
  13798. meshes = this.meshes;
  13799. }
  13800. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13801. var mesh = meshes[meshIndex];
  13802. if (mesh.isBlocked) {
  13803. continue;
  13804. }
  13805. this._totalVertices += mesh.getTotalVertices();
  13806. if (!mesh.isReady() || !mesh.isEnabled()) {
  13807. continue;
  13808. }
  13809. mesh.computeWorldMatrix();
  13810. // Intersections
  13811. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13812. this._meshesForIntersections.pushNoDuplicate(mesh);
  13813. }
  13814. // Switch to current LOD
  13815. var meshLOD = mesh.getLOD(this.activeCamera);
  13816. if (!meshLOD) {
  13817. continue;
  13818. }
  13819. mesh._preActivate();
  13820. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13821. this._activeMeshes.push(mesh);
  13822. this.activeCamera._activeMeshes.push(mesh);
  13823. mesh._activate(this._renderId);
  13824. this._activeMesh(meshLOD);
  13825. }
  13826. }
  13827. // Particle systems
  13828. var beforeParticlesDate = BABYLON.Tools.Now;
  13829. if (this.particlesEnabled) {
  13830. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13831. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13832. var particleSystem = this.particleSystems[particleIndex];
  13833. if (!particleSystem.isStarted()) {
  13834. continue;
  13835. }
  13836. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13837. this._activeParticleSystems.push(particleSystem);
  13838. particleSystem.animate();
  13839. }
  13840. }
  13841. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13842. }
  13843. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13844. };
  13845. Scene.prototype._activeMesh = function (mesh) {
  13846. if (mesh.skeleton && this.skeletonsEnabled) {
  13847. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13848. if (!mesh.computeBonesUsingShaders) {
  13849. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13850. }
  13851. }
  13852. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13853. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13854. }
  13855. if (mesh._edgesRenderer) {
  13856. this._edgesRenderers.push(mesh._edgesRenderer);
  13857. }
  13858. if (mesh && mesh.subMeshes) {
  13859. // Submeshes Octrees
  13860. var len;
  13861. var subMeshes;
  13862. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13863. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13864. len = intersections.length;
  13865. subMeshes = intersections.data;
  13866. }
  13867. else {
  13868. subMeshes = mesh.subMeshes;
  13869. len = subMeshes.length;
  13870. }
  13871. for (var subIndex = 0; subIndex < len; subIndex++) {
  13872. var subMesh = subMeshes[subIndex];
  13873. this._evaluateSubMesh(subMesh, mesh);
  13874. }
  13875. }
  13876. };
  13877. Scene.prototype.updateTransformMatrix = function (force) {
  13878. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13879. };
  13880. Scene.prototype._renderForCamera = function (camera) {
  13881. var engine = this._engine;
  13882. this.activeCamera = camera;
  13883. if (!this.activeCamera)
  13884. throw new Error("Active camera not set");
  13885. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13886. // Viewport
  13887. engine.setViewport(this.activeCamera.viewport);
  13888. // Camera
  13889. this.resetCachedMaterial();
  13890. this._renderId++;
  13891. this.updateTransformMatrix();
  13892. if (this.beforeCameraRender) {
  13893. this.beforeCameraRender(this.activeCamera);
  13894. }
  13895. // Meshes
  13896. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13897. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13898. this._evaluateActiveMeshes();
  13899. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13900. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13901. // Skeletons
  13902. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13903. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13904. skeleton.prepare();
  13905. }
  13906. // Software skinning
  13907. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13908. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13909. mesh.applySkeleton(mesh.skeleton);
  13910. }
  13911. // Render targets
  13912. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13913. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13914. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13915. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13916. var renderTarget = this._renderTargets.data[renderIndex];
  13917. if (renderTarget._shouldRender()) {
  13918. this._renderId++;
  13919. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13920. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13921. }
  13922. }
  13923. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13924. this._renderId++;
  13925. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13926. }
  13927. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13928. // Prepare Frame
  13929. this.postProcessManager._prepareFrame();
  13930. var beforeRenderDate = BABYLON.Tools.Now;
  13931. // Backgrounds
  13932. var layerIndex;
  13933. var layer;
  13934. if (this.layers.length) {
  13935. engine.setDepthBuffer(false);
  13936. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13937. layer = this.layers[layerIndex];
  13938. if (layer.isBackground) {
  13939. layer.render();
  13940. }
  13941. }
  13942. engine.setDepthBuffer(true);
  13943. }
  13944. // Render
  13945. BABYLON.Tools.StartPerformanceCounter("Main render");
  13946. this._renderingManager.render(null, null, true, true);
  13947. BABYLON.Tools.EndPerformanceCounter("Main render");
  13948. // Bounding boxes
  13949. this._boundingBoxRenderer.render();
  13950. // Edges
  13951. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13952. this._edgesRenderers.data[edgesRendererIndex].render();
  13953. }
  13954. // Lens flares
  13955. if (this.lensFlaresEnabled) {
  13956. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13957. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13958. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13959. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13960. lensFlareSystem.render();
  13961. }
  13962. }
  13963. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13964. }
  13965. // Foregrounds
  13966. if (this.layers.length) {
  13967. engine.setDepthBuffer(false);
  13968. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13969. layer = this.layers[layerIndex];
  13970. if (!layer.isBackground) {
  13971. layer.render();
  13972. }
  13973. }
  13974. engine.setDepthBuffer(true);
  13975. }
  13976. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13977. // Finalize frame
  13978. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13979. // Update camera
  13980. this.activeCamera._updateFromScene();
  13981. // Reset some special arrays
  13982. this._renderTargets.reset();
  13983. if (this.afterCameraRender) {
  13984. this.afterCameraRender(this.activeCamera);
  13985. }
  13986. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13987. };
  13988. Scene.prototype._processSubCameras = function (camera) {
  13989. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13990. this._renderForCamera(camera);
  13991. return;
  13992. }
  13993. // rig cameras
  13994. for (var index = 0; index < camera._rigCameras.length; index++) {
  13995. this._renderForCamera(camera._rigCameras[index]);
  13996. }
  13997. this.activeCamera = camera;
  13998. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13999. // Update camera
  14000. this.activeCamera._updateFromScene();
  14001. };
  14002. Scene.prototype._checkIntersections = function () {
  14003. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14004. var sourceMesh = this._meshesForIntersections.data[index];
  14005. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14006. var action = sourceMesh.actionManager.actions[actionIndex];
  14007. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14008. var parameters = action.getTriggerParameter();
  14009. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14010. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14011. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14012. if (areIntersecting && currentIntersectionInProgress === -1) {
  14013. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14014. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14015. sourceMesh._intersectionsInProgress.push(otherMesh);
  14016. }
  14017. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14018. sourceMesh._intersectionsInProgress.push(otherMesh);
  14019. }
  14020. }
  14021. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14022. //They intersected, and now they don't.
  14023. //is this trigger an exit trigger? execute an event.
  14024. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14025. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14026. }
  14027. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14028. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14029. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14030. }
  14031. }
  14032. }
  14033. }
  14034. }
  14035. };
  14036. Scene.prototype.render = function () {
  14037. var startDate = BABYLON.Tools.Now;
  14038. this._particlesDuration = 0;
  14039. this._spritesDuration = 0;
  14040. this._activeParticles = 0;
  14041. this._renderDuration = 0;
  14042. this._renderTargetsDuration = 0;
  14043. this._evaluateActiveMeshesDuration = 0;
  14044. this._totalVertices = 0;
  14045. this._activeIndices = 0;
  14046. this._activeBones = 0;
  14047. this.getEngine().resetDrawCalls();
  14048. this._meshesForIntersections.reset();
  14049. this.resetCachedMaterial();
  14050. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14051. // Actions
  14052. if (this.actionManager) {
  14053. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14054. }
  14055. //Simplification Queue
  14056. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14057. this.simplificationQueue.executeNext();
  14058. }
  14059. // Animations
  14060. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14061. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14062. this._animate();
  14063. // Physics
  14064. if (this._physicsEngine) {
  14065. BABYLON.Tools.StartPerformanceCounter("Physics");
  14066. this._physicsEngine._step(deltaTime / 1000.0);
  14067. BABYLON.Tools.EndPerformanceCounter("Physics");
  14068. }
  14069. // Before render
  14070. if (this.beforeRender) {
  14071. this.beforeRender();
  14072. }
  14073. var callbackIndex;
  14074. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14075. this._onBeforeRenderCallbacks[callbackIndex]();
  14076. }
  14077. // Customs render targets
  14078. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14079. var engine = this.getEngine();
  14080. var currentActiveCamera = this.activeCamera;
  14081. if (this.renderTargetsEnabled) {
  14082. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14083. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14084. var renderTarget = this.customRenderTargets[customIndex];
  14085. if (renderTarget._shouldRender()) {
  14086. this._renderId++;
  14087. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14088. if (!this.activeCamera)
  14089. throw new Error("Active camera not set");
  14090. // Viewport
  14091. engine.setViewport(this.activeCamera.viewport);
  14092. // Camera
  14093. this.updateTransformMatrix();
  14094. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14095. }
  14096. }
  14097. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14098. this._renderId++;
  14099. }
  14100. if (this.customRenderTargets.length > 0) {
  14101. engine.restoreDefaultFramebuffer();
  14102. }
  14103. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14104. this.activeCamera = currentActiveCamera;
  14105. // Procedural textures
  14106. if (this.proceduralTexturesEnabled) {
  14107. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14108. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14109. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14110. if (proceduralTexture._shouldRender()) {
  14111. proceduralTexture.render();
  14112. }
  14113. }
  14114. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14115. }
  14116. // Clear
  14117. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14118. // Shadows
  14119. if (this.shadowsEnabled) {
  14120. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14121. var light = this.lights[lightIndex];
  14122. var shadowGenerator = light.getShadowGenerator();
  14123. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14124. this._renderTargets.push(shadowGenerator.getShadowMap());
  14125. }
  14126. }
  14127. }
  14128. // Depth renderer
  14129. if (this._depthRenderer) {
  14130. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14131. }
  14132. // RenderPipeline
  14133. this.postProcessRenderPipelineManager.update();
  14134. // Multi-cameras?
  14135. if (this.activeCameras.length > 0) {
  14136. var currentRenderId = this._renderId;
  14137. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14138. this._renderId = currentRenderId;
  14139. if (cameraIndex > 0) {
  14140. this._engine.clear(0, false, true);
  14141. }
  14142. this._processSubCameras(this.activeCameras[cameraIndex]);
  14143. }
  14144. }
  14145. else {
  14146. if (!this.activeCamera) {
  14147. throw new Error("No camera defined");
  14148. }
  14149. this._processSubCameras(this.activeCamera);
  14150. }
  14151. // Intersection checks
  14152. this._checkIntersections();
  14153. // Update the audio listener attached to the camera
  14154. if (BABYLON.AudioEngine) {
  14155. this._updateAudioParameters();
  14156. }
  14157. // After render
  14158. if (this.afterRender) {
  14159. this.afterRender();
  14160. }
  14161. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14162. this._onAfterRenderCallbacks[callbackIndex]();
  14163. }
  14164. // Cleaning
  14165. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14166. this._toBeDisposed.data[index].dispose();
  14167. this._toBeDisposed[index] = null;
  14168. }
  14169. this._toBeDisposed.reset();
  14170. if (this.dumpNextRenderTargets) {
  14171. this.dumpNextRenderTargets = false;
  14172. }
  14173. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14174. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14175. };
  14176. Scene.prototype._updateAudioParameters = function () {
  14177. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14178. return;
  14179. }
  14180. var listeningCamera;
  14181. var audioEngine = BABYLON.Engine.audioEngine;
  14182. if (this.activeCameras.length > 0) {
  14183. listeningCamera = this.activeCameras[0];
  14184. }
  14185. else {
  14186. listeningCamera = this.activeCamera;
  14187. }
  14188. if (listeningCamera && audioEngine.canUseWebAudio) {
  14189. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14190. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14191. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14192. cameraDirection.normalize();
  14193. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14194. var i;
  14195. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14196. var sound = this.mainSoundTrack.soundCollection[i];
  14197. if (sound.useCustomAttenuation) {
  14198. sound.updateDistanceFromListener();
  14199. }
  14200. }
  14201. for (i = 0; i < this.soundTracks.length; i++) {
  14202. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14203. sound = this.soundTracks[i].soundCollection[j];
  14204. if (sound.useCustomAttenuation) {
  14205. sound.updateDistanceFromListener();
  14206. }
  14207. }
  14208. }
  14209. }
  14210. };
  14211. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14212. // Audio
  14213. get: function () {
  14214. return this._audioEnabled;
  14215. },
  14216. set: function (value) {
  14217. this._audioEnabled = value;
  14218. if (BABYLON.AudioEngine) {
  14219. if (this._audioEnabled) {
  14220. this._enableAudio();
  14221. }
  14222. else {
  14223. this._disableAudio();
  14224. }
  14225. }
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. Scene.prototype._disableAudio = function () {
  14231. var i;
  14232. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14233. this.mainSoundTrack.soundCollection[i].pause();
  14234. }
  14235. for (i = 0; i < this.soundTracks.length; i++) {
  14236. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14237. this.soundTracks[i].soundCollection[j].pause();
  14238. }
  14239. }
  14240. };
  14241. Scene.prototype._enableAudio = function () {
  14242. var i;
  14243. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14244. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14245. this.mainSoundTrack.soundCollection[i].play();
  14246. }
  14247. }
  14248. for (i = 0; i < this.soundTracks.length; i++) {
  14249. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14250. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14251. this.soundTracks[i].soundCollection[j].play();
  14252. }
  14253. }
  14254. }
  14255. };
  14256. Object.defineProperty(Scene.prototype, "headphone", {
  14257. get: function () {
  14258. return this._headphone;
  14259. },
  14260. set: function (value) {
  14261. this._headphone = value;
  14262. if (BABYLON.AudioEngine) {
  14263. if (this._headphone) {
  14264. this._switchAudioModeForHeadphones();
  14265. }
  14266. else {
  14267. this._switchAudioModeForNormalSpeakers();
  14268. }
  14269. }
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Scene.prototype._switchAudioModeForHeadphones = function () {
  14275. this.mainSoundTrack.switchPanningModelToHRTF();
  14276. for (var i = 0; i < this.soundTracks.length; i++) {
  14277. this.soundTracks[i].switchPanningModelToHRTF();
  14278. }
  14279. };
  14280. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14281. this.mainSoundTrack.switchPanningModelToEqualPower();
  14282. for (var i = 0; i < this.soundTracks.length; i++) {
  14283. this.soundTracks[i].switchPanningModelToEqualPower();
  14284. }
  14285. };
  14286. Scene.prototype.enableDepthRenderer = function () {
  14287. if (this._depthRenderer) {
  14288. return this._depthRenderer;
  14289. }
  14290. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14291. return this._depthRenderer;
  14292. };
  14293. Scene.prototype.disableDepthRenderer = function () {
  14294. if (!this._depthRenderer) {
  14295. return;
  14296. }
  14297. this._depthRenderer.dispose();
  14298. this._depthRenderer = null;
  14299. };
  14300. Scene.prototype.freezeMaterials = function () {
  14301. for (var i = 0; i < this.materials.length; i++) {
  14302. this.materials[i].freeze();
  14303. }
  14304. };
  14305. Scene.prototype.unfreezeMaterials = function () {
  14306. for (var i = 0; i < this.materials.length; i++) {
  14307. this.materials[i].unfreeze();
  14308. }
  14309. };
  14310. Scene.prototype.dispose = function () {
  14311. this.beforeRender = null;
  14312. this.afterRender = null;
  14313. this.skeletons = [];
  14314. this._boundingBoxRenderer.dispose();
  14315. if (this._depthRenderer) {
  14316. this._depthRenderer.dispose();
  14317. }
  14318. // Debug layer
  14319. this.debugLayer.hide();
  14320. // Events
  14321. if (this.onDispose) {
  14322. this.onDispose();
  14323. }
  14324. this._onBeforeRenderCallbacks = [];
  14325. this._onAfterRenderCallbacks = [];
  14326. this.detachControl();
  14327. // Release sounds & sounds tracks
  14328. if (BABYLON.AudioEngine) {
  14329. this.disposeSounds();
  14330. }
  14331. // Detach cameras
  14332. var canvas = this._engine.getRenderingCanvas();
  14333. var index;
  14334. for (index = 0; index < this.cameras.length; index++) {
  14335. this.cameras[index].detachControl(canvas);
  14336. }
  14337. // Release lights
  14338. while (this.lights.length) {
  14339. this.lights[0].dispose();
  14340. }
  14341. // Release meshes
  14342. while (this.meshes.length) {
  14343. this.meshes[0].dispose(true);
  14344. }
  14345. // Release cameras
  14346. while (this.cameras.length) {
  14347. this.cameras[0].dispose();
  14348. }
  14349. // Release materials
  14350. while (this.materials.length) {
  14351. this.materials[0].dispose();
  14352. }
  14353. // Release particles
  14354. while (this.particleSystems.length) {
  14355. this.particleSystems[0].dispose();
  14356. }
  14357. // Release sprites
  14358. while (this.spriteManagers.length) {
  14359. this.spriteManagers[0].dispose();
  14360. }
  14361. // Release layers
  14362. while (this.layers.length) {
  14363. this.layers[0].dispose();
  14364. }
  14365. // Release textures
  14366. while (this.textures.length) {
  14367. this.textures[0].dispose();
  14368. }
  14369. // Post-processes
  14370. this.postProcessManager.dispose();
  14371. // Physics
  14372. if (this._physicsEngine) {
  14373. this.disablePhysicsEngine();
  14374. }
  14375. // Remove from engine
  14376. index = this._engine.scenes.indexOf(this);
  14377. if (index > -1) {
  14378. this._engine.scenes.splice(index, 1);
  14379. }
  14380. this._engine.wipeCaches();
  14381. };
  14382. // Release sounds & sounds tracks
  14383. Scene.prototype.disposeSounds = function () {
  14384. this.mainSoundTrack.dispose();
  14385. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14386. this.soundTracks[scIndex].dispose();
  14387. }
  14388. };
  14389. // Octrees
  14390. Scene.prototype.getWorldExtends = function () {
  14391. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14392. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14393. for (var index = 0; index < this.meshes.length; index++) {
  14394. var mesh = this.meshes[index];
  14395. mesh.computeWorldMatrix(true);
  14396. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14397. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14398. BABYLON.Tools.CheckExtends(minBox, min, max);
  14399. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14400. }
  14401. return {
  14402. min: min,
  14403. max: max
  14404. };
  14405. };
  14406. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14407. if (maxCapacity === void 0) { maxCapacity = 64; }
  14408. if (maxDepth === void 0) { maxDepth = 2; }
  14409. if (!this._selectionOctree) {
  14410. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14411. }
  14412. var worldExtends = this.getWorldExtends();
  14413. // Update octree
  14414. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14415. return this._selectionOctree;
  14416. };
  14417. // Picking
  14418. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14419. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14420. var engine = this._engine;
  14421. if (!camera) {
  14422. if (!this.activeCamera)
  14423. throw new Error("Active camera not set");
  14424. camera = this.activeCamera;
  14425. }
  14426. var cameraViewport = camera.viewport;
  14427. var viewport = cameraViewport.toGlobal(engine);
  14428. // Moving coordinates to local viewport world
  14429. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14430. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14431. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14432. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14433. };
  14434. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14435. var engine = this._engine;
  14436. if (!camera) {
  14437. if (!this.activeCamera)
  14438. throw new Error("Active camera not set");
  14439. camera = this.activeCamera;
  14440. }
  14441. var cameraViewport = camera.viewport;
  14442. var viewport = cameraViewport.toGlobal(engine);
  14443. var identity = BABYLON.Matrix.Identity();
  14444. // Moving coordinates to local viewport world
  14445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14447. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14448. };
  14449. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14450. var pickingInfo = null;
  14451. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14452. var mesh = this.meshes[meshIndex];
  14453. if (predicate) {
  14454. if (!predicate(mesh)) {
  14455. continue;
  14456. }
  14457. }
  14458. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14459. continue;
  14460. }
  14461. var world = mesh.getWorldMatrix();
  14462. var ray = rayFunction(world);
  14463. var result = mesh.intersects(ray, fastCheck);
  14464. if (!result || !result.hit)
  14465. continue;
  14466. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14467. continue;
  14468. pickingInfo = result;
  14469. if (fastCheck) {
  14470. break;
  14471. }
  14472. }
  14473. return pickingInfo || new BABYLON.PickingInfo();
  14474. };
  14475. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14476. var pickingInfo = null;
  14477. camera = camera || this.activeCamera;
  14478. if (this.spriteManagers.length > 0) {
  14479. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14480. var spriteManager = this.spriteManagers[spriteIndex];
  14481. if (!spriteManager.isPickable) {
  14482. continue;
  14483. }
  14484. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14485. if (!result || !result.hit)
  14486. continue;
  14487. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14488. continue;
  14489. pickingInfo = result;
  14490. if (fastCheck) {
  14491. break;
  14492. }
  14493. }
  14494. }
  14495. return pickingInfo || new BABYLON.PickingInfo();
  14496. };
  14497. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14498. var _this = this;
  14499. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14500. /// <param name="x">X position on screen</param>
  14501. /// <param name="y">Y position on screen</param>
  14502. /// <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>
  14503. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14504. /// <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>
  14505. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14506. };
  14507. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14508. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14509. /// <param name="x">X position on screen</param>
  14510. /// <param name="y">Y position on screen</param>
  14511. /// <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>
  14512. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14513. /// <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>
  14514. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14515. };
  14516. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14517. var _this = this;
  14518. return this._internalPick(function (world) {
  14519. if (!_this._pickWithRayInverseMatrix) {
  14520. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14521. }
  14522. world.invertToRef(_this._pickWithRayInverseMatrix);
  14523. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14524. }, predicate, fastCheck);
  14525. };
  14526. Scene.prototype.setPointerOverMesh = function (mesh) {
  14527. if (this._pointerOverMesh === mesh) {
  14528. return;
  14529. }
  14530. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14531. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14532. }
  14533. this._pointerOverMesh = mesh;
  14534. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14535. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14536. }
  14537. };
  14538. Scene.prototype.getPointerOverMesh = function () {
  14539. return this._pointerOverMesh;
  14540. };
  14541. Scene.prototype.setPointerOverSprite = function (sprite) {
  14542. if (this._pointerOverSprite === sprite) {
  14543. return;
  14544. }
  14545. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14546. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14547. }
  14548. this._pointerOverSprite = sprite;
  14549. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14550. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14551. }
  14552. };
  14553. Scene.prototype.getPointerOverSprite = function () {
  14554. return this._pointerOverSprite;
  14555. };
  14556. // Physics
  14557. Scene.prototype.getPhysicsEngine = function () {
  14558. return this._physicsEngine;
  14559. };
  14560. /**
  14561. * Enables physics to the current scene
  14562. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14563. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14564. * @return {boolean} was the physics engine initialized
  14565. */
  14566. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14567. if (this._physicsEngine) {
  14568. return true;
  14569. }
  14570. try {
  14571. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14572. return true;
  14573. }
  14574. catch (e) {
  14575. BABYLON.Tools.Error(e.message);
  14576. return false;
  14577. }
  14578. };
  14579. Scene.prototype.disablePhysicsEngine = function () {
  14580. if (!this._physicsEngine) {
  14581. return;
  14582. }
  14583. this._physicsEngine.dispose();
  14584. this._physicsEngine = undefined;
  14585. };
  14586. Scene.prototype.isPhysicsEnabled = function () {
  14587. return this._physicsEngine !== undefined;
  14588. };
  14589. /**
  14590. *
  14591. * Sets the gravity of the physics engine (and NOT of the scene)
  14592. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14593. */
  14594. Scene.prototype.setGravity = function (gravity) {
  14595. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14596. if (!this._physicsEngine) {
  14597. return;
  14598. }
  14599. this._physicsEngine.setGravity(gravity);
  14600. };
  14601. /**
  14602. * Legacy support, using the new API
  14603. * @Deprecated
  14604. */
  14605. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14606. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14607. if (parts.parts) {
  14608. options = parts;
  14609. parts = parts.parts;
  14610. }
  14611. var mainMesh = parts[0].mesh;
  14612. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14613. for (var index = 1; index < parts.length; index++) {
  14614. var mesh = parts[index].mesh;
  14615. if (mesh.parent !== mainMesh) {
  14616. mesh.position = mesh.position.subtract(mainMesh.position);
  14617. mesh.parent = mainMesh;
  14618. }
  14619. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14620. }
  14621. mainMesh.physicsImpostor.forceUpdate();
  14622. };
  14623. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14624. var mesh = compound.parts[0].mesh;
  14625. mesh.physicsImpostor.dispose(true);
  14626. mesh.physicsImpostor = null;
  14627. };
  14628. // Misc.
  14629. Scene.prototype.createDefaultCameraOrLight = function () {
  14630. // Light
  14631. if (this.lights.length === 0) {
  14632. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14633. }
  14634. // Camera
  14635. if (!this.activeCamera) {
  14636. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14637. // Compute position
  14638. var worldExtends = this.getWorldExtends();
  14639. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14640. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14641. camera.setTarget(worldCenter);
  14642. this.activeCamera = camera;
  14643. }
  14644. };
  14645. // Tags
  14646. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14647. if (tagsQuery === undefined) {
  14648. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14649. return list;
  14650. }
  14651. var listByTags = [];
  14652. forEach = forEach || (function (item) { return; });
  14653. for (var i in list) {
  14654. var item = list[i];
  14655. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14656. listByTags.push(item);
  14657. forEach(item);
  14658. }
  14659. }
  14660. return listByTags;
  14661. };
  14662. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14663. return this._getByTags(this.meshes, tagsQuery, forEach);
  14664. };
  14665. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14666. return this._getByTags(this.cameras, tagsQuery, forEach);
  14667. };
  14668. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14669. return this._getByTags(this.lights, tagsQuery, forEach);
  14670. };
  14671. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14672. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14673. };
  14674. // Statics
  14675. Scene._FOGMODE_NONE = 0;
  14676. Scene._FOGMODE_EXP = 1;
  14677. Scene._FOGMODE_EXP2 = 2;
  14678. Scene._FOGMODE_LINEAR = 3;
  14679. Scene.MinDeltaTime = 1.0;
  14680. Scene.MaxDeltaTime = 1000.0;
  14681. return Scene;
  14682. })();
  14683. BABYLON.Scene = Scene;
  14684. })(BABYLON || (BABYLON = {}));
  14685. var BABYLON;
  14686. (function (BABYLON) {
  14687. var VertexBuffer = (function () {
  14688. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14689. if (engine instanceof BABYLON.Mesh) {
  14690. this._engine = engine.getScene().getEngine();
  14691. }
  14692. else {
  14693. this._engine = engine;
  14694. }
  14695. this._updatable = updatable;
  14696. this._data = data;
  14697. if (!postponeInternalCreation) {
  14698. this.create();
  14699. }
  14700. this._kind = kind;
  14701. if (stride) {
  14702. this._strideSize = stride;
  14703. return;
  14704. }
  14705. // Deduce stride from kind
  14706. switch (kind) {
  14707. case VertexBuffer.PositionKind:
  14708. this._strideSize = 3;
  14709. break;
  14710. case VertexBuffer.NormalKind:
  14711. this._strideSize = 3;
  14712. break;
  14713. case VertexBuffer.UVKind:
  14714. case VertexBuffer.UV2Kind:
  14715. case VertexBuffer.UV3Kind:
  14716. case VertexBuffer.UV4Kind:
  14717. case VertexBuffer.UV5Kind:
  14718. case VertexBuffer.UV6Kind:
  14719. this._strideSize = 2;
  14720. break;
  14721. case VertexBuffer.ColorKind:
  14722. this._strideSize = 4;
  14723. break;
  14724. case VertexBuffer.MatricesIndicesKind:
  14725. case VertexBuffer.MatricesIndicesExtraKind:
  14726. this._strideSize = 4;
  14727. break;
  14728. case VertexBuffer.MatricesWeightsKind:
  14729. case VertexBuffer.MatricesWeightsExtraKind:
  14730. this._strideSize = 4;
  14731. break;
  14732. }
  14733. }
  14734. // Properties
  14735. VertexBuffer.prototype.isUpdatable = function () {
  14736. return this._updatable;
  14737. };
  14738. VertexBuffer.prototype.getData = function () {
  14739. return this._data;
  14740. };
  14741. VertexBuffer.prototype.getBuffer = function () {
  14742. return this._buffer;
  14743. };
  14744. VertexBuffer.prototype.getStrideSize = function () {
  14745. return this._strideSize;
  14746. };
  14747. // Methods
  14748. VertexBuffer.prototype.create = function (data) {
  14749. if (!data && this._buffer) {
  14750. return; // nothing to do
  14751. }
  14752. data = data || this._data;
  14753. if (!this._buffer) {
  14754. if (this._updatable) {
  14755. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14756. }
  14757. else {
  14758. this._buffer = this._engine.createVertexBuffer(data);
  14759. }
  14760. }
  14761. if (this._updatable) {
  14762. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14763. this._data = data;
  14764. }
  14765. };
  14766. VertexBuffer.prototype.update = function (data) {
  14767. this.create(data);
  14768. };
  14769. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14770. if (!this._buffer) {
  14771. return;
  14772. }
  14773. if (this._updatable) {
  14774. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14775. this._data = null;
  14776. }
  14777. };
  14778. VertexBuffer.prototype.dispose = function () {
  14779. if (!this._buffer) {
  14780. return;
  14781. }
  14782. if (this._engine._releaseBuffer(this._buffer)) {
  14783. this._buffer = null;
  14784. }
  14785. };
  14786. Object.defineProperty(VertexBuffer, "PositionKind", {
  14787. get: function () {
  14788. return VertexBuffer._PositionKind;
  14789. },
  14790. enumerable: true,
  14791. configurable: true
  14792. });
  14793. Object.defineProperty(VertexBuffer, "NormalKind", {
  14794. get: function () {
  14795. return VertexBuffer._NormalKind;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(VertexBuffer, "UVKind", {
  14801. get: function () {
  14802. return VertexBuffer._UVKind;
  14803. },
  14804. enumerable: true,
  14805. configurable: true
  14806. });
  14807. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14808. get: function () {
  14809. return VertexBuffer._UV2Kind;
  14810. },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14815. get: function () {
  14816. return VertexBuffer._UV3Kind;
  14817. },
  14818. enumerable: true,
  14819. configurable: true
  14820. });
  14821. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14822. get: function () {
  14823. return VertexBuffer._UV4Kind;
  14824. },
  14825. enumerable: true,
  14826. configurable: true
  14827. });
  14828. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14829. get: function () {
  14830. return VertexBuffer._UV5Kind;
  14831. },
  14832. enumerable: true,
  14833. configurable: true
  14834. });
  14835. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14836. get: function () {
  14837. return VertexBuffer._UV6Kind;
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. Object.defineProperty(VertexBuffer, "ColorKind", {
  14843. get: function () {
  14844. return VertexBuffer._ColorKind;
  14845. },
  14846. enumerable: true,
  14847. configurable: true
  14848. });
  14849. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14850. get: function () {
  14851. return VertexBuffer._MatricesIndicesKind;
  14852. },
  14853. enumerable: true,
  14854. configurable: true
  14855. });
  14856. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14857. get: function () {
  14858. return VertexBuffer._MatricesWeightsKind;
  14859. },
  14860. enumerable: true,
  14861. configurable: true
  14862. });
  14863. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14864. get: function () {
  14865. return VertexBuffer._MatricesIndicesExtraKind;
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14871. get: function () {
  14872. return VertexBuffer._MatricesWeightsExtraKind;
  14873. },
  14874. enumerable: true,
  14875. configurable: true
  14876. });
  14877. // Enums
  14878. VertexBuffer._PositionKind = "position";
  14879. VertexBuffer._NormalKind = "normal";
  14880. VertexBuffer._UVKind = "uv";
  14881. VertexBuffer._UV2Kind = "uv2";
  14882. VertexBuffer._UV3Kind = "uv3";
  14883. VertexBuffer._UV4Kind = "uv4";
  14884. VertexBuffer._UV5Kind = "uv5";
  14885. VertexBuffer._UV6Kind = "uv6";
  14886. VertexBuffer._ColorKind = "color";
  14887. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14888. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14889. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14890. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14891. return VertexBuffer;
  14892. })();
  14893. BABYLON.VertexBuffer = VertexBuffer;
  14894. })(BABYLON || (BABYLON = {}));
  14895. var BABYLON;
  14896. (function (BABYLON) {
  14897. /**
  14898. * Creates an instance based on a source mesh.
  14899. */
  14900. var InstancedMesh = (function (_super) {
  14901. __extends(InstancedMesh, _super);
  14902. function InstancedMesh(name, source) {
  14903. _super.call(this, name, source.getScene());
  14904. source.instances.push(this);
  14905. this._sourceMesh = source;
  14906. this.position.copyFrom(source.position);
  14907. this.rotation.copyFrom(source.rotation);
  14908. this.scaling.copyFrom(source.scaling);
  14909. if (source.rotationQuaternion) {
  14910. this.rotationQuaternion = source.rotationQuaternion.clone();
  14911. }
  14912. this.infiniteDistance = source.infiniteDistance;
  14913. this.setPivotMatrix(source.getPivotMatrix());
  14914. this.refreshBoundingInfo();
  14915. this._syncSubMeshes();
  14916. }
  14917. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14918. // Methods
  14919. get: function () {
  14920. return this._sourceMesh.receiveShadows;
  14921. },
  14922. enumerable: true,
  14923. configurable: true
  14924. });
  14925. Object.defineProperty(InstancedMesh.prototype, "material", {
  14926. get: function () {
  14927. return this._sourceMesh.material;
  14928. },
  14929. enumerable: true,
  14930. configurable: true
  14931. });
  14932. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14933. get: function () {
  14934. return this._sourceMesh.visibility;
  14935. },
  14936. enumerable: true,
  14937. configurable: true
  14938. });
  14939. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14940. get: function () {
  14941. return this._sourceMesh.skeleton;
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14947. get: function () {
  14948. return this._sourceMesh.renderingGroupId;
  14949. },
  14950. enumerable: true,
  14951. configurable: true
  14952. });
  14953. InstancedMesh.prototype.getTotalVertices = function () {
  14954. return this._sourceMesh.getTotalVertices();
  14955. };
  14956. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14957. get: function () {
  14958. return this._sourceMesh;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14964. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14965. };
  14966. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14967. return this._sourceMesh.isVerticesDataPresent(kind);
  14968. };
  14969. InstancedMesh.prototype.getIndices = function () {
  14970. return this._sourceMesh.getIndices();
  14971. };
  14972. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14973. get: function () {
  14974. return this._sourceMesh._positions;
  14975. },
  14976. enumerable: true,
  14977. configurable: true
  14978. });
  14979. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14980. var meshBB = this._sourceMesh.getBoundingInfo();
  14981. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14982. this._updateBoundingInfo();
  14983. };
  14984. InstancedMesh.prototype._preActivate = function () {
  14985. if (this._currentLOD) {
  14986. this._currentLOD._preActivate();
  14987. }
  14988. };
  14989. InstancedMesh.prototype._activate = function (renderId) {
  14990. if (this._currentLOD) {
  14991. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14992. }
  14993. };
  14994. InstancedMesh.prototype.getLOD = function (camera) {
  14995. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14996. if (this._currentLOD === this.sourceMesh) {
  14997. return this;
  14998. }
  14999. return this._currentLOD;
  15000. };
  15001. InstancedMesh.prototype._syncSubMeshes = function () {
  15002. this.releaseSubMeshes();
  15003. if (this._sourceMesh.subMeshes) {
  15004. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15005. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15006. }
  15007. }
  15008. };
  15009. InstancedMesh.prototype._generatePointsArray = function () {
  15010. return this._sourceMesh._generatePointsArray();
  15011. };
  15012. // Clone
  15013. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15014. var result = this._sourceMesh.createInstance(name);
  15015. // Deep copy
  15016. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15017. // Bounding info
  15018. this.refreshBoundingInfo();
  15019. // Parent
  15020. if (newParent) {
  15021. result.parent = newParent;
  15022. }
  15023. if (!doNotCloneChildren) {
  15024. // Children
  15025. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15026. var mesh = this.getScene().meshes[index];
  15027. if (mesh.parent === this) {
  15028. mesh.clone(mesh.name, result);
  15029. }
  15030. }
  15031. }
  15032. result.computeWorldMatrix(true);
  15033. return result;
  15034. };
  15035. // Dispoe
  15036. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15037. // Remove from mesh
  15038. var index = this._sourceMesh.instances.indexOf(this);
  15039. this._sourceMesh.instances.splice(index, 1);
  15040. _super.prototype.dispose.call(this, doNotRecurse);
  15041. };
  15042. return InstancedMesh;
  15043. })(BABYLON.AbstractMesh);
  15044. BABYLON.InstancedMesh = InstancedMesh;
  15045. })(BABYLON || (BABYLON = {}));
  15046. var BABYLON;
  15047. (function (BABYLON) {
  15048. var _InstancesBatch = (function () {
  15049. function _InstancesBatch() {
  15050. this.mustReturn = false;
  15051. this.visibleInstances = new Array();
  15052. this.renderSelf = new Array();
  15053. }
  15054. return _InstancesBatch;
  15055. })();
  15056. BABYLON._InstancesBatch = _InstancesBatch;
  15057. var Mesh = (function (_super) {
  15058. __extends(Mesh, _super);
  15059. /**
  15060. * @constructor
  15061. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15062. * @param {Scene} scene - The scene to add this mesh to.
  15063. * @param {Node} parent - The parent of this mesh, if it has one
  15064. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15065. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15066. * When false, achieved by calling a clone(), also passing False.
  15067. * This will make creation of children, recursive.
  15068. */
  15069. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15070. if (parent === void 0) { parent = null; }
  15071. _super.call(this, name, scene);
  15072. // Members
  15073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15074. this.instances = new Array();
  15075. this._LODLevels = new Array();
  15076. this._onBeforeRenderCallbacks = new Array();
  15077. this._onAfterRenderCallbacks = new Array();
  15078. this._visibleInstances = {};
  15079. this._renderIdForInstances = new Array();
  15080. this._batchCache = new _InstancesBatch();
  15081. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15082. this._sideOrientation = Mesh._DEFAULTSIDE;
  15083. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15084. if (source) {
  15085. // Geometry
  15086. if (source._geometry) {
  15087. source._geometry.applyToMesh(this);
  15088. }
  15089. // Deep copy
  15090. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  15091. // Pivot
  15092. this.setPivotMatrix(source.getPivotMatrix());
  15093. this.id = name + "." + source.id;
  15094. // Material
  15095. this.material = source.material;
  15096. var index;
  15097. if (!doNotCloneChildren) {
  15098. // Children
  15099. for (index = 0; index < scene.meshes.length; index++) {
  15100. var mesh = scene.meshes[index];
  15101. if (mesh.parent === source) {
  15102. // doNotCloneChildren is always going to be False
  15103. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15104. }
  15105. }
  15106. }
  15107. // Particles
  15108. for (index = 0; index < scene.particleSystems.length; index++) {
  15109. var system = scene.particleSystems[index];
  15110. if (system.emitter === source) {
  15111. system.clone(system.name, this);
  15112. }
  15113. }
  15114. this.computeWorldMatrix(true);
  15115. }
  15116. // Parent
  15117. if (parent !== null) {
  15118. this.parent = parent;
  15119. }
  15120. }
  15121. Object.defineProperty(Mesh, "FRONTSIDE", {
  15122. get: function () {
  15123. return Mesh._FRONTSIDE;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. Object.defineProperty(Mesh, "BACKSIDE", {
  15129. get: function () {
  15130. return Mesh._BACKSIDE;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15136. get: function () {
  15137. return Mesh._DOUBLESIDE;
  15138. },
  15139. enumerable: true,
  15140. configurable: true
  15141. });
  15142. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15143. get: function () {
  15144. return Mesh._DEFAULTSIDE;
  15145. },
  15146. enumerable: true,
  15147. configurable: true
  15148. });
  15149. Object.defineProperty(Mesh, "NO_CAP", {
  15150. get: function () {
  15151. return Mesh._NO_CAP;
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. Object.defineProperty(Mesh, "CAP_START", {
  15157. get: function () {
  15158. return Mesh._CAP_START;
  15159. },
  15160. enumerable: true,
  15161. configurable: true
  15162. });
  15163. Object.defineProperty(Mesh, "CAP_END", {
  15164. get: function () {
  15165. return Mesh._CAP_END;
  15166. },
  15167. enumerable: true,
  15168. configurable: true
  15169. });
  15170. Object.defineProperty(Mesh, "CAP_ALL", {
  15171. get: function () {
  15172. return Mesh._CAP_ALL;
  15173. },
  15174. enumerable: true,
  15175. configurable: true
  15176. });
  15177. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15178. // Methods
  15179. get: function () {
  15180. return this._LODLevels.length > 0;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Mesh.prototype._sortLODLevels = function () {
  15186. this._LODLevels.sort(function (a, b) {
  15187. if (a.distance < b.distance) {
  15188. return 1;
  15189. }
  15190. if (a.distance > b.distance) {
  15191. return -1;
  15192. }
  15193. return 0;
  15194. });
  15195. };
  15196. /**
  15197. * Add a mesh as LOD level triggered at the given distance.
  15198. * @param {number} distance - the distance from the center of the object to show this level
  15199. * @param {Mesh} mesh - the mesh to be added as LOD level
  15200. * @return {Mesh} this mesh (for chaining)
  15201. */
  15202. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15203. if (mesh && mesh._masterMesh) {
  15204. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15205. return this;
  15206. }
  15207. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15208. this._LODLevels.push(level);
  15209. if (mesh) {
  15210. mesh._masterMesh = this;
  15211. }
  15212. this._sortLODLevels();
  15213. return this;
  15214. };
  15215. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15216. for (var index = 0; index < this._LODLevels.length; index++) {
  15217. var level = this._LODLevels[index];
  15218. if (level.distance === distance) {
  15219. return level.mesh;
  15220. }
  15221. }
  15222. return null;
  15223. };
  15224. /**
  15225. * Remove a mesh from the LOD array
  15226. * @param {Mesh} mesh - the mesh to be removed.
  15227. * @return {Mesh} this mesh (for chaining)
  15228. */
  15229. Mesh.prototype.removeLODLevel = function (mesh) {
  15230. for (var index = 0; index < this._LODLevels.length; index++) {
  15231. if (this._LODLevels[index].mesh === mesh) {
  15232. this._LODLevels.splice(index, 1);
  15233. if (mesh) {
  15234. mesh._masterMesh = null;
  15235. }
  15236. }
  15237. }
  15238. this._sortLODLevels();
  15239. return this;
  15240. };
  15241. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15242. if (!this._LODLevels || this._LODLevels.length === 0) {
  15243. return this;
  15244. }
  15245. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15246. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15247. if (this.onLODLevelSelection) {
  15248. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15249. }
  15250. return this;
  15251. }
  15252. for (var index = 0; index < this._LODLevels.length; index++) {
  15253. var level = this._LODLevels[index];
  15254. if (level.distance < distanceToCamera) {
  15255. if (level.mesh) {
  15256. level.mesh._preActivate();
  15257. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15258. }
  15259. if (this.onLODLevelSelection) {
  15260. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15261. }
  15262. return level.mesh;
  15263. }
  15264. }
  15265. if (this.onLODLevelSelection) {
  15266. this.onLODLevelSelection(distanceToCamera, this, this);
  15267. }
  15268. return this;
  15269. };
  15270. Object.defineProperty(Mesh.prototype, "geometry", {
  15271. get: function () {
  15272. return this._geometry;
  15273. },
  15274. enumerable: true,
  15275. configurable: true
  15276. });
  15277. Mesh.prototype.getTotalVertices = function () {
  15278. if (!this._geometry) {
  15279. return 0;
  15280. }
  15281. return this._geometry.getTotalVertices();
  15282. };
  15283. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15284. if (!this._geometry) {
  15285. return null;
  15286. }
  15287. return this._geometry.getVerticesData(kind, copyWhenShared);
  15288. };
  15289. Mesh.prototype.getVertexBuffer = function (kind) {
  15290. if (!this._geometry) {
  15291. return undefined;
  15292. }
  15293. return this._geometry.getVertexBuffer(kind);
  15294. };
  15295. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15296. if (!this._geometry) {
  15297. if (this._delayInfo) {
  15298. return this._delayInfo.indexOf(kind) !== -1;
  15299. }
  15300. return false;
  15301. }
  15302. return this._geometry.isVerticesDataPresent(kind);
  15303. };
  15304. Mesh.prototype.getVerticesDataKinds = function () {
  15305. if (!this._geometry) {
  15306. var result = [];
  15307. if (this._delayInfo) {
  15308. for (var kind in this._delayInfo) {
  15309. result.push(kind);
  15310. }
  15311. }
  15312. return result;
  15313. }
  15314. return this._geometry.getVerticesDataKinds();
  15315. };
  15316. Mesh.prototype.getTotalIndices = function () {
  15317. if (!this._geometry) {
  15318. return 0;
  15319. }
  15320. return this._geometry.getTotalIndices();
  15321. };
  15322. Mesh.prototype.getIndices = function (copyWhenShared) {
  15323. if (!this._geometry) {
  15324. return [];
  15325. }
  15326. return this._geometry.getIndices(copyWhenShared);
  15327. };
  15328. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15329. get: function () {
  15330. return this._masterMesh !== null && this._masterMesh !== undefined;
  15331. },
  15332. enumerable: true,
  15333. configurable: true
  15334. });
  15335. Mesh.prototype.isReady = function () {
  15336. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15337. return false;
  15338. }
  15339. return _super.prototype.isReady.call(this);
  15340. };
  15341. Mesh.prototype.isDisposed = function () {
  15342. return this._isDisposed;
  15343. };
  15344. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15345. get: function () {
  15346. return this._sideOrientation;
  15347. },
  15348. set: function (sideO) {
  15349. this._sideOrientation = sideO;
  15350. },
  15351. enumerable: true,
  15352. configurable: true
  15353. });
  15354. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15355. get: function () {
  15356. return this._areNormalsFrozen;
  15357. },
  15358. enumerable: true,
  15359. configurable: true
  15360. });
  15361. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15362. Mesh.prototype.freezeNormals = function () {
  15363. this._areNormalsFrozen = true;
  15364. };
  15365. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15366. Mesh.prototype.unfreezeNormals = function () {
  15367. this._areNormalsFrozen = false;
  15368. };
  15369. // Methods
  15370. Mesh.prototype._preActivate = function () {
  15371. var sceneRenderId = this.getScene().getRenderId();
  15372. if (this._preActivateId === sceneRenderId) {
  15373. return;
  15374. }
  15375. this._preActivateId = sceneRenderId;
  15376. this._visibleInstances = null;
  15377. };
  15378. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15379. if (!this._visibleInstances) {
  15380. this._visibleInstances = {};
  15381. this._visibleInstances.defaultRenderId = renderId;
  15382. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15383. }
  15384. if (!this._visibleInstances[renderId]) {
  15385. this._visibleInstances[renderId] = new Array();
  15386. }
  15387. this._visibleInstances[renderId].push(instance);
  15388. };
  15389. Mesh.prototype.refreshBoundingInfo = function () {
  15390. if (this._boundingInfo.isLocked) {
  15391. return;
  15392. }
  15393. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15394. if (data) {
  15395. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15396. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15397. }
  15398. if (this.subMeshes) {
  15399. for (var index = 0; index < this.subMeshes.length; index++) {
  15400. this.subMeshes[index].refreshBoundingInfo();
  15401. }
  15402. }
  15403. this._updateBoundingInfo();
  15404. };
  15405. Mesh.prototype._createGlobalSubMesh = function () {
  15406. var totalVertices = this.getTotalVertices();
  15407. if (!totalVertices || !this.getIndices()) {
  15408. return null;
  15409. }
  15410. this.releaseSubMeshes();
  15411. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15412. };
  15413. Mesh.prototype.subdivide = function (count) {
  15414. if (count < 1) {
  15415. return;
  15416. }
  15417. var totalIndices = this.getTotalIndices();
  15418. var subdivisionSize = (totalIndices / count) | 0;
  15419. var offset = 0;
  15420. // Ensure that subdivisionSize is a multiple of 3
  15421. while (subdivisionSize % 3 !== 0) {
  15422. subdivisionSize++;
  15423. }
  15424. this.releaseSubMeshes();
  15425. for (var index = 0; index < count; index++) {
  15426. if (offset >= totalIndices) {
  15427. break;
  15428. }
  15429. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15430. offset += subdivisionSize;
  15431. }
  15432. this.synchronizeInstances();
  15433. };
  15434. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15435. if (!this._geometry) {
  15436. var vertexData = new BABYLON.VertexData();
  15437. vertexData.set(data, kind);
  15438. var scene = this.getScene();
  15439. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15440. }
  15441. else {
  15442. this._geometry.setVerticesData(kind, data, updatable, stride);
  15443. }
  15444. };
  15445. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15446. if (!this._geometry) {
  15447. return;
  15448. }
  15449. if (!makeItUnique) {
  15450. this._geometry.updateVerticesData(kind, data, updateExtends);
  15451. }
  15452. else {
  15453. this.makeGeometryUnique();
  15454. this.updateVerticesData(kind, data, updateExtends, false);
  15455. }
  15456. };
  15457. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15458. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15459. if (!this._geometry) {
  15460. return;
  15461. }
  15462. if (!makeItUnique) {
  15463. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15464. }
  15465. else {
  15466. this.makeGeometryUnique();
  15467. this.updateVerticesDataDirectly(kind, data, offset, false);
  15468. }
  15469. };
  15470. // Mesh positions update function :
  15471. // updates the mesh positions according to the positionFunction returned values.
  15472. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15473. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15474. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15475. if (computeNormals === void 0) { computeNormals = true; }
  15476. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15477. positionFunction(positions);
  15478. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15479. if (computeNormals) {
  15480. var indices = this.getIndices();
  15481. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15482. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15483. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15484. }
  15485. };
  15486. Mesh.prototype.makeGeometryUnique = function () {
  15487. if (!this._geometry) {
  15488. return;
  15489. }
  15490. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15491. geometry.applyToMesh(this);
  15492. };
  15493. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15494. if (!this._geometry) {
  15495. var vertexData = new BABYLON.VertexData();
  15496. vertexData.indices = indices;
  15497. var scene = this.getScene();
  15498. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15499. }
  15500. else {
  15501. this._geometry.setIndices(indices, totalVertices);
  15502. }
  15503. };
  15504. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15505. var engine = this.getScene().getEngine();
  15506. // Wireframe
  15507. var indexToBind;
  15508. if (this._unIndexed) {
  15509. indexToBind = null;
  15510. }
  15511. else {
  15512. switch (fillMode) {
  15513. case BABYLON.Material.PointFillMode:
  15514. indexToBind = null;
  15515. break;
  15516. case BABYLON.Material.WireFrameFillMode:
  15517. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15518. break;
  15519. default:
  15520. case BABYLON.Material.TriangleFillMode:
  15521. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15522. break;
  15523. }
  15524. }
  15525. // VBOs
  15526. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15527. };
  15528. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15529. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15530. return;
  15531. }
  15532. if (this.onBeforeDraw) {
  15533. this.onBeforeDraw();
  15534. }
  15535. var engine = this.getScene().getEngine();
  15536. // Draw order
  15537. switch (fillMode) {
  15538. case BABYLON.Material.PointFillMode:
  15539. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15540. break;
  15541. case BABYLON.Material.WireFrameFillMode:
  15542. if (this._unIndexed) {
  15543. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15544. }
  15545. else {
  15546. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15547. }
  15548. break;
  15549. default:
  15550. if (this._unIndexed) {
  15551. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15552. }
  15553. else {
  15554. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15555. }
  15556. }
  15557. };
  15558. Mesh.prototype.registerBeforeRender = function (func) {
  15559. this._onBeforeRenderCallbacks.push(func);
  15560. };
  15561. Mesh.prototype.unregisterBeforeRender = function (func) {
  15562. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15563. if (index > -1) {
  15564. this._onBeforeRenderCallbacks.splice(index, 1);
  15565. }
  15566. };
  15567. Mesh.prototype.registerAfterRender = function (func) {
  15568. this._onAfterRenderCallbacks.push(func);
  15569. };
  15570. Mesh.prototype.unregisterAfterRender = function (func) {
  15571. var index = this._onAfterRenderCallbacks.indexOf(func);
  15572. if (index > -1) {
  15573. this._onAfterRenderCallbacks.splice(index, 1);
  15574. }
  15575. };
  15576. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15577. var scene = this.getScene();
  15578. this._batchCache.mustReturn = false;
  15579. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15580. this._batchCache.visibleInstances[subMeshId] = null;
  15581. if (this._visibleInstances) {
  15582. var currentRenderId = scene.getRenderId();
  15583. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15584. var selfRenderId = this._renderId;
  15585. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15586. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15587. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15588. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15589. }
  15590. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15591. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15592. this._batchCache.mustReturn = true;
  15593. return this._batchCache;
  15594. }
  15595. if (currentRenderId !== selfRenderId) {
  15596. this._batchCache.renderSelf[subMeshId] = false;
  15597. }
  15598. }
  15599. this._renderIdForInstances[subMeshId] = currentRenderId;
  15600. }
  15601. return this._batchCache;
  15602. };
  15603. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15604. var visibleInstances = batch.visibleInstances[subMesh._id];
  15605. var matricesCount = visibleInstances.length + 1;
  15606. var bufferSize = matricesCount * 16 * 4;
  15607. while (this._instancesBufferSize < bufferSize) {
  15608. this._instancesBufferSize *= 2;
  15609. }
  15610. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15611. if (this._worldMatricesInstancesBuffer) {
  15612. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15613. }
  15614. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15615. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15616. }
  15617. var offset = 0;
  15618. var instancesCount = 0;
  15619. var world = this.getWorldMatrix();
  15620. if (batch.renderSelf[subMesh._id]) {
  15621. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15622. offset += 16;
  15623. instancesCount++;
  15624. }
  15625. if (visibleInstances) {
  15626. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15627. var instance = visibleInstances[instanceIndex];
  15628. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15629. offset += 16;
  15630. instancesCount++;
  15631. }
  15632. }
  15633. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15634. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15635. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15636. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15637. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15638. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15639. this._draw(subMesh, fillMode, instancesCount);
  15640. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15641. };
  15642. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15643. var scene = this.getScene();
  15644. var engine = scene.getEngine();
  15645. if (hardwareInstancedRendering) {
  15646. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15647. }
  15648. else {
  15649. if (batch.renderSelf[subMesh._id]) {
  15650. // Draw
  15651. if (onBeforeDraw) {
  15652. onBeforeDraw(false, this.getWorldMatrix());
  15653. }
  15654. this._draw(subMesh, fillMode);
  15655. }
  15656. if (batch.visibleInstances[subMesh._id]) {
  15657. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15658. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15659. // World
  15660. var world = instance.getWorldMatrix();
  15661. if (onBeforeDraw) {
  15662. onBeforeDraw(true, world);
  15663. }
  15664. // Draw
  15665. this._draw(subMesh, fillMode);
  15666. }
  15667. }
  15668. }
  15669. };
  15670. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15671. var scene = this.getScene();
  15672. // Managing instances
  15673. var batch = this._getInstancesRenderList(subMesh._id);
  15674. if (batch.mustReturn) {
  15675. return;
  15676. }
  15677. // Checking geometry state
  15678. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15679. return;
  15680. }
  15681. var callbackIndex;
  15682. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15683. this._onBeforeRenderCallbacks[callbackIndex](this);
  15684. }
  15685. var engine = scene.getEngine();
  15686. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15687. // Material
  15688. var effectiveMaterial = subMesh.getMaterial();
  15689. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15690. return;
  15691. }
  15692. // Outline - step 1
  15693. var savedDepthWrite = engine.getDepthWrite();
  15694. if (this.renderOutline) {
  15695. engine.setDepthWrite(false);
  15696. scene.getOutlineRenderer().render(subMesh, batch);
  15697. engine.setDepthWrite(savedDepthWrite);
  15698. }
  15699. effectiveMaterial._preBind();
  15700. var effect = effectiveMaterial.getEffect();
  15701. // Bind
  15702. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15703. this._bind(subMesh, effect, fillMode);
  15704. var world = this.getWorldMatrix();
  15705. effectiveMaterial.bind(world, this);
  15706. // Alpha mode
  15707. if (enableAlphaMode) {
  15708. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15709. }
  15710. // Draw
  15711. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15712. if (isInstance) {
  15713. effectiveMaterial.bindOnlyWorldMatrix(world);
  15714. }
  15715. });
  15716. // Unbind
  15717. effectiveMaterial.unbind();
  15718. // Outline - step 2
  15719. if (this.renderOutline && savedDepthWrite) {
  15720. engine.setDepthWrite(true);
  15721. engine.setColorWrite(false);
  15722. scene.getOutlineRenderer().render(subMesh, batch);
  15723. engine.setColorWrite(true);
  15724. }
  15725. // Overlay
  15726. if (this.renderOverlay) {
  15727. var currentMode = engine.getAlphaMode();
  15728. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15729. scene.getOutlineRenderer().render(subMesh, batch, true);
  15730. engine.setAlphaMode(currentMode);
  15731. }
  15732. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15733. this._onAfterRenderCallbacks[callbackIndex](this);
  15734. }
  15735. };
  15736. Mesh.prototype.getEmittedParticleSystems = function () {
  15737. var results = new Array();
  15738. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15739. var particleSystem = this.getScene().particleSystems[index];
  15740. if (particleSystem.emitter === this) {
  15741. results.push(particleSystem);
  15742. }
  15743. }
  15744. return results;
  15745. };
  15746. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15747. var results = new Array();
  15748. var descendants = this.getDescendants();
  15749. descendants.push(this);
  15750. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15751. var particleSystem = this.getScene().particleSystems[index];
  15752. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15753. results.push(particleSystem);
  15754. }
  15755. }
  15756. return results;
  15757. };
  15758. Mesh.prototype._checkDelayState = function () {
  15759. var _this = this;
  15760. var that = this;
  15761. var scene = this.getScene();
  15762. if (this._geometry) {
  15763. this._geometry.load(scene);
  15764. }
  15765. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15766. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15767. scene._addPendingData(that);
  15768. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15769. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15770. if (data instanceof ArrayBuffer) {
  15771. _this._delayLoadingFunction(data, _this);
  15772. }
  15773. else {
  15774. _this._delayLoadingFunction(JSON.parse(data), _this);
  15775. }
  15776. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15777. scene._removePendingData(_this);
  15778. }, function () { }, scene.database, getBinaryData);
  15779. }
  15780. };
  15781. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15782. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15783. return false;
  15784. }
  15785. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15786. return false;
  15787. }
  15788. this._checkDelayState();
  15789. return true;
  15790. };
  15791. Mesh.prototype.setMaterialByID = function (id) {
  15792. var materials = this.getScene().materials;
  15793. var index;
  15794. for (index = 0; index < materials.length; index++) {
  15795. if (materials[index].id === id) {
  15796. this.material = materials[index];
  15797. return;
  15798. }
  15799. }
  15800. // Multi
  15801. var multiMaterials = this.getScene().multiMaterials;
  15802. for (index = 0; index < multiMaterials.length; index++) {
  15803. if (multiMaterials[index].id === id) {
  15804. this.material = multiMaterials[index];
  15805. return;
  15806. }
  15807. }
  15808. };
  15809. Mesh.prototype.getAnimatables = function () {
  15810. var results = [];
  15811. if (this.material) {
  15812. results.push(this.material);
  15813. }
  15814. if (this.skeleton) {
  15815. results.push(this.skeleton);
  15816. }
  15817. return results;
  15818. };
  15819. // Geometry
  15820. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15821. // Position
  15822. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15823. return;
  15824. }
  15825. this._resetPointsArrayCache();
  15826. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15827. var temp = [];
  15828. var index;
  15829. for (index = 0; index < data.length; index += 3) {
  15830. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15831. }
  15832. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15833. // Normals
  15834. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15835. return;
  15836. }
  15837. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15838. temp = [];
  15839. for (index = 0; index < data.length; index += 3) {
  15840. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15841. }
  15842. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15843. // flip faces?
  15844. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15845. this.flipFaces();
  15846. }
  15847. };
  15848. // Will apply current transform to mesh and reset world matrix
  15849. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15850. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15851. this.scaling.copyFromFloats(1, 1, 1);
  15852. this.position.copyFromFloats(0, 0, 0);
  15853. this.rotation.copyFromFloats(0, 0, 0);
  15854. //only if quaternion is already set
  15855. if (this.rotationQuaternion) {
  15856. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15857. }
  15858. this._worldMatrix = BABYLON.Matrix.Identity();
  15859. };
  15860. // Cache
  15861. Mesh.prototype._resetPointsArrayCache = function () {
  15862. this._positions = null;
  15863. };
  15864. Mesh.prototype._generatePointsArray = function () {
  15865. if (this._positions)
  15866. return true;
  15867. this._positions = [];
  15868. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15869. if (!data) {
  15870. return false;
  15871. }
  15872. for (var index = 0; index < data.length; index += 3) {
  15873. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15874. }
  15875. return true;
  15876. };
  15877. // Clone
  15878. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15879. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15880. };
  15881. // Dispose
  15882. Mesh.prototype.dispose = function (doNotRecurse) {
  15883. if (this._geometry) {
  15884. this._geometry.releaseForMesh(this, true);
  15885. }
  15886. // Instances
  15887. if (this._worldMatricesInstancesBuffer) {
  15888. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15889. this._worldMatricesInstancesBuffer = null;
  15890. }
  15891. while (this.instances.length) {
  15892. this.instances[0].dispose();
  15893. }
  15894. _super.prototype.dispose.call(this, doNotRecurse);
  15895. };
  15896. // Geometric tools
  15897. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15898. var _this = this;
  15899. var scene = this.getScene();
  15900. var onload = function (img) {
  15901. // Getting height map data
  15902. var canvas = document.createElement("canvas");
  15903. var context = canvas.getContext("2d");
  15904. var heightMapWidth = img.width;
  15905. var heightMapHeight = img.height;
  15906. canvas.width = heightMapWidth;
  15907. canvas.height = heightMapHeight;
  15908. context.drawImage(img, 0, 0);
  15909. // Create VertexData from map data
  15910. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15911. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15912. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15913. //execute success callback, if set
  15914. if (onSuccess) {
  15915. onSuccess(_this);
  15916. }
  15917. };
  15918. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15919. };
  15920. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15921. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15922. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15923. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15924. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15925. return;
  15926. }
  15927. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15928. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15929. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15930. var position = BABYLON.Vector3.Zero();
  15931. var normal = BABYLON.Vector3.Zero();
  15932. var uv = BABYLON.Vector2.Zero();
  15933. for (var index = 0; index < positions.length; index += 3) {
  15934. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15935. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15936. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15937. // Compute height
  15938. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15939. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15940. var pos = (u + v * heightMapWidth) * 4;
  15941. var r = buffer[pos] / 255.0;
  15942. var g = buffer[pos + 1] / 255.0;
  15943. var b = buffer[pos + 2] / 255.0;
  15944. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15945. normal.normalize();
  15946. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15947. position = position.add(normal);
  15948. position.toArray(positions, index);
  15949. }
  15950. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15951. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15952. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15953. };
  15954. Mesh.prototype.convertToFlatShadedMesh = function () {
  15955. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15956. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15957. var kinds = this.getVerticesDataKinds();
  15958. var vbs = [];
  15959. var data = [];
  15960. var newdata = [];
  15961. var updatableNormals = false;
  15962. var kindIndex;
  15963. var kind;
  15964. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15965. kind = kinds[kindIndex];
  15966. var vertexBuffer = this.getVertexBuffer(kind);
  15967. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15968. updatableNormals = vertexBuffer.isUpdatable();
  15969. kinds.splice(kindIndex, 1);
  15970. kindIndex--;
  15971. continue;
  15972. }
  15973. vbs[kind] = vertexBuffer;
  15974. data[kind] = vbs[kind].getData();
  15975. newdata[kind] = [];
  15976. }
  15977. // Save previous submeshes
  15978. var previousSubmeshes = this.subMeshes.slice(0);
  15979. var indices = this.getIndices();
  15980. var totalIndices = this.getTotalIndices();
  15981. // Generating unique vertices per face
  15982. var index;
  15983. for (index = 0; index < totalIndices; index++) {
  15984. var vertexIndex = indices[index];
  15985. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15986. kind = kinds[kindIndex];
  15987. var stride = vbs[kind].getStrideSize();
  15988. for (var offset = 0; offset < stride; offset++) {
  15989. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15990. }
  15991. }
  15992. }
  15993. // Updating faces & normal
  15994. var normals = [];
  15995. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15996. for (index = 0; index < totalIndices; index += 3) {
  15997. indices[index] = index;
  15998. indices[index + 1] = index + 1;
  15999. indices[index + 2] = index + 2;
  16000. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16001. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16002. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16003. var p1p2 = p1.subtract(p2);
  16004. var p3p2 = p3.subtract(p2);
  16005. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16006. // Store same normals for every vertex
  16007. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16008. normals.push(normal.x);
  16009. normals.push(normal.y);
  16010. normals.push(normal.z);
  16011. }
  16012. }
  16013. this.setIndices(indices);
  16014. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16015. // Updating vertex buffers
  16016. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16017. kind = kinds[kindIndex];
  16018. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16019. }
  16020. // Updating submeshes
  16021. this.releaseSubMeshes();
  16022. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16023. var previousOne = previousSubmeshes[submeshIndex];
  16024. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16025. }
  16026. this.synchronizeInstances();
  16027. };
  16028. Mesh.prototype.convertToUnIndexedMesh = function () {
  16029. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16030. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16031. var kinds = this.getVerticesDataKinds();
  16032. var vbs = [];
  16033. var data = [];
  16034. var newdata = [];
  16035. var updatableNormals = false;
  16036. var kindIndex;
  16037. var kind;
  16038. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16039. kind = kinds[kindIndex];
  16040. var vertexBuffer = this.getVertexBuffer(kind);
  16041. vbs[kind] = vertexBuffer;
  16042. data[kind] = vbs[kind].getData();
  16043. newdata[kind] = [];
  16044. }
  16045. // Save previous submeshes
  16046. var previousSubmeshes = this.subMeshes.slice(0);
  16047. var indices = this.getIndices();
  16048. var totalIndices = this.getTotalIndices();
  16049. // Generating unique vertices per face
  16050. var index;
  16051. for (index = 0; index < totalIndices; index++) {
  16052. var vertexIndex = indices[index];
  16053. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16054. kind = kinds[kindIndex];
  16055. var stride = vbs[kind].getStrideSize();
  16056. for (var offset = 0; offset < stride; offset++) {
  16057. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16058. }
  16059. }
  16060. }
  16061. // Updating indices
  16062. for (index = 0; index < totalIndices; index += 3) {
  16063. indices[index] = index;
  16064. indices[index + 1] = index + 1;
  16065. indices[index + 2] = index + 2;
  16066. }
  16067. this.setIndices(indices);
  16068. // Updating vertex buffers
  16069. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16070. kind = kinds[kindIndex];
  16071. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16072. }
  16073. // Updating submeshes
  16074. this.releaseSubMeshes();
  16075. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16076. var previousOne = previousSubmeshes[submeshIndex];
  16077. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16078. }
  16079. this._unIndexed = true;
  16080. this.synchronizeInstances();
  16081. };
  16082. // will inverse faces orientations, and invert normals too if specified
  16083. Mesh.prototype.flipFaces = function (flipNormals) {
  16084. if (flipNormals === void 0) { flipNormals = false; }
  16085. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16086. var i;
  16087. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16088. for (i = 0; i < vertex_data.normals.length; i++) {
  16089. vertex_data.normals[i] *= -1;
  16090. }
  16091. }
  16092. var temp;
  16093. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16094. // reassign indices
  16095. temp = vertex_data.indices[i + 1];
  16096. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16097. vertex_data.indices[i + 2] = temp;
  16098. }
  16099. vertex_data.applyToMesh(this);
  16100. };
  16101. // Instances
  16102. Mesh.prototype.createInstance = function (name) {
  16103. return new BABYLON.InstancedMesh(name, this);
  16104. };
  16105. Mesh.prototype.synchronizeInstances = function () {
  16106. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16107. var instance = this.instances[instanceIndex];
  16108. instance._syncSubMeshes();
  16109. }
  16110. };
  16111. /**
  16112. * Simplify the mesh according to the given array of settings.
  16113. * Function will return immediately and will simplify async.
  16114. * @param settings a collection of simplification settings.
  16115. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16116. * @param type the type of simplification to run.
  16117. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16118. */
  16119. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16120. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16121. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16122. this.getScene().simplificationQueue.addTask({
  16123. settings: settings,
  16124. parallelProcessing: parallelProcessing,
  16125. mesh: this,
  16126. simplificationType: simplificationType,
  16127. successCallback: successCallback
  16128. });
  16129. };
  16130. /**
  16131. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16132. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16133. * This should be used together with the simplification to avoid disappearing triangles.
  16134. * @param successCallback an optional success callback to be called after the optimization finished.
  16135. */
  16136. Mesh.prototype.optimizeIndices = function (successCallback) {
  16137. var _this = this;
  16138. var indices = this.getIndices();
  16139. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16140. var vectorPositions = [];
  16141. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16142. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16143. }
  16144. var dupes = [];
  16145. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16146. var realPos = vectorPositions.length - 1 - iteration;
  16147. var testedPosition = vectorPositions[realPos];
  16148. for (var j = 0; j < realPos; ++j) {
  16149. var againstPosition = vectorPositions[j];
  16150. if (testedPosition.equals(againstPosition)) {
  16151. dupes[realPos] = j;
  16152. break;
  16153. }
  16154. }
  16155. }, function () {
  16156. for (var i = 0; i < indices.length; ++i) {
  16157. indices[i] = dupes[indices[i]] || indices[i];
  16158. }
  16159. //indices are now reordered
  16160. var originalSubMeshes = _this.subMeshes.slice(0);
  16161. _this.setIndices(indices);
  16162. _this.subMeshes = originalSubMeshes;
  16163. if (successCallback) {
  16164. successCallback(_this);
  16165. }
  16166. });
  16167. };
  16168. // Statics
  16169. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16170. var mesh = new Mesh(parsedMesh.name, scene);
  16171. mesh.id = parsedMesh.id;
  16172. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16173. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16174. if (parsedMesh.rotationQuaternion) {
  16175. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16176. }
  16177. else if (parsedMesh.rotation) {
  16178. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16179. }
  16180. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16181. if (parsedMesh.localMatrix) {
  16182. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16183. }
  16184. else if (parsedMesh.pivotMatrix) {
  16185. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16186. }
  16187. mesh.setEnabled(parsedMesh.isEnabled);
  16188. mesh.isVisible = parsedMesh.isVisible;
  16189. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16190. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16191. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16192. if (parsedMesh.applyFog !== undefined) {
  16193. mesh.applyFog = parsedMesh.applyFog;
  16194. }
  16195. if (parsedMesh.pickable !== undefined) {
  16196. mesh.isPickable = parsedMesh.pickable;
  16197. }
  16198. if (parsedMesh.alphaIndex !== undefined) {
  16199. mesh.alphaIndex = parsedMesh.alphaIndex;
  16200. }
  16201. mesh.receiveShadows = parsedMesh.receiveShadows;
  16202. mesh.billboardMode = parsedMesh.billboardMode;
  16203. if (parsedMesh.visibility !== undefined) {
  16204. mesh.visibility = parsedMesh.visibility;
  16205. }
  16206. mesh.checkCollisions = parsedMesh.checkCollisions;
  16207. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16208. // freezeWorldMatrix
  16209. if (parsedMesh.freezeWorldMatrix) {
  16210. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16211. }
  16212. // Parent
  16213. if (parsedMesh.parentId) {
  16214. mesh._waitingParentId = parsedMesh.parentId;
  16215. }
  16216. // Actions
  16217. if (parsedMesh.actions !== undefined) {
  16218. mesh._waitingActions = parsedMesh.actions;
  16219. }
  16220. // Geometry
  16221. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16222. if (parsedMesh.delayLoadingFile) {
  16223. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16224. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16225. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16226. if (parsedMesh._binaryInfo) {
  16227. mesh._binaryInfo = parsedMesh._binaryInfo;
  16228. }
  16229. mesh._delayInfo = [];
  16230. if (parsedMesh.hasUVs) {
  16231. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16232. }
  16233. if (parsedMesh.hasUVs2) {
  16234. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16235. }
  16236. if (parsedMesh.hasUVs3) {
  16237. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16238. }
  16239. if (parsedMesh.hasUVs4) {
  16240. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16241. }
  16242. if (parsedMesh.hasUVs5) {
  16243. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16244. }
  16245. if (parsedMesh.hasUVs6) {
  16246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16247. }
  16248. if (parsedMesh.hasColors) {
  16249. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16250. }
  16251. if (parsedMesh.hasMatricesIndices) {
  16252. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16253. }
  16254. if (parsedMesh.hasMatricesWeights) {
  16255. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16256. }
  16257. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16258. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16259. mesh._checkDelayState();
  16260. }
  16261. }
  16262. else {
  16263. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16264. }
  16265. // Material
  16266. if (parsedMesh.materialId) {
  16267. mesh.setMaterialByID(parsedMesh.materialId);
  16268. }
  16269. else {
  16270. mesh.material = null;
  16271. }
  16272. // Skeleton
  16273. if (parsedMesh.skeletonId > -1) {
  16274. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16275. if (parsedMesh.numBoneInfluencers) {
  16276. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16277. }
  16278. }
  16279. // Animations
  16280. if (parsedMesh.animations) {
  16281. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16282. var parsedAnimation = parsedMesh.animations[animationIndex];
  16283. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16284. }
  16285. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16286. }
  16287. if (parsedMesh.autoAnimate) {
  16288. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16289. }
  16290. // Layer Mask
  16291. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16292. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16293. }
  16294. else {
  16295. mesh.layerMask = 0x0FFFFFFF;
  16296. }
  16297. // Instances
  16298. if (parsedMesh.instances) {
  16299. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16300. var parsedInstance = parsedMesh.instances[index];
  16301. var instance = mesh.createInstance(parsedInstance.name);
  16302. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16303. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16304. if (parsedInstance.rotationQuaternion) {
  16305. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16306. }
  16307. else if (parsedInstance.rotation) {
  16308. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16309. }
  16310. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16311. instance.checkCollisions = mesh.checkCollisions;
  16312. if (parsedMesh.animations) {
  16313. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16314. parsedAnimation = parsedMesh.animations[animationIndex];
  16315. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16316. }
  16317. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16318. }
  16319. }
  16320. }
  16321. return mesh;
  16322. };
  16323. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16324. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16325. pathArray: pathArray,
  16326. closeArray: closeArray,
  16327. closePath: closePath,
  16328. offset: offset,
  16329. updatable: updatable,
  16330. sideOrientation: sideOrientation,
  16331. instance: instance
  16332. }, scene);
  16333. };
  16334. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16335. var options = {
  16336. radius: radius,
  16337. tessellation: tessellation,
  16338. sideOrientation: sideOrientation,
  16339. updatable: updatable
  16340. };
  16341. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16342. };
  16343. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16344. var options = {
  16345. size: size,
  16346. sideOrientation: sideOrientation,
  16347. updatable: updatable
  16348. };
  16349. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16350. };
  16351. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16352. var options = {
  16353. segments: segments,
  16354. diameterX: diameter,
  16355. diameterY: diameter,
  16356. diameterZ: diameter,
  16357. sideOrientation: sideOrientation,
  16358. updatable: updatable
  16359. };
  16360. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16361. };
  16362. // Cylinder and cone
  16363. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16364. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16365. if (scene !== undefined) {
  16366. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16367. updatable = scene;
  16368. }
  16369. scene = subdivisions;
  16370. subdivisions = 1;
  16371. }
  16372. var options = {
  16373. height: height,
  16374. diameterTop: diameterTop,
  16375. diameterBottom: diameterBottom,
  16376. tessellation: tessellation,
  16377. subdivisions: subdivisions,
  16378. sideOrientation: sideOrientation,
  16379. updatable: updatable
  16380. };
  16381. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16382. };
  16383. // Torus (Code from SharpDX.org)
  16384. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16385. var options = {
  16386. diameter: diameter,
  16387. thickness: thickness,
  16388. tessellation: tessellation,
  16389. sideOrientation: sideOrientation,
  16390. updatable: updatable
  16391. };
  16392. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16393. };
  16394. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16395. var options = {
  16396. radius: radius,
  16397. tube: tube,
  16398. radialSegments: radialSegments,
  16399. tubularSegments: tubularSegments,
  16400. p: p,
  16401. q: q,
  16402. sideOrientation: sideOrientation,
  16403. updatable: updatable
  16404. };
  16405. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16406. };
  16407. // Lines
  16408. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16409. var options = {
  16410. points: points,
  16411. updatable: updatable,
  16412. instance: instance
  16413. };
  16414. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16415. };
  16416. // Dashed Lines
  16417. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16418. var options = {
  16419. points: points,
  16420. dashSize: dashSize,
  16421. gapSize: gapSize,
  16422. dashNb: dashNb,
  16423. updatable: updatable
  16424. };
  16425. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16426. };
  16427. // Extrusion
  16428. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16429. var options = {
  16430. shape: shape,
  16431. path: path,
  16432. scale: scale,
  16433. rotation: rotation,
  16434. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16435. sideOrientation: sideOrientation,
  16436. instance: instance,
  16437. updatable: updatable
  16438. };
  16439. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16440. };
  16441. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16442. var options = {
  16443. shape: shape,
  16444. path: path,
  16445. scaleFunction: scaleFunction,
  16446. rotationFunction: rotationFunction,
  16447. ribbonCloseArray: ribbonCloseArray,
  16448. ribbonClosePath: ribbonClosePath,
  16449. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16450. sideOrientation: sideOrientation,
  16451. instance: instance,
  16452. updatable: updatable
  16453. };
  16454. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16455. };
  16456. // Lathe
  16457. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16458. var options = {
  16459. shape: shape,
  16460. radius: radius,
  16461. tessellation: tessellation,
  16462. sideOrientation: sideOrientation,
  16463. updatable: updatable
  16464. };
  16465. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16466. };
  16467. // Plane & ground
  16468. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16469. var options = {
  16470. size: size,
  16471. width: size,
  16472. height: size,
  16473. sideOrientation: sideOrientation,
  16474. updatable: updatable
  16475. };
  16476. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16477. };
  16478. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16479. var options = {
  16480. width: width,
  16481. height: height,
  16482. subdivisions: subdivisions,
  16483. updatable: updatable
  16484. };
  16485. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16486. };
  16487. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16488. var options = {
  16489. xmin: xmin,
  16490. zmin: zmin,
  16491. xmax: xmax,
  16492. zmax: zmax,
  16493. subdivisions: subdivisions,
  16494. precision: precision,
  16495. updatable: updatable
  16496. };
  16497. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16498. };
  16499. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16500. var options = {
  16501. width: width,
  16502. height: height,
  16503. subdivisions: subdivisions,
  16504. minHeight: minHeight,
  16505. maxHeight: maxHeight,
  16506. updatable: updatable,
  16507. onReady: onReady
  16508. };
  16509. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16510. };
  16511. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16512. var options = {
  16513. path: path,
  16514. radius: radius,
  16515. tessellation: tessellation,
  16516. radiusFunction: radiusFunction,
  16517. arc: 1,
  16518. cap: cap,
  16519. updatable: updatable,
  16520. sideOrientation: sideOrientation,
  16521. instance: instance
  16522. };
  16523. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16524. };
  16525. Mesh.CreatePolyhedron = function (name, options, scene) {
  16526. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16527. };
  16528. Mesh.CreateIcoSphere = function (name, options, scene) {
  16529. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16530. };
  16531. // Decals
  16532. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16533. var options = {
  16534. position: position,
  16535. normal: normal,
  16536. size: size,
  16537. angle: angle
  16538. };
  16539. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16540. };
  16541. // Skeletons
  16542. /**
  16543. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16544. */
  16545. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16546. var source;
  16547. if (!this._sourcePositions) {
  16548. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16549. this._sourcePositions = new Float32Array(source);
  16550. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16551. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16552. }
  16553. }
  16554. return this._sourcePositions;
  16555. };
  16556. /**
  16557. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16558. */
  16559. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16560. var source;
  16561. if (!this._sourceNormals) {
  16562. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16563. this._sourceNormals = new Float32Array(source);
  16564. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16565. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16566. }
  16567. }
  16568. return this._sourceNormals;
  16569. };
  16570. /**
  16571. * Update the vertex buffers by applying transformation from the bones
  16572. * @param {skeleton} skeleton to apply
  16573. */
  16574. Mesh.prototype.applySkeleton = function (skeleton) {
  16575. if (!this.geometry) {
  16576. return;
  16577. }
  16578. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16579. return;
  16580. }
  16581. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16582. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16583. return this;
  16584. }
  16585. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16586. return this;
  16587. }
  16588. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16589. return this;
  16590. }
  16591. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16592. return this;
  16593. }
  16594. if (!this._sourcePositions) {
  16595. this.setPositionsForCPUSkinning();
  16596. }
  16597. if (!this._sourceNormals) {
  16598. this.setNormalsForCPUSkinning();
  16599. }
  16600. // positionsData checks for not being Float32Array will only pass at most once
  16601. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16602. if (!(positionsData instanceof Float32Array)) {
  16603. positionsData = new Float32Array(positionsData);
  16604. }
  16605. // normalsData checks for not being Float32Array will only pass at most once
  16606. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16607. if (!(normalsData instanceof Float32Array)) {
  16608. normalsData = new Float32Array(normalsData);
  16609. }
  16610. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16611. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16612. var needExtras = this.numBoneInfluencers > 4;
  16613. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16614. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16615. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16616. var tempVector3 = BABYLON.Vector3.Zero();
  16617. var finalMatrix = new BABYLON.Matrix();
  16618. var tempMatrix = new BABYLON.Matrix();
  16619. var matWeightIdx = 0;
  16620. var inf;
  16621. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16622. var weight;
  16623. for (inf = 0; inf < 4; inf++) {
  16624. weight = matricesWeightsData[matWeightIdx + inf];
  16625. if (weight > 0) {
  16626. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16627. finalMatrix.addToSelf(tempMatrix);
  16628. }
  16629. else
  16630. break;
  16631. }
  16632. if (needExtras) {
  16633. for (inf = 0; inf < 4; inf++) {
  16634. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16635. if (weight > 0) {
  16636. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16637. finalMatrix.addToSelf(tempMatrix);
  16638. }
  16639. else
  16640. break;
  16641. }
  16642. }
  16643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16644. tempVector3.toArray(positionsData, index);
  16645. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16646. tempVector3.toArray(normalsData, index);
  16647. finalMatrix.reset();
  16648. }
  16649. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16650. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16651. return this;
  16652. };
  16653. // Tools
  16654. Mesh.MinMax = function (meshes) {
  16655. var minVector = null;
  16656. var maxVector = null;
  16657. for (var i in meshes) {
  16658. var mesh = meshes[i];
  16659. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16660. if (!minVector) {
  16661. minVector = boundingBox.minimumWorld;
  16662. maxVector = boundingBox.maximumWorld;
  16663. continue;
  16664. }
  16665. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16666. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16667. }
  16668. return {
  16669. min: minVector,
  16670. max: maxVector
  16671. };
  16672. };
  16673. Mesh.Center = function (meshesOrMinMaxVector) {
  16674. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16675. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16676. };
  16677. /**
  16678. * Merge the array of meshes into a single mesh for performance reasons.
  16679. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16680. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16681. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16682. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16683. */
  16684. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16685. if (disposeSource === void 0) { disposeSource = true; }
  16686. var index;
  16687. if (!allow32BitsIndices) {
  16688. var totalVertices = 0;
  16689. // Counting vertices
  16690. for (index = 0; index < meshes.length; index++) {
  16691. if (meshes[index]) {
  16692. totalVertices += meshes[index].getTotalVertices();
  16693. if (totalVertices > 65536) {
  16694. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16695. return null;
  16696. }
  16697. }
  16698. }
  16699. }
  16700. // Merge
  16701. var vertexData;
  16702. var otherVertexData;
  16703. var source;
  16704. for (index = 0; index < meshes.length; index++) {
  16705. if (meshes[index]) {
  16706. meshes[index].computeWorldMatrix(true);
  16707. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16708. otherVertexData.transform(meshes[index].getWorldMatrix());
  16709. if (vertexData) {
  16710. vertexData.merge(otherVertexData);
  16711. }
  16712. else {
  16713. vertexData = otherVertexData;
  16714. source = meshes[index];
  16715. }
  16716. }
  16717. }
  16718. if (!meshSubclass) {
  16719. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16720. }
  16721. vertexData.applyToMesh(meshSubclass);
  16722. // Setting properties
  16723. meshSubclass.material = source.material;
  16724. meshSubclass.checkCollisions = source.checkCollisions;
  16725. // Cleaning
  16726. if (disposeSource) {
  16727. for (index = 0; index < meshes.length; index++) {
  16728. if (meshes[index]) {
  16729. meshes[index].dispose();
  16730. }
  16731. }
  16732. }
  16733. return meshSubclass;
  16734. };
  16735. // Consts
  16736. Mesh._FRONTSIDE = 0;
  16737. Mesh._BACKSIDE = 1;
  16738. Mesh._DOUBLESIDE = 2;
  16739. Mesh._DEFAULTSIDE = 0;
  16740. Mesh._NO_CAP = 0;
  16741. Mesh._CAP_START = 1;
  16742. Mesh._CAP_END = 2;
  16743. Mesh._CAP_ALL = 3;
  16744. return Mesh;
  16745. })(BABYLON.AbstractMesh);
  16746. BABYLON.Mesh = Mesh;
  16747. })(BABYLON || (BABYLON = {}));
  16748. var BABYLON;
  16749. (function (BABYLON) {
  16750. var SubMesh = (function () {
  16751. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16752. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16753. this.materialIndex = materialIndex;
  16754. this.verticesStart = verticesStart;
  16755. this.verticesCount = verticesCount;
  16756. this.indexStart = indexStart;
  16757. this.indexCount = indexCount;
  16758. this._renderId = 0;
  16759. this._mesh = mesh;
  16760. this._renderingMesh = renderingMesh || mesh;
  16761. mesh.subMeshes.push(this);
  16762. this._trianglePlanes = [];
  16763. this._id = mesh.subMeshes.length - 1;
  16764. if (createBoundingBox) {
  16765. this.refreshBoundingInfo();
  16766. mesh.computeWorldMatrix(true);
  16767. }
  16768. }
  16769. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16770. get: function () {
  16771. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. SubMesh.prototype.getBoundingInfo = function () {
  16777. if (this.IsGlobal) {
  16778. return this._mesh.getBoundingInfo();
  16779. }
  16780. return this._boundingInfo;
  16781. };
  16782. SubMesh.prototype.getMesh = function () {
  16783. return this._mesh;
  16784. };
  16785. SubMesh.prototype.getRenderingMesh = function () {
  16786. return this._renderingMesh;
  16787. };
  16788. SubMesh.prototype.getMaterial = function () {
  16789. var rootMaterial = this._renderingMesh.material;
  16790. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16791. var multiMaterial = rootMaterial;
  16792. return multiMaterial.getSubMaterial(this.materialIndex);
  16793. }
  16794. if (!rootMaterial) {
  16795. return this._mesh.getScene().defaultMaterial;
  16796. }
  16797. return rootMaterial;
  16798. };
  16799. // Methods
  16800. SubMesh.prototype.refreshBoundingInfo = function () {
  16801. this._lastColliderWorldVertices = null;
  16802. if (this.IsGlobal) {
  16803. return;
  16804. }
  16805. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16806. if (!data) {
  16807. this._boundingInfo = this._mesh._boundingInfo;
  16808. return;
  16809. }
  16810. var indices = this._renderingMesh.getIndices();
  16811. var extend;
  16812. //is this the only submesh?
  16813. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16814. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16815. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16816. }
  16817. else {
  16818. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16819. }
  16820. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16821. };
  16822. SubMesh.prototype._checkCollision = function (collider) {
  16823. return this.getBoundingInfo()._checkCollision(collider);
  16824. };
  16825. SubMesh.prototype.updateBoundingInfo = function (world) {
  16826. if (!this.getBoundingInfo()) {
  16827. this.refreshBoundingInfo();
  16828. }
  16829. this.getBoundingInfo().update(world);
  16830. };
  16831. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16832. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16833. };
  16834. SubMesh.prototype.render = function (enableAlphaMode) {
  16835. this._renderingMesh.render(this, enableAlphaMode);
  16836. };
  16837. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16838. if (!this._linesIndexBuffer) {
  16839. var linesIndices = [];
  16840. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16841. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16842. }
  16843. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16844. this.linesIndexCount = linesIndices.length;
  16845. }
  16846. return this._linesIndexBuffer;
  16847. };
  16848. SubMesh.prototype.canIntersects = function (ray) {
  16849. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16850. };
  16851. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16852. var intersectInfo = null;
  16853. // Triangles test
  16854. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16855. var p0 = positions[indices[index]];
  16856. var p1 = positions[indices[index + 1]];
  16857. var p2 = positions[indices[index + 2]];
  16858. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16859. if (currentIntersectInfo) {
  16860. if (currentIntersectInfo.distance < 0) {
  16861. continue;
  16862. }
  16863. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16864. intersectInfo = currentIntersectInfo;
  16865. intersectInfo.faceId = index / 3;
  16866. if (fastCheck) {
  16867. break;
  16868. }
  16869. }
  16870. }
  16871. }
  16872. return intersectInfo;
  16873. };
  16874. // Clone
  16875. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16876. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16877. if (!this.IsGlobal) {
  16878. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16879. }
  16880. return result;
  16881. };
  16882. // Dispose
  16883. SubMesh.prototype.dispose = function () {
  16884. if (this._linesIndexBuffer) {
  16885. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16886. this._linesIndexBuffer = null;
  16887. }
  16888. // Remove from mesh
  16889. var index = this._mesh.subMeshes.indexOf(this);
  16890. this._mesh.subMeshes.splice(index, 1);
  16891. };
  16892. // Statics
  16893. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16894. var minVertexIndex = Number.MAX_VALUE;
  16895. var maxVertexIndex = -Number.MAX_VALUE;
  16896. renderingMesh = renderingMesh || mesh;
  16897. var indices = renderingMesh.getIndices();
  16898. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16899. var vertexIndex = indices[index];
  16900. if (vertexIndex < minVertexIndex)
  16901. minVertexIndex = vertexIndex;
  16902. if (vertexIndex > maxVertexIndex)
  16903. maxVertexIndex = vertexIndex;
  16904. }
  16905. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16906. };
  16907. return SubMesh;
  16908. })();
  16909. BABYLON.SubMesh = SubMesh;
  16910. })(BABYLON || (BABYLON = {}));
  16911. var BABYLON;
  16912. (function (BABYLON) {
  16913. var MeshBuilder = (function () {
  16914. function MeshBuilder() {
  16915. }
  16916. MeshBuilder.CreateBox = function (name, options, scene) {
  16917. var box = new BABYLON.Mesh(name, scene);
  16918. var vertexData = BABYLON.VertexData.CreateBox(options);
  16919. vertexData.applyToMesh(box, options.updatable);
  16920. return box;
  16921. };
  16922. MeshBuilder.CreateSphere = function (name, options, scene) {
  16923. var sphere = new BABYLON.Mesh(name, scene);
  16924. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16925. vertexData.applyToMesh(sphere, options.updatable);
  16926. return sphere;
  16927. };
  16928. MeshBuilder.CreateDisc = function (name, options, scene) {
  16929. var disc = new BABYLON.Mesh(name, scene);
  16930. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16931. vertexData.applyToMesh(disc, options.updatable);
  16932. return disc;
  16933. };
  16934. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16935. var sphere = new BABYLON.Mesh(name, scene);
  16936. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16937. vertexData.applyToMesh(sphere, options.updatable);
  16938. return sphere;
  16939. };
  16940. ;
  16941. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16942. var pathArray = options.pathArray;
  16943. var closeArray = options.closeArray;
  16944. var closePath = options.closePath;
  16945. var offset = options.offset;
  16946. var sideOrientation = options.sideOrientation;
  16947. var instance = options.instance;
  16948. var updatable = options.updatable;
  16949. if (instance) {
  16950. // positionFunction : ribbon case
  16951. // only pathArray and sideOrientation parameters are taken into account for positions update
  16952. var positionFunction = function (positions) {
  16953. var minlg = pathArray[0].length;
  16954. var i = 0;
  16955. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16956. for (var si = 1; si <= ns; si++) {
  16957. for (var p = 0; p < pathArray.length; p++) {
  16958. var path = pathArray[p];
  16959. var l = path.length;
  16960. minlg = (minlg < l) ? minlg : l;
  16961. var j = 0;
  16962. while (j < minlg) {
  16963. positions[i] = path[j].x;
  16964. positions[i + 1] = path[j].y;
  16965. positions[i + 2] = path[j].z;
  16966. j++;
  16967. i += 3;
  16968. }
  16969. if (instance._closePath) {
  16970. positions[i] = path[0].x;
  16971. positions[i + 1] = path[0].y;
  16972. positions[i + 2] = path[0].z;
  16973. i += 3;
  16974. }
  16975. }
  16976. }
  16977. };
  16978. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16979. positionFunction(positions);
  16980. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16981. if (!(instance.areNormalsFrozen)) {
  16982. var indices = instance.getIndices();
  16983. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16984. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16985. if (instance._closePath) {
  16986. var indexFirst = 0;
  16987. var indexLast = 0;
  16988. for (var p = 0; p < pathArray.length; p++) {
  16989. indexFirst = instance._idx[p] * 3;
  16990. if (p + 1 < pathArray.length) {
  16991. indexLast = (instance._idx[p + 1] - 1) * 3;
  16992. }
  16993. else {
  16994. indexLast = normals.length - 3;
  16995. }
  16996. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16997. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16998. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16999. normals[indexLast] = normals[indexFirst];
  17000. normals[indexLast + 1] = normals[indexFirst + 1];
  17001. normals[indexLast + 2] = normals[indexFirst + 2];
  17002. }
  17003. }
  17004. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17005. }
  17006. return instance;
  17007. }
  17008. else {
  17009. var ribbon = new BABYLON.Mesh(name, scene);
  17010. ribbon.sideOrientation = sideOrientation;
  17011. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17012. if (closePath) {
  17013. ribbon._idx = vertexData._idx;
  17014. }
  17015. ribbon._closePath = closePath;
  17016. ribbon._closeArray = closeArray;
  17017. vertexData.applyToMesh(ribbon, updatable);
  17018. return ribbon;
  17019. }
  17020. };
  17021. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17022. var cylinder = new BABYLON.Mesh(name, scene);
  17023. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17024. vertexData.applyToMesh(cylinder, options.updatable);
  17025. return cylinder;
  17026. };
  17027. MeshBuilder.CreateTorus = function (name, options, scene) {
  17028. var torus = new BABYLON.Mesh(name, scene);
  17029. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17030. vertexData.applyToMesh(torus, options.updatable);
  17031. return torus;
  17032. };
  17033. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17034. var torusKnot = new BABYLON.Mesh(name, scene);
  17035. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17036. vertexData.applyToMesh(torusKnot, options.updatable);
  17037. return torusKnot;
  17038. };
  17039. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17040. var instance = options.instance;
  17041. var lines = options.lines;
  17042. if (instance) {
  17043. var positionFunction = function (positions) {
  17044. var i = 0;
  17045. for (var l = 0; l < lines.length; l++) {
  17046. var points = lines[l];
  17047. for (var p = 0; p < points.length; p++) {
  17048. positions[i] = points[p].x;
  17049. positions[i + 1] = points[p].y;
  17050. positions[i + 2] = points[p].z;
  17051. i += 3;
  17052. }
  17053. }
  17054. };
  17055. instance.updateMeshPositions(positionFunction, false);
  17056. return instance;
  17057. }
  17058. // line system creation
  17059. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17060. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17061. vertexData.applyToMesh(lineSystem, options.updatable);
  17062. return lineSystem;
  17063. };
  17064. MeshBuilder.CreateLines = function (name, options, scene) {
  17065. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17066. return lines;
  17067. };
  17068. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17069. var points = options.points;
  17070. var instance = options.instance;
  17071. var gapSize = options.gapSize;
  17072. var dashNb = options.dashNb;
  17073. var dashSize = options.dashSize;
  17074. if (instance) {
  17075. var positionFunction = function (positions) {
  17076. var curvect = BABYLON.Vector3.Zero();
  17077. var nbSeg = positions.length / 6;
  17078. var lg = 0;
  17079. var nb = 0;
  17080. var shft = 0;
  17081. var dashshft = 0;
  17082. var curshft = 0;
  17083. var p = 0;
  17084. var i = 0;
  17085. var j = 0;
  17086. for (i = 0; i < points.length - 1; i++) {
  17087. points[i + 1].subtractToRef(points[i], curvect);
  17088. lg += curvect.length();
  17089. }
  17090. shft = lg / nbSeg;
  17091. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17092. for (i = 0; i < points.length - 1; i++) {
  17093. points[i + 1].subtractToRef(points[i], curvect);
  17094. nb = Math.floor(curvect.length() / shft);
  17095. curvect.normalize();
  17096. j = 0;
  17097. while (j < nb && p < positions.length) {
  17098. curshft = shft * j;
  17099. positions[p] = points[i].x + curshft * curvect.x;
  17100. positions[p + 1] = points[i].y + curshft * curvect.y;
  17101. positions[p + 2] = points[i].z + curshft * curvect.z;
  17102. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17103. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17104. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17105. p += 6;
  17106. j++;
  17107. }
  17108. }
  17109. while (p < positions.length) {
  17110. positions[p] = points[i].x;
  17111. positions[p + 1] = points[i].y;
  17112. positions[p + 2] = points[i].z;
  17113. p += 3;
  17114. }
  17115. };
  17116. instance.updateMeshPositions(positionFunction, false);
  17117. return instance;
  17118. }
  17119. // dashed lines creation
  17120. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17121. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17122. vertexData.applyToMesh(dashedLines, options.updatable);
  17123. dashedLines.dashSize = dashSize;
  17124. dashedLines.gapSize = gapSize;
  17125. return dashedLines;
  17126. };
  17127. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17128. var path = options.path;
  17129. var shape = options.shape;
  17130. var scale = options.scale || 1;
  17131. var rotation = options.rotation || 0;
  17132. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17133. var updatable = options.updatable;
  17134. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17135. var instance = options.instance;
  17136. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17137. };
  17138. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17139. var path = options.path;
  17140. var shape = options.shape;
  17141. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17142. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17143. var ribbonCloseArray = options.ribbonCloseArray || false;
  17144. var ribbonClosePath = options.ribbonClosePath || false;
  17145. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17146. var updatable = options.updatable;
  17147. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17148. var instance = options.instance;
  17149. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17150. };
  17151. MeshBuilder.CreateLathe = function (name, options, scene) {
  17152. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17153. var closed = (options.closed === undefined) ? true : options.closed;
  17154. var shape = options.shape;
  17155. var radius = options.radius || 1;
  17156. var tessellation = options.tessellation || 64;
  17157. var updatable = options.updatable;
  17158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17159. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17160. var pi2 = Math.PI * 2;
  17161. var paths = new Array();
  17162. var i = 0;
  17163. var p = 0;
  17164. var step = pi2 / tessellation * arc;
  17165. var rotated;
  17166. var path = new Array();
  17167. ;
  17168. for (i = 0; i <= tessellation; i++) {
  17169. var path = [];
  17170. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17171. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17172. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17173. }
  17174. for (p = 0; p < shape.length; p++) {
  17175. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17176. path.push(rotated);
  17177. }
  17178. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17179. 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));
  17180. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17181. }
  17182. paths.push(path);
  17183. }
  17184. // lathe ribbon
  17185. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17186. return lathe;
  17187. };
  17188. MeshBuilder.CreatePlane = function (name, options, scene) {
  17189. var plane = new BABYLON.Mesh(name, scene);
  17190. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17191. vertexData.applyToMesh(plane, options.updatable);
  17192. if (options.sourcePlane) {
  17193. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17194. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17195. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17196. plane.rotate(vectorProduct, product);
  17197. }
  17198. return plane;
  17199. };
  17200. MeshBuilder.CreateGround = function (name, options, scene) {
  17201. var ground = new BABYLON.GroundMesh(name, scene);
  17202. ground._setReady(false);
  17203. ground._subdivisions = options.subdivisions || 1;
  17204. ground._width = options.width || 1;
  17205. ground._height = options.height || 1;
  17206. ground._maxX = ground._width / 2;
  17207. ground._maxZ = ground._height / 2;
  17208. ground._minX = -ground._maxX;
  17209. ground._minZ = -ground._maxZ;
  17210. var vertexData = BABYLON.VertexData.CreateGround(options);
  17211. vertexData.applyToMesh(ground, options.updatable);
  17212. ground._setReady(true);
  17213. return ground;
  17214. };
  17215. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17216. var tiledGround = new BABYLON.Mesh(name, scene);
  17217. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17218. vertexData.applyToMesh(tiledGround, options.updatable);
  17219. return tiledGround;
  17220. };
  17221. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17222. var width = options.width || 10;
  17223. var height = options.height || 10;
  17224. var subdivisions = options.subdivisions || 1;
  17225. var minHeight = options.minHeight;
  17226. var maxHeight = options.maxHeight || 10;
  17227. var updatable = options.updatable;
  17228. var onReady = options.onReady;
  17229. var ground = new BABYLON.GroundMesh(name, scene);
  17230. ground._subdivisions = subdivisions;
  17231. ground._width = width;
  17232. ground._height = height;
  17233. ground._maxX = ground._width / 2;
  17234. ground._maxZ = ground._height / 2;
  17235. ground._minX = -ground._maxX;
  17236. ground._minZ = -ground._maxZ;
  17237. ground._setReady(false);
  17238. var onload = function (img) {
  17239. // Getting height map data
  17240. var canvas = document.createElement("canvas");
  17241. var context = canvas.getContext("2d");
  17242. var bufferWidth = img.width;
  17243. var bufferHeight = img.height;
  17244. canvas.width = bufferWidth;
  17245. canvas.height = bufferHeight;
  17246. context.drawImage(img, 0, 0);
  17247. // Create VertexData from map data
  17248. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17249. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17250. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17251. width: width, height: height,
  17252. subdivisions: subdivisions,
  17253. minHeight: minHeight, maxHeight: maxHeight,
  17254. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17255. });
  17256. vertexData.applyToMesh(ground, updatable);
  17257. ground._setReady(true);
  17258. //execute ready callback, if set
  17259. if (onReady) {
  17260. onReady(ground);
  17261. }
  17262. };
  17263. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17264. return ground;
  17265. };
  17266. MeshBuilder.CreateTube = function (name, options, scene) {
  17267. var path = options.path;
  17268. var radius = options.radius || 1;
  17269. var tessellation = options.tessellation || 64;
  17270. var radiusFunction = options.radiusFunction;
  17271. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17272. var updatable = options.updatable;
  17273. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17274. var instance = options.instance;
  17275. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17276. // tube geometry
  17277. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17278. var tangents = path3D.getTangents();
  17279. var normals = path3D.getNormals();
  17280. var distances = path3D.getDistances();
  17281. var pi2 = Math.PI * 2;
  17282. var step = pi2 / tessellation * arc;
  17283. var returnRadius = function () { return radius; };
  17284. var radiusFunctionFinal = radiusFunction || returnRadius;
  17285. var circlePath;
  17286. var rad;
  17287. var normal;
  17288. var rotated;
  17289. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17290. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17291. for (var i = 0; i < path.length; i++) {
  17292. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17293. circlePath = Array(); // current circle array
  17294. normal = normals[i]; // current normal
  17295. for (var t = 0; t < tessellation; t++) {
  17296. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17297. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17298. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17299. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17300. circlePath[t] = rotated;
  17301. }
  17302. circlePaths[index] = circlePath;
  17303. index++;
  17304. }
  17305. // cap
  17306. var capPath = function (nbPoints, pathIndex) {
  17307. var pointCap = Array();
  17308. for (var i = 0; i < nbPoints; i++) {
  17309. pointCap.push(path[pathIndex]);
  17310. }
  17311. return pointCap;
  17312. };
  17313. switch (cap) {
  17314. case BABYLON.Mesh.NO_CAP:
  17315. break;
  17316. case BABYLON.Mesh.CAP_START:
  17317. circlePaths[0] = capPath(tessellation, 0);
  17318. circlePaths[1] = circlePaths[2].slice(0);
  17319. break;
  17320. case BABYLON.Mesh.CAP_END:
  17321. circlePaths[index] = circlePaths[index - 1].slice(0);
  17322. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17323. break;
  17324. case BABYLON.Mesh.CAP_ALL:
  17325. circlePaths[0] = capPath(tessellation, 0);
  17326. circlePaths[1] = circlePaths[2].slice(0);
  17327. circlePaths[index] = circlePaths[index - 1].slice(0);
  17328. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17329. break;
  17330. default:
  17331. break;
  17332. }
  17333. return circlePaths;
  17334. };
  17335. var path3D;
  17336. var pathArray;
  17337. if (instance) {
  17338. var arc = options.arc || instance.arc;
  17339. path3D = (instance.path3D).update(path);
  17340. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17341. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17342. instance.path3D = path3D;
  17343. instance.pathArray = pathArray;
  17344. instance.arc = arc;
  17345. return instance;
  17346. }
  17347. // tube creation
  17348. path3D = new BABYLON.Path3D(path);
  17349. var newPathArray = new Array();
  17350. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17351. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17352. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17353. tube.pathArray = pathArray;
  17354. tube.path3D = path3D;
  17355. tube.tessellation = tessellation;
  17356. tube.cap = cap;
  17357. tube.arc = options.arc;
  17358. return tube;
  17359. };
  17360. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17361. var polyhedron = new BABYLON.Mesh(name, scene);
  17362. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17363. vertexData.applyToMesh(polyhedron, options.updatable);
  17364. return polyhedron;
  17365. };
  17366. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17367. var indices = sourceMesh.getIndices();
  17368. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17369. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17370. var position = options.position || BABYLON.Vector3.Zero();
  17371. var normal = options.normal || BABYLON.Vector3.Up();
  17372. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17373. var angle = options.angle || 0;
  17374. // Getting correct rotation
  17375. if (!normal) {
  17376. var target = new BABYLON.Vector3(0, 0, 1);
  17377. var camera = sourceMesh.getScene().activeCamera;
  17378. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17379. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17380. }
  17381. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17382. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17383. var pitch = Math.atan2(normal.y, len);
  17384. // Matrix
  17385. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17386. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17387. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17388. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17389. var vertexData = new BABYLON.VertexData();
  17390. vertexData.indices = [];
  17391. vertexData.positions = [];
  17392. vertexData.normals = [];
  17393. vertexData.uvs = [];
  17394. var currentVertexDataIndex = 0;
  17395. var extractDecalVector3 = function (indexId) {
  17396. var vertexId = indices[indexId];
  17397. var result = new BABYLON.PositionNormalVertex();
  17398. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17399. // Send vector to decal local world
  17400. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17401. // Get normal
  17402. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17403. return result;
  17404. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17405. var clip = function (vertices, axis) {
  17406. if (vertices.length === 0) {
  17407. return vertices;
  17408. }
  17409. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17410. var clipVertices = function (v0, v1) {
  17411. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17412. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17413. };
  17414. var result = new Array();
  17415. for (var index = 0; index < vertices.length; index += 3) {
  17416. var v1Out;
  17417. var v2Out;
  17418. var v3Out;
  17419. var total = 0;
  17420. var nV1, nV2, nV3, nV4;
  17421. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17422. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17423. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17424. v1Out = d1 > 0;
  17425. v2Out = d2 > 0;
  17426. v3Out = d3 > 0;
  17427. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17428. switch (total) {
  17429. case 0:
  17430. result.push(vertices[index]);
  17431. result.push(vertices[index + 1]);
  17432. result.push(vertices[index + 2]);
  17433. break;
  17434. case 1:
  17435. if (v1Out) {
  17436. nV1 = vertices[index + 1];
  17437. nV2 = vertices[index + 2];
  17438. nV3 = clipVertices(vertices[index], nV1);
  17439. nV4 = clipVertices(vertices[index], nV2);
  17440. }
  17441. if (v2Out) {
  17442. nV1 = vertices[index];
  17443. nV2 = vertices[index + 2];
  17444. nV3 = clipVertices(vertices[index + 1], nV1);
  17445. nV4 = clipVertices(vertices[index + 1], nV2);
  17446. result.push(nV3);
  17447. result.push(nV2.clone());
  17448. result.push(nV1.clone());
  17449. result.push(nV2.clone());
  17450. result.push(nV3.clone());
  17451. result.push(nV4);
  17452. break;
  17453. }
  17454. if (v3Out) {
  17455. nV1 = vertices[index];
  17456. nV2 = vertices[index + 1];
  17457. nV3 = clipVertices(vertices[index + 2], nV1);
  17458. nV4 = clipVertices(vertices[index + 2], nV2);
  17459. }
  17460. result.push(nV1.clone());
  17461. result.push(nV2.clone());
  17462. result.push(nV3);
  17463. result.push(nV4);
  17464. result.push(nV3.clone());
  17465. result.push(nV2.clone());
  17466. break;
  17467. case 2:
  17468. if (!v1Out) {
  17469. nV1 = vertices[index].clone();
  17470. nV2 = clipVertices(nV1, vertices[index + 1]);
  17471. nV3 = clipVertices(nV1, vertices[index + 2]);
  17472. result.push(nV1);
  17473. result.push(nV2);
  17474. result.push(nV3);
  17475. }
  17476. if (!v2Out) {
  17477. nV1 = vertices[index + 1].clone();
  17478. nV2 = clipVertices(nV1, vertices[index + 2]);
  17479. nV3 = clipVertices(nV1, vertices[index]);
  17480. result.push(nV1);
  17481. result.push(nV2);
  17482. result.push(nV3);
  17483. }
  17484. if (!v3Out) {
  17485. nV1 = vertices[index + 2].clone();
  17486. nV2 = clipVertices(nV1, vertices[index]);
  17487. nV3 = clipVertices(nV1, vertices[index + 1]);
  17488. result.push(nV1);
  17489. result.push(nV2);
  17490. result.push(nV3);
  17491. }
  17492. break;
  17493. case 3:
  17494. break;
  17495. }
  17496. }
  17497. return result;
  17498. };
  17499. for (var index = 0; index < indices.length; index += 3) {
  17500. var faceVertices = new Array();
  17501. faceVertices.push(extractDecalVector3(index));
  17502. faceVertices.push(extractDecalVector3(index + 1));
  17503. faceVertices.push(extractDecalVector3(index + 2));
  17504. // Clip
  17505. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17506. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17507. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17510. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17511. if (faceVertices.length === 0) {
  17512. continue;
  17513. }
  17514. // Add UVs and get back to world
  17515. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17516. var vertex = faceVertices[vIndex];
  17517. //TODO check for Int32Array
  17518. vertexData.indices.push(currentVertexDataIndex);
  17519. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17520. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17521. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17522. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17523. currentVertexDataIndex++;
  17524. }
  17525. }
  17526. // Return mesh
  17527. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17528. vertexData.applyToMesh(decal);
  17529. decal.position = position.clone();
  17530. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17531. return decal;
  17532. };
  17533. // Privates
  17534. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17535. // extrusion geometry
  17536. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17537. var tangents = path3D.getTangents();
  17538. var normals = path3D.getNormals();
  17539. var binormals = path3D.getBinormals();
  17540. var distances = path3D.getDistances();
  17541. var angle = 0;
  17542. var returnScale = function () { return scale; };
  17543. var returnRotation = function () { return rotation; };
  17544. var rotate = custom ? rotateFunction : returnRotation;
  17545. var scl = custom ? scaleFunction : returnScale;
  17546. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17547. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17548. for (var i = 0; i < curve.length; i++) {
  17549. var shapePath = new Array();
  17550. var angleStep = rotate(i, distances[i]);
  17551. var scaleRatio = scl(i, distances[i]);
  17552. for (var p = 0; p < shape.length; p++) {
  17553. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17554. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17555. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17556. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17557. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17558. shapePath[p] = rotated;
  17559. }
  17560. shapePaths[index] = shapePath;
  17561. angle += angleStep;
  17562. index++;
  17563. }
  17564. // cap
  17565. var capPath = function (shapePath) {
  17566. var pointCap = Array();
  17567. var barycenter = BABYLON.Vector3.Zero();
  17568. var i;
  17569. for (i = 0; i < shapePath.length; i++) {
  17570. barycenter.addInPlace(shapePath[i]);
  17571. }
  17572. barycenter.scaleInPlace(1 / shapePath.length);
  17573. for (i = 0; i < shapePath.length; i++) {
  17574. pointCap.push(barycenter);
  17575. }
  17576. return pointCap;
  17577. };
  17578. switch (cap) {
  17579. case BABYLON.Mesh.NO_CAP:
  17580. break;
  17581. case BABYLON.Mesh.CAP_START:
  17582. shapePaths[0] = capPath(shapePaths[2]);
  17583. shapePaths[1] = shapePaths[2].slice(0);
  17584. break;
  17585. case BABYLON.Mesh.CAP_END:
  17586. shapePaths[index] = shapePaths[index - 1];
  17587. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17588. break;
  17589. case BABYLON.Mesh.CAP_ALL:
  17590. shapePaths[0] = capPath(shapePaths[2]);
  17591. shapePaths[1] = shapePaths[2].slice(0);
  17592. shapePaths[index] = shapePaths[index - 1];
  17593. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17594. break;
  17595. default:
  17596. break;
  17597. }
  17598. return shapePaths;
  17599. };
  17600. var path3D;
  17601. var pathArray;
  17602. if (instance) {
  17603. path3D = (instance.path3D).update(curve);
  17604. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17605. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17606. return instance;
  17607. }
  17608. // extruded shape creation
  17609. path3D = new BABYLON.Path3D(curve);
  17610. var newShapePaths = new Array();
  17611. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17612. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17613. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17614. extrudedGeneric.pathArray = pathArray;
  17615. extrudedGeneric.path3D = path3D;
  17616. extrudedGeneric.cap = cap;
  17617. return extrudedGeneric;
  17618. };
  17619. return MeshBuilder;
  17620. })();
  17621. BABYLON.MeshBuilder = MeshBuilder;
  17622. })(BABYLON || (BABYLON = {}));
  17623. var BABYLON;
  17624. (function (BABYLON) {
  17625. var BaseTexture = (function () {
  17626. function BaseTexture(scene) {
  17627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17628. this.hasAlpha = false;
  17629. this.getAlphaFromRGB = false;
  17630. this.level = 1;
  17631. this.isCube = false;
  17632. this.isRenderTarget = false;
  17633. this.animations = new Array();
  17634. this.coordinatesIndex = 0;
  17635. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17636. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17637. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17638. this.anisotropicFilteringLevel = 4;
  17639. this._scene = scene;
  17640. this._scene.textures.push(this);
  17641. }
  17642. BaseTexture.prototype.getScene = function () {
  17643. return this._scene;
  17644. };
  17645. BaseTexture.prototype.getTextureMatrix = function () {
  17646. return null;
  17647. };
  17648. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17649. return null;
  17650. };
  17651. BaseTexture.prototype.getInternalTexture = function () {
  17652. return this._texture;
  17653. };
  17654. BaseTexture.prototype.isReady = function () {
  17655. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17656. return true;
  17657. }
  17658. if (this._texture) {
  17659. return this._texture.isReady;
  17660. }
  17661. return false;
  17662. };
  17663. BaseTexture.prototype.getSize = function () {
  17664. if (this._texture._width) {
  17665. return { width: this._texture._width, height: this._texture._height };
  17666. }
  17667. if (this._texture._size) {
  17668. return { width: this._texture._size, height: this._texture._size };
  17669. }
  17670. return { width: 0, height: 0 };
  17671. };
  17672. BaseTexture.prototype.getBaseSize = function () {
  17673. if (!this.isReady())
  17674. return { width: 0, height: 0 };
  17675. if (this._texture._size) {
  17676. return { width: this._texture._size, height: this._texture._size };
  17677. }
  17678. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17679. };
  17680. BaseTexture.prototype.scale = function (ratio) {
  17681. };
  17682. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17683. get: function () {
  17684. return false;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17690. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17691. for (var index = 0; index < texturesCache.length; index++) {
  17692. var texturesCacheEntry = texturesCache[index];
  17693. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17694. texturesCache.splice(index, 1);
  17695. return;
  17696. }
  17697. }
  17698. };
  17699. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17700. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17701. for (var index = 0; index < texturesCache.length; index++) {
  17702. var texturesCacheEntry = texturesCache[index];
  17703. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17704. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17705. texturesCacheEntry.references++;
  17706. return texturesCacheEntry;
  17707. }
  17708. }
  17709. }
  17710. return null;
  17711. };
  17712. BaseTexture.prototype.delayLoad = function () {
  17713. };
  17714. BaseTexture.prototype.clone = function () {
  17715. return null;
  17716. };
  17717. BaseTexture.prototype.releaseInternalTexture = function () {
  17718. if (this._texture) {
  17719. this._scene.getEngine().releaseInternalTexture(this._texture);
  17720. delete this._texture;
  17721. }
  17722. };
  17723. BaseTexture.prototype.dispose = function () {
  17724. // Animations
  17725. this.getScene().stopAnimation(this);
  17726. // Remove from scene
  17727. var index = this._scene.textures.indexOf(this);
  17728. if (index >= 0) {
  17729. this._scene.textures.splice(index, 1);
  17730. }
  17731. if (this._texture === undefined) {
  17732. return;
  17733. }
  17734. // Release
  17735. this.releaseInternalTexture();
  17736. // Callback
  17737. if (this.onDispose) {
  17738. this.onDispose();
  17739. }
  17740. };
  17741. BaseTexture.prototype.serialize = function () {
  17742. var serializationObject = {};
  17743. if (!this.name) {
  17744. return null;
  17745. }
  17746. serializationObject.name = this.name;
  17747. serializationObject.hasAlpha = this.hasAlpha;
  17748. serializationObject.level = this.level;
  17749. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17750. serializationObject.coordinatesMode = this.coordinatesMode;
  17751. serializationObject.wrapU = this.wrapU;
  17752. serializationObject.wrapV = this.wrapV;
  17753. // Animations
  17754. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17755. return serializationObject;
  17756. };
  17757. return BaseTexture;
  17758. })();
  17759. BABYLON.BaseTexture = BaseTexture;
  17760. })(BABYLON || (BABYLON = {}));
  17761. var BABYLON;
  17762. (function (BABYLON) {
  17763. var Texture = (function (_super) {
  17764. __extends(Texture, _super);
  17765. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17766. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17767. if (onLoad === void 0) { onLoad = null; }
  17768. if (onError === void 0) { onError = null; }
  17769. if (buffer === void 0) { buffer = null; }
  17770. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17771. _super.call(this, scene);
  17772. this.uOffset = 0;
  17773. this.vOffset = 0;
  17774. this.uScale = 1.0;
  17775. this.vScale = 1.0;
  17776. this.uAng = 0;
  17777. this.vAng = 0;
  17778. this.wAng = 0;
  17779. this.name = url;
  17780. this.url = url;
  17781. this._noMipmap = noMipmap;
  17782. this._invertY = invertY;
  17783. this._samplingMode = samplingMode;
  17784. this._buffer = buffer;
  17785. this._deleteBuffer = deleteBuffer;
  17786. if (!url) {
  17787. return;
  17788. }
  17789. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17790. if (!this._texture) {
  17791. if (!scene.useDelayedTextureLoading) {
  17792. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17793. if (deleteBuffer) {
  17794. delete this._buffer;
  17795. }
  17796. }
  17797. else {
  17798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17799. this._delayedOnLoad = onLoad;
  17800. this._delayedOnError = onError;
  17801. }
  17802. }
  17803. else {
  17804. BABYLON.Tools.SetImmediate(function () {
  17805. if (onLoad) {
  17806. onLoad();
  17807. }
  17808. });
  17809. }
  17810. }
  17811. Texture.prototype.delayLoad = function () {
  17812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17813. return;
  17814. }
  17815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17816. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17817. if (!this._texture) {
  17818. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17819. if (this._deleteBuffer) {
  17820. delete this._buffer;
  17821. }
  17822. }
  17823. };
  17824. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17825. if (!this._texture) {
  17826. return;
  17827. }
  17828. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17829. };
  17830. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17831. x *= this.uScale;
  17832. y *= this.vScale;
  17833. x -= 0.5 * this.uScale;
  17834. y -= 0.5 * this.vScale;
  17835. z -= 0.5;
  17836. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17837. t.x += 0.5 * this.uScale + this.uOffset;
  17838. t.y += 0.5 * this.vScale + this.vOffset;
  17839. t.z += 0.5;
  17840. };
  17841. Texture.prototype.getTextureMatrix = function () {
  17842. if (this.uOffset === this._cachedUOffset &&
  17843. this.vOffset === this._cachedVOffset &&
  17844. this.uScale === this._cachedUScale &&
  17845. this.vScale === this._cachedVScale &&
  17846. this.uAng === this._cachedUAng &&
  17847. this.vAng === this._cachedVAng &&
  17848. this.wAng === this._cachedWAng) {
  17849. return this._cachedTextureMatrix;
  17850. }
  17851. this._cachedUOffset = this.uOffset;
  17852. this._cachedVOffset = this.vOffset;
  17853. this._cachedUScale = this.uScale;
  17854. this._cachedVScale = this.vScale;
  17855. this._cachedUAng = this.uAng;
  17856. this._cachedVAng = this.vAng;
  17857. this._cachedWAng = this.wAng;
  17858. if (!this._cachedTextureMatrix) {
  17859. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17860. this._rowGenerationMatrix = new BABYLON.Matrix();
  17861. this._t0 = BABYLON.Vector3.Zero();
  17862. this._t1 = BABYLON.Vector3.Zero();
  17863. this._t2 = BABYLON.Vector3.Zero();
  17864. }
  17865. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17866. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17867. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17868. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17869. this._t1.subtractInPlace(this._t0);
  17870. this._t2.subtractInPlace(this._t0);
  17871. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17872. this._cachedTextureMatrix.m[0] = this._t1.x;
  17873. this._cachedTextureMatrix.m[1] = this._t1.y;
  17874. this._cachedTextureMatrix.m[2] = this._t1.z;
  17875. this._cachedTextureMatrix.m[4] = this._t2.x;
  17876. this._cachedTextureMatrix.m[5] = this._t2.y;
  17877. this._cachedTextureMatrix.m[6] = this._t2.z;
  17878. this._cachedTextureMatrix.m[8] = this._t0.x;
  17879. this._cachedTextureMatrix.m[9] = this._t0.y;
  17880. this._cachedTextureMatrix.m[10] = this._t0.z;
  17881. return this._cachedTextureMatrix;
  17882. };
  17883. Texture.prototype.getReflectionTextureMatrix = function () {
  17884. if (this.uOffset === this._cachedUOffset &&
  17885. this.vOffset === this._cachedVOffset &&
  17886. this.uScale === this._cachedUScale &&
  17887. this.vScale === this._cachedVScale &&
  17888. this.coordinatesMode === this._cachedCoordinatesMode) {
  17889. return this._cachedTextureMatrix;
  17890. }
  17891. if (!this._cachedTextureMatrix) {
  17892. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17893. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17894. }
  17895. this._cachedCoordinatesMode = this.coordinatesMode;
  17896. switch (this.coordinatesMode) {
  17897. case Texture.PLANAR_MODE:
  17898. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17899. this._cachedTextureMatrix[0] = this.uScale;
  17900. this._cachedTextureMatrix[5] = this.vScale;
  17901. this._cachedTextureMatrix[12] = this.uOffset;
  17902. this._cachedTextureMatrix[13] = this.vOffset;
  17903. break;
  17904. case Texture.PROJECTION_MODE:
  17905. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17906. this._projectionModeMatrix.m[0] = 0.5;
  17907. this._projectionModeMatrix.m[5] = -0.5;
  17908. this._projectionModeMatrix.m[10] = 0.0;
  17909. this._projectionModeMatrix.m[12] = 0.5;
  17910. this._projectionModeMatrix.m[13] = 0.5;
  17911. this._projectionModeMatrix.m[14] = 1.0;
  17912. this._projectionModeMatrix.m[15] = 1.0;
  17913. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17914. break;
  17915. default:
  17916. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17917. break;
  17918. }
  17919. return this._cachedTextureMatrix;
  17920. };
  17921. Texture.prototype.clone = function () {
  17922. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17923. // Base texture
  17924. newTexture.hasAlpha = this.hasAlpha;
  17925. newTexture.level = this.level;
  17926. newTexture.wrapU = this.wrapU;
  17927. newTexture.wrapV = this.wrapV;
  17928. newTexture.coordinatesIndex = this.coordinatesIndex;
  17929. newTexture.coordinatesMode = this.coordinatesMode;
  17930. // Texture
  17931. newTexture.uOffset = this.uOffset;
  17932. newTexture.vOffset = this.vOffset;
  17933. newTexture.uScale = this.uScale;
  17934. newTexture.vScale = this.vScale;
  17935. newTexture.uAng = this.uAng;
  17936. newTexture.vAng = this.vAng;
  17937. newTexture.wAng = this.wAng;
  17938. return newTexture;
  17939. };
  17940. Texture.prototype.serialize = function () {
  17941. if (!this.name) {
  17942. return null;
  17943. }
  17944. var serializationObject = _super.prototype.serialize.call(this);
  17945. serializationObject.uOffset = this.uOffset;
  17946. serializationObject.vOffset = this.vOffset;
  17947. serializationObject.uScale = this.uScale;
  17948. serializationObject.vScale = this.vScale;
  17949. serializationObject.uAng = this.uAng;
  17950. serializationObject.vAng = this.vAng;
  17951. serializationObject.wAng = this.wAng;
  17952. return serializationObject;
  17953. };
  17954. // Statics
  17955. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17956. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17957. if (onLoad === void 0) { onLoad = null; }
  17958. if (onError === void 0) { onError = null; }
  17959. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17960. };
  17961. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17962. if (parsedTexture.isCube) {
  17963. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17964. }
  17965. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17966. return null;
  17967. }
  17968. var texture;
  17969. if (parsedTexture.mirrorPlane) {
  17970. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17971. texture._waitingRenderList = parsedTexture.renderList;
  17972. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17973. }
  17974. else if (parsedTexture.isRenderTarget) {
  17975. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17976. texture._waitingRenderList = parsedTexture.renderList;
  17977. }
  17978. else {
  17979. if (parsedTexture.base64String) {
  17980. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17981. }
  17982. else {
  17983. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17984. }
  17985. }
  17986. texture.name = parsedTexture.name;
  17987. texture.hasAlpha = parsedTexture.hasAlpha;
  17988. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17989. texture.level = parsedTexture.level;
  17990. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17991. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17992. texture.uOffset = parsedTexture.uOffset;
  17993. texture.vOffset = parsedTexture.vOffset;
  17994. texture.uScale = parsedTexture.uScale;
  17995. texture.vScale = parsedTexture.vScale;
  17996. texture.uAng = parsedTexture.uAng;
  17997. texture.vAng = parsedTexture.vAng;
  17998. texture.wAng = parsedTexture.wAng;
  17999. texture.wrapU = parsedTexture.wrapU;
  18000. texture.wrapV = parsedTexture.wrapV;
  18001. // Animations
  18002. if (parsedTexture.animations) {
  18003. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18004. var parsedAnimation = parsedTexture.animations[animationIndex];
  18005. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18006. }
  18007. }
  18008. return texture;
  18009. };
  18010. // Constants
  18011. Texture.NEAREST_SAMPLINGMODE = 1;
  18012. Texture.BILINEAR_SAMPLINGMODE = 2;
  18013. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18014. Texture.EXPLICIT_MODE = 0;
  18015. Texture.SPHERICAL_MODE = 1;
  18016. Texture.PLANAR_MODE = 2;
  18017. Texture.CUBIC_MODE = 3;
  18018. Texture.PROJECTION_MODE = 4;
  18019. Texture.SKYBOX_MODE = 5;
  18020. Texture.INVCUBIC_MODE = 6;
  18021. Texture.EQUIRECTANGULAR_MODE = 7;
  18022. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18023. Texture.CLAMP_ADDRESSMODE = 0;
  18024. Texture.WRAP_ADDRESSMODE = 1;
  18025. Texture.MIRROR_ADDRESSMODE = 2;
  18026. return Texture;
  18027. })(BABYLON.BaseTexture);
  18028. BABYLON.Texture = Texture;
  18029. })(BABYLON || (BABYLON = {}));
  18030. var BABYLON;
  18031. (function (BABYLON) {
  18032. var CubeTexture = (function (_super) {
  18033. __extends(CubeTexture, _super);
  18034. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18035. _super.call(this, scene);
  18036. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18037. this.name = rootUrl;
  18038. this.url = rootUrl;
  18039. this._noMipmap = noMipmap;
  18040. this.hasAlpha = false;
  18041. if (!rootUrl && !files) {
  18042. return;
  18043. }
  18044. this._texture = this._getFromCache(rootUrl, noMipmap);
  18045. if (!files) {
  18046. if (!extensions) {
  18047. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18048. }
  18049. files = [];
  18050. for (var index = 0; index < extensions.length; index++) {
  18051. files.push(rootUrl + extensions[index]);
  18052. }
  18053. this._extensions = extensions;
  18054. }
  18055. this._files = files;
  18056. if (!this._texture) {
  18057. if (!scene.useDelayedTextureLoading) {
  18058. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18059. }
  18060. else {
  18061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18062. }
  18063. }
  18064. this.isCube = true;
  18065. this._textureMatrix = BABYLON.Matrix.Identity();
  18066. }
  18067. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18068. return new CubeTexture("", scene, null, noMipmap, files);
  18069. };
  18070. CubeTexture.prototype.clone = function () {
  18071. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18072. // Base texture
  18073. newTexture.level = this.level;
  18074. newTexture.wrapU = this.wrapU;
  18075. newTexture.wrapV = this.wrapV;
  18076. newTexture.coordinatesIndex = this.coordinatesIndex;
  18077. newTexture.coordinatesMode = this.coordinatesMode;
  18078. return newTexture;
  18079. };
  18080. // Methods
  18081. CubeTexture.prototype.delayLoad = function () {
  18082. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18083. return;
  18084. }
  18085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18086. this._texture = this._getFromCache(this.url, this._noMipmap);
  18087. if (!this._texture) {
  18088. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18089. }
  18090. };
  18091. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18092. return this._textureMatrix;
  18093. };
  18094. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18095. var texture = null;
  18096. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18097. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18098. texture.name = parsedTexture.name;
  18099. texture.hasAlpha = parsedTexture.hasAlpha;
  18100. texture.level = parsedTexture.level;
  18101. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18102. }
  18103. return texture;
  18104. };
  18105. CubeTexture.prototype.serialize = function () {
  18106. if (!this.name) {
  18107. return null;
  18108. }
  18109. var serializationObject = {};
  18110. serializationObject.name = this.name;
  18111. serializationObject.hasAlpha = this.hasAlpha;
  18112. serializationObject.isCube = true;
  18113. serializationObject.level = this.level;
  18114. serializationObject.coordinatesMode = this.coordinatesMode;
  18115. return serializationObject;
  18116. };
  18117. return CubeTexture;
  18118. })(BABYLON.BaseTexture);
  18119. BABYLON.CubeTexture = CubeTexture;
  18120. })(BABYLON || (BABYLON = {}));
  18121. var BABYLON;
  18122. (function (BABYLON) {
  18123. var RenderTargetTexture = (function (_super) {
  18124. __extends(RenderTargetTexture, _super);
  18125. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18126. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18127. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18128. if (isCube === void 0) { isCube = false; }
  18129. _super.call(this, null, scene, !generateMipMaps);
  18130. this.isCube = isCube;
  18131. this.renderList = new Array();
  18132. this.renderParticles = true;
  18133. this.renderSprites = false;
  18134. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18135. this._currentRefreshId = -1;
  18136. this._refreshRate = 1;
  18137. this.name = name;
  18138. this.isRenderTarget = true;
  18139. this._size = size;
  18140. this._generateMipMaps = generateMipMaps;
  18141. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18142. if (isCube) {
  18143. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18144. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18145. this._textureMatrix = BABYLON.Matrix.Identity();
  18146. }
  18147. else {
  18148. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18149. }
  18150. // Rendering groups
  18151. this._renderingManager = new BABYLON.RenderingManager(scene);
  18152. }
  18153. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18154. get: function () {
  18155. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18156. },
  18157. enumerable: true,
  18158. configurable: true
  18159. });
  18160. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18161. get: function () {
  18162. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18168. get: function () {
  18169. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18175. this._currentRefreshId = -1;
  18176. };
  18177. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18178. get: function () {
  18179. return this._refreshRate;
  18180. },
  18181. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18182. set: function (value) {
  18183. this._refreshRate = value;
  18184. this.resetRefreshCounter();
  18185. },
  18186. enumerable: true,
  18187. configurable: true
  18188. });
  18189. RenderTargetTexture.prototype._shouldRender = function () {
  18190. if (this._currentRefreshId === -1) {
  18191. this._currentRefreshId = 1;
  18192. return true;
  18193. }
  18194. if (this.refreshRate === this._currentRefreshId) {
  18195. this._currentRefreshId = 1;
  18196. return true;
  18197. }
  18198. this._currentRefreshId++;
  18199. return false;
  18200. };
  18201. RenderTargetTexture.prototype.isReady = function () {
  18202. if (!this.getScene().renderTargetsEnabled) {
  18203. return false;
  18204. }
  18205. return _super.prototype.isReady.call(this);
  18206. };
  18207. RenderTargetTexture.prototype.getRenderSize = function () {
  18208. return this._size;
  18209. };
  18210. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18211. get: function () {
  18212. return true;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. RenderTargetTexture.prototype.scale = function (ratio) {
  18218. var newSize = this._size * ratio;
  18219. this.resize(newSize, this._generateMipMaps);
  18220. };
  18221. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18222. if (this.isCube) {
  18223. return this._textureMatrix;
  18224. }
  18225. return _super.prototype.getReflectionTextureMatrix.call(this);
  18226. };
  18227. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18228. this.releaseInternalTexture();
  18229. if (this.isCube) {
  18230. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18231. }
  18232. else {
  18233. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18234. }
  18235. };
  18236. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18237. var scene = this.getScene();
  18238. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18239. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18240. }
  18241. if (this._waitingRenderList) {
  18242. this.renderList = [];
  18243. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18244. var id = this._waitingRenderList[index];
  18245. this.renderList.push(scene.getMeshByID(id));
  18246. }
  18247. delete this._waitingRenderList;
  18248. }
  18249. if (this.renderList && this.renderList.length === 0) {
  18250. return;
  18251. }
  18252. // Prepare renderingManager
  18253. this._renderingManager.reset();
  18254. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18255. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18256. var mesh = currentRenderList[meshIndex];
  18257. if (mesh) {
  18258. if (!mesh.isReady()) {
  18259. // Reset _currentRefreshId
  18260. this.resetRefreshCounter();
  18261. continue;
  18262. }
  18263. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18264. mesh._activate(scene.getRenderId());
  18265. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18266. var subMesh = mesh.subMeshes[subIndex];
  18267. scene._activeIndices += subMesh.indexCount;
  18268. this._renderingManager.dispatch(subMesh);
  18269. }
  18270. }
  18271. }
  18272. }
  18273. if (this.isCube) {
  18274. for (var face = 0; face < 6; face++) {
  18275. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18276. scene.incrementRenderId();
  18277. }
  18278. }
  18279. else {
  18280. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18281. }
  18282. if (this.onAfterUnbind) {
  18283. this.onAfterUnbind();
  18284. }
  18285. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18286. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18287. }
  18288. scene.resetCachedMaterial();
  18289. };
  18290. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18291. var scene = this.getScene();
  18292. var engine = scene.getEngine();
  18293. // Bind
  18294. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18295. if (this.isCube) {
  18296. engine.bindFramebuffer(this._texture, faceIndex);
  18297. }
  18298. else {
  18299. engine.bindFramebuffer(this._texture);
  18300. }
  18301. }
  18302. if (this.onBeforeRender) {
  18303. this.onBeforeRender(faceIndex);
  18304. }
  18305. // Clear
  18306. if (this.onClear) {
  18307. this.onClear(engine);
  18308. }
  18309. else {
  18310. engine.clear(scene.clearColor, true, true);
  18311. }
  18312. if (!this._doNotChangeAspectRatio) {
  18313. scene.updateTransformMatrix(true);
  18314. }
  18315. // Render
  18316. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18317. if (useCameraPostProcess) {
  18318. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18319. }
  18320. if (!this._doNotChangeAspectRatio) {
  18321. scene.updateTransformMatrix(true);
  18322. }
  18323. if (this.onAfterRender) {
  18324. this.onAfterRender(faceIndex);
  18325. }
  18326. // Dump ?
  18327. if (dumpForDebug) {
  18328. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18329. }
  18330. // Unbind
  18331. if (!this.isCube || faceIndex === 5) {
  18332. if (this.isCube) {
  18333. if (faceIndex === 5) {
  18334. engine.generateMipMapsForCubemap(this._texture);
  18335. }
  18336. }
  18337. engine.unBindFramebuffer(this._texture, this.isCube);
  18338. }
  18339. };
  18340. RenderTargetTexture.prototype.clone = function () {
  18341. var textureSize = this.getSize();
  18342. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18343. // Base texture
  18344. newTexture.hasAlpha = this.hasAlpha;
  18345. newTexture.level = this.level;
  18346. // RenderTarget Texture
  18347. newTexture.coordinatesMode = this.coordinatesMode;
  18348. newTexture.renderList = this.renderList.slice(0);
  18349. return newTexture;
  18350. };
  18351. RenderTargetTexture.prototype.serialize = function () {
  18352. if (!this.name) {
  18353. return null;
  18354. }
  18355. var serializationObject = _super.prototype.serialize.call(this);
  18356. serializationObject.renderTargetSize = this.getRenderSize();
  18357. serializationObject.renderList = [];
  18358. for (var index = 0; index < this.renderList.length; index++) {
  18359. serializationObject.renderList.push(this.renderList[index].id);
  18360. }
  18361. return serializationObject;
  18362. };
  18363. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18364. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18365. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18366. return RenderTargetTexture;
  18367. })(BABYLON.Texture);
  18368. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18369. })(BABYLON || (BABYLON = {}));
  18370. var BABYLON;
  18371. (function (BABYLON) {
  18372. var ProceduralTexture = (function (_super) {
  18373. __extends(ProceduralTexture, _super);
  18374. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18375. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18376. if (isCube === void 0) { isCube = false; }
  18377. _super.call(this, null, scene, !generateMipMaps);
  18378. this.isCube = isCube;
  18379. this.isEnabled = true;
  18380. this._currentRefreshId = -1;
  18381. this._refreshRate = 1;
  18382. this._vertexDeclaration = [2];
  18383. this._vertexStrideSize = 2 * 4;
  18384. this._uniforms = new Array();
  18385. this._samplers = new Array();
  18386. this._textures = new Array();
  18387. this._floats = new Array();
  18388. this._floatsArrays = {};
  18389. this._colors3 = new Array();
  18390. this._colors4 = new Array();
  18391. this._vectors2 = new Array();
  18392. this._vectors3 = new Array();
  18393. this._matrices = new Array();
  18394. this._fallbackTextureUsed = false;
  18395. scene._proceduralTextures.push(this);
  18396. this.name = name;
  18397. this.isRenderTarget = true;
  18398. this._size = size;
  18399. this._generateMipMaps = generateMipMaps;
  18400. this.setFragment(fragment);
  18401. this._fallbackTexture = fallbackTexture;
  18402. if (isCube) {
  18403. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18404. this.setFloat("face", 0);
  18405. }
  18406. else {
  18407. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18408. }
  18409. // VBO
  18410. var vertices = [];
  18411. vertices.push(1, 1);
  18412. vertices.push(-1, 1);
  18413. vertices.push(-1, -1);
  18414. vertices.push(1, -1);
  18415. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18416. // Indices
  18417. var indices = [];
  18418. indices.push(0);
  18419. indices.push(1);
  18420. indices.push(2);
  18421. indices.push(0);
  18422. indices.push(2);
  18423. indices.push(3);
  18424. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18425. }
  18426. ProceduralTexture.prototype.reset = function () {
  18427. if (this._effect === undefined) {
  18428. return;
  18429. }
  18430. var engine = this.getScene().getEngine();
  18431. engine._releaseEffect(this._effect);
  18432. };
  18433. ProceduralTexture.prototype.isReady = function () {
  18434. var _this = this;
  18435. var engine = this.getScene().getEngine();
  18436. var shaders;
  18437. if (!this._fragment) {
  18438. return false;
  18439. }
  18440. if (this._fallbackTextureUsed) {
  18441. return true;
  18442. }
  18443. if (this._fragment.fragmentElement !== undefined) {
  18444. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18445. }
  18446. else {
  18447. shaders = { vertex: "procedural", fragment: this._fragment };
  18448. }
  18449. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18450. _this.releaseInternalTexture();
  18451. if (_this._fallbackTexture) {
  18452. _this._texture = _this._fallbackTexture._texture;
  18453. _this._texture.references++;
  18454. }
  18455. _this._fallbackTextureUsed = true;
  18456. });
  18457. return this._effect.isReady();
  18458. };
  18459. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18460. this._currentRefreshId = -1;
  18461. };
  18462. ProceduralTexture.prototype.setFragment = function (fragment) {
  18463. this._fragment = fragment;
  18464. };
  18465. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18466. get: function () {
  18467. return this._refreshRate;
  18468. },
  18469. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18470. set: function (value) {
  18471. this._refreshRate = value;
  18472. this.resetRefreshCounter();
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. ProceduralTexture.prototype._shouldRender = function () {
  18478. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18479. return false;
  18480. }
  18481. if (this._fallbackTextureUsed) {
  18482. return false;
  18483. }
  18484. if (this._currentRefreshId === -1) {
  18485. this._currentRefreshId = 1;
  18486. return true;
  18487. }
  18488. if (this.refreshRate === this._currentRefreshId) {
  18489. this._currentRefreshId = 1;
  18490. return true;
  18491. }
  18492. this._currentRefreshId++;
  18493. return false;
  18494. };
  18495. ProceduralTexture.prototype.getRenderSize = function () {
  18496. return this._size;
  18497. };
  18498. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18499. if (this._fallbackTextureUsed) {
  18500. return;
  18501. }
  18502. this.releaseInternalTexture();
  18503. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18504. };
  18505. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18506. if (this._uniforms.indexOf(uniformName) === -1) {
  18507. this._uniforms.push(uniformName);
  18508. }
  18509. };
  18510. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18511. if (this._samplers.indexOf(name) === -1) {
  18512. this._samplers.push(name);
  18513. }
  18514. this._textures[name] = texture;
  18515. return this;
  18516. };
  18517. ProceduralTexture.prototype.setFloat = function (name, value) {
  18518. this._checkUniform(name);
  18519. this._floats[name] = value;
  18520. return this;
  18521. };
  18522. ProceduralTexture.prototype.setFloats = function (name, value) {
  18523. this._checkUniform(name);
  18524. this._floatsArrays[name] = value;
  18525. return this;
  18526. };
  18527. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18528. this._checkUniform(name);
  18529. this._colors3[name] = value;
  18530. return this;
  18531. };
  18532. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18533. this._checkUniform(name);
  18534. this._colors4[name] = value;
  18535. return this;
  18536. };
  18537. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18538. this._checkUniform(name);
  18539. this._vectors2[name] = value;
  18540. return this;
  18541. };
  18542. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18543. this._checkUniform(name);
  18544. this._vectors3[name] = value;
  18545. return this;
  18546. };
  18547. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18548. this._checkUniform(name);
  18549. this._matrices[name] = value;
  18550. return this;
  18551. };
  18552. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18553. var scene = this.getScene();
  18554. var engine = scene.getEngine();
  18555. // Render
  18556. engine.enableEffect(this._effect);
  18557. engine.setState(false);
  18558. // Texture
  18559. for (var name in this._textures) {
  18560. this._effect.setTexture(name, this._textures[name]);
  18561. }
  18562. // Float
  18563. for (name in this._floats) {
  18564. this._effect.setFloat(name, this._floats[name]);
  18565. }
  18566. // Floats
  18567. for (name in this._floatsArrays) {
  18568. this._effect.setArray(name, this._floatsArrays[name]);
  18569. }
  18570. // Color3
  18571. for (name in this._colors3) {
  18572. this._effect.setColor3(name, this._colors3[name]);
  18573. }
  18574. // Color4
  18575. for (name in this._colors4) {
  18576. var color = this._colors4[name];
  18577. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18578. }
  18579. // Vector2
  18580. for (name in this._vectors2) {
  18581. this._effect.setVector2(name, this._vectors2[name]);
  18582. }
  18583. // Vector3
  18584. for (name in this._vectors3) {
  18585. this._effect.setVector3(name, this._vectors3[name]);
  18586. }
  18587. // Matrix
  18588. for (name in this._matrices) {
  18589. this._effect.setMatrix(name, this._matrices[name]);
  18590. }
  18591. // VBOs
  18592. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18593. if (this.isCube) {
  18594. for (var face = 0; face < 6; face++) {
  18595. engine.bindFramebuffer(this._texture, face);
  18596. this._effect.setFloat("face", face);
  18597. // Clear
  18598. engine.clear(scene.clearColor, true, true);
  18599. // Draw order
  18600. engine.draw(true, 0, 6);
  18601. // Mipmaps
  18602. if (face === 5) {
  18603. engine.generateMipMapsForCubemap(this._texture);
  18604. }
  18605. }
  18606. }
  18607. else {
  18608. engine.bindFramebuffer(this._texture);
  18609. // Clear
  18610. engine.clear(scene.clearColor, true, true);
  18611. // Draw order
  18612. engine.draw(true, 0, 6);
  18613. }
  18614. // Unbind
  18615. engine.unBindFramebuffer(this._texture, this.isCube);
  18616. if (this.onGenerated) {
  18617. this.onGenerated();
  18618. }
  18619. };
  18620. ProceduralTexture.prototype.clone = function () {
  18621. var textureSize = this.getSize();
  18622. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18623. // Base texture
  18624. newTexture.hasAlpha = this.hasAlpha;
  18625. newTexture.level = this.level;
  18626. // RenderTarget Texture
  18627. newTexture.coordinatesMode = this.coordinatesMode;
  18628. return newTexture;
  18629. };
  18630. ProceduralTexture.prototype.dispose = function () {
  18631. var index = this.getScene()._proceduralTextures.indexOf(this);
  18632. if (index >= 0) {
  18633. this.getScene()._proceduralTextures.splice(index, 1);
  18634. }
  18635. _super.prototype.dispose.call(this);
  18636. };
  18637. return ProceduralTexture;
  18638. })(BABYLON.Texture);
  18639. BABYLON.ProceduralTexture = ProceduralTexture;
  18640. })(BABYLON || (BABYLON = {}));
  18641. var BABYLON;
  18642. (function (BABYLON) {
  18643. var MirrorTexture = (function (_super) {
  18644. __extends(MirrorTexture, _super);
  18645. function MirrorTexture(name, size, scene, generateMipMaps) {
  18646. var _this = this;
  18647. _super.call(this, name, size, scene, generateMipMaps, true);
  18648. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18649. this._transformMatrix = BABYLON.Matrix.Zero();
  18650. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18651. this.onBeforeRender = function () {
  18652. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18653. _this._savedViewMatrix = scene.getViewMatrix();
  18654. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18655. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18656. scene.clipPlane = _this.mirrorPlane;
  18657. scene.getEngine().cullBackFaces = false;
  18658. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18659. };
  18660. this.onAfterRender = function () {
  18661. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18662. scene.getEngine().cullBackFaces = true;
  18663. scene._mirroredCameraPosition = null;
  18664. delete scene.clipPlane;
  18665. };
  18666. }
  18667. MirrorTexture.prototype.clone = function () {
  18668. var textureSize = this.getSize();
  18669. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18670. // Base texture
  18671. newTexture.hasAlpha = this.hasAlpha;
  18672. newTexture.level = this.level;
  18673. // Mirror Texture
  18674. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18675. newTexture.renderList = this.renderList.slice(0);
  18676. return newTexture;
  18677. };
  18678. MirrorTexture.prototype.serialize = function () {
  18679. if (!this.name) {
  18680. return null;
  18681. }
  18682. var serializationObject = _super.prototype.serialize.call(this);
  18683. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18684. return serializationObject;
  18685. };
  18686. return MirrorTexture;
  18687. })(BABYLON.RenderTargetTexture);
  18688. BABYLON.MirrorTexture = MirrorTexture;
  18689. })(BABYLON || (BABYLON = {}));
  18690. var BABYLON;
  18691. (function (BABYLON) {
  18692. /**
  18693. * Creates a refraction texture used by refraction channel of the standard material.
  18694. * @param name the texture name
  18695. * @param size size of the underlying texture
  18696. * @param scene root scene
  18697. */
  18698. var RefractionTexture = (function (_super) {
  18699. __extends(RefractionTexture, _super);
  18700. function RefractionTexture(name, size, scene, generateMipMaps) {
  18701. var _this = this;
  18702. _super.call(this, name, size, scene, generateMipMaps, true);
  18703. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18704. this.depth = 2.0;
  18705. this.onBeforeRender = function () {
  18706. scene.clipPlane = _this.refractionPlane;
  18707. };
  18708. this.onAfterRender = function () {
  18709. delete scene.clipPlane;
  18710. };
  18711. }
  18712. RefractionTexture.prototype.clone = function () {
  18713. var textureSize = this.getSize();
  18714. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18715. // Base texture
  18716. newTexture.hasAlpha = this.hasAlpha;
  18717. newTexture.level = this.level;
  18718. // Refraction Texture
  18719. newTexture.refractionPlane = this.refractionPlane.clone();
  18720. newTexture.renderList = this.renderList.slice(0);
  18721. newTexture.depth = this.depth;
  18722. return newTexture;
  18723. };
  18724. RefractionTexture.prototype.serialize = function () {
  18725. if (!this.name) {
  18726. return null;
  18727. }
  18728. var serializationObject = _super.prototype.serialize.call(this);
  18729. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18730. serializationObject.depth = this.depth;
  18731. return serializationObject;
  18732. };
  18733. return RefractionTexture;
  18734. })(BABYLON.RenderTargetTexture);
  18735. BABYLON.RefractionTexture = RefractionTexture;
  18736. })(BABYLON || (BABYLON = {}));
  18737. var BABYLON;
  18738. (function (BABYLON) {
  18739. var DynamicTexture = (function (_super) {
  18740. __extends(DynamicTexture, _super);
  18741. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18743. _super.call(this, null, scene, !generateMipMaps);
  18744. this.name = name;
  18745. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18746. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18747. this._generateMipMaps = generateMipMaps;
  18748. if (options.getContext) {
  18749. this._canvas = options;
  18750. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18751. }
  18752. else {
  18753. this._canvas = document.createElement("canvas");
  18754. if (options.width) {
  18755. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18756. }
  18757. else {
  18758. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18759. }
  18760. }
  18761. var textureSize = this.getSize();
  18762. this._canvas.width = textureSize.width;
  18763. this._canvas.height = textureSize.height;
  18764. this._context = this._canvas.getContext("2d");
  18765. }
  18766. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18767. get: function () {
  18768. return true;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. DynamicTexture.prototype.scale = function (ratio) {
  18774. var textureSize = this.getSize();
  18775. textureSize.width *= ratio;
  18776. textureSize.height *= ratio;
  18777. this._canvas.width = textureSize.width;
  18778. this._canvas.height = textureSize.height;
  18779. this.releaseInternalTexture();
  18780. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18781. };
  18782. DynamicTexture.prototype.getContext = function () {
  18783. return this._context;
  18784. };
  18785. DynamicTexture.prototype.clear = function () {
  18786. var size = this.getSize();
  18787. this._context.fillRect(0, 0, size.width, size.height);
  18788. };
  18789. DynamicTexture.prototype.update = function (invertY) {
  18790. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18791. };
  18792. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18793. if (update === void 0) { update = true; }
  18794. var size = this.getSize();
  18795. if (clearColor) {
  18796. this._context.fillStyle = clearColor;
  18797. this._context.fillRect(0, 0, size.width, size.height);
  18798. }
  18799. this._context.font = font;
  18800. if (x === null) {
  18801. var textSize = this._context.measureText(text);
  18802. x = (size.width - textSize.width) / 2;
  18803. }
  18804. this._context.fillStyle = color;
  18805. this._context.fillText(text, x, y);
  18806. if (update) {
  18807. this.update(invertY);
  18808. }
  18809. };
  18810. DynamicTexture.prototype.clone = function () {
  18811. var textureSize = this.getSize();
  18812. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18813. // Base texture
  18814. newTexture.hasAlpha = this.hasAlpha;
  18815. newTexture.level = this.level;
  18816. // Dynamic Texture
  18817. newTexture.wrapU = this.wrapU;
  18818. newTexture.wrapV = this.wrapV;
  18819. return newTexture;
  18820. };
  18821. return DynamicTexture;
  18822. })(BABYLON.Texture);
  18823. BABYLON.DynamicTexture = DynamicTexture;
  18824. })(BABYLON || (BABYLON = {}));
  18825. var BABYLON;
  18826. (function (BABYLON) {
  18827. var VideoTexture = (function (_super) {
  18828. __extends(VideoTexture, _super);
  18829. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18830. var _this = this;
  18831. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18832. if (invertY === void 0) { invertY = false; }
  18833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18834. _super.call(this, null, scene, !generateMipMaps, invertY);
  18835. this._autoLaunch = true;
  18836. this.name = name;
  18837. this.video = document.createElement("video");
  18838. this.video.autoplay = false;
  18839. this.video.loop = true;
  18840. this.video.addEventListener("canplaythrough", function () {
  18841. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18842. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18843. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18844. }
  18845. else {
  18846. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18847. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18848. generateMipMaps = false;
  18849. }
  18850. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18851. _this._texture.isReady = true;
  18852. });
  18853. urls.forEach(function (url) {
  18854. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18855. var source = document.createElement("source");
  18856. source.src = url;
  18857. _this.video.appendChild(source);
  18858. });
  18859. this._lastUpdate = BABYLON.Tools.Now;
  18860. }
  18861. VideoTexture.prototype.update = function () {
  18862. if (this._autoLaunch) {
  18863. this._autoLaunch = false;
  18864. this.video.play();
  18865. }
  18866. var now = BABYLON.Tools.Now;
  18867. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18868. return false;
  18869. }
  18870. this._lastUpdate = now;
  18871. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18872. return true;
  18873. };
  18874. return VideoTexture;
  18875. })(BABYLON.Texture);
  18876. BABYLON.VideoTexture = VideoTexture;
  18877. })(BABYLON || (BABYLON = {}));
  18878. var BABYLON;
  18879. (function (BABYLON) {
  18880. var CustomProceduralTexture = (function (_super) {
  18881. __extends(CustomProceduralTexture, _super);
  18882. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18883. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18884. this._animate = true;
  18885. this._time = 0;
  18886. this._texturePath = texturePath;
  18887. //Try to load json
  18888. this.loadJson(texturePath);
  18889. this.refreshRate = 1;
  18890. }
  18891. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18892. var _this = this;
  18893. var that = this;
  18894. function noConfigFile() {
  18895. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18896. try {
  18897. that.setFragment(that._texturePath);
  18898. }
  18899. catch (ex) {
  18900. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18901. }
  18902. }
  18903. var configFileUrl = jsonUrl + "/config.json";
  18904. var xhr = new XMLHttpRequest();
  18905. xhr.open("GET", configFileUrl, true);
  18906. xhr.addEventListener("load", function () {
  18907. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18908. try {
  18909. _this._config = JSON.parse(xhr.response);
  18910. _this.updateShaderUniforms();
  18911. _this.updateTextures();
  18912. _this.setFragment(_this._texturePath + "/custom");
  18913. _this._animate = _this._config.animate;
  18914. _this.refreshRate = _this._config.refreshrate;
  18915. }
  18916. catch (ex) {
  18917. noConfigFile();
  18918. }
  18919. }
  18920. else {
  18921. noConfigFile();
  18922. }
  18923. }, false);
  18924. xhr.addEventListener("error", function () {
  18925. noConfigFile();
  18926. }, false);
  18927. try {
  18928. xhr.send();
  18929. }
  18930. catch (ex) {
  18931. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18932. }
  18933. };
  18934. CustomProceduralTexture.prototype.isReady = function () {
  18935. if (!_super.prototype.isReady.call(this)) {
  18936. return false;
  18937. }
  18938. for (var name in this._textures) {
  18939. var texture = this._textures[name];
  18940. if (!texture.isReady()) {
  18941. return false;
  18942. }
  18943. }
  18944. return true;
  18945. };
  18946. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18947. if (this._animate) {
  18948. this._time += this.getScene().getAnimationRatio() * 0.03;
  18949. this.updateShaderUniforms();
  18950. }
  18951. _super.prototype.render.call(this, useCameraPostProcess);
  18952. };
  18953. CustomProceduralTexture.prototype.updateTextures = function () {
  18954. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18955. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18956. }
  18957. };
  18958. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18959. if (this._config) {
  18960. for (var j = 0; j < this._config.uniforms.length; j++) {
  18961. var uniform = this._config.uniforms[j];
  18962. switch (uniform.type) {
  18963. case "float":
  18964. this.setFloat(uniform.name, uniform.value);
  18965. break;
  18966. case "color3":
  18967. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18968. break;
  18969. case "color4":
  18970. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18971. break;
  18972. case "vector2":
  18973. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18974. break;
  18975. case "vector3":
  18976. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18977. break;
  18978. }
  18979. }
  18980. }
  18981. this.setFloat("time", this._time);
  18982. };
  18983. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18984. get: function () {
  18985. return this._animate;
  18986. },
  18987. set: function (value) {
  18988. this._animate = value;
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. return CustomProceduralTexture;
  18994. })(BABYLON.ProceduralTexture);
  18995. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18996. })(BABYLON || (BABYLON = {}));
  18997. var BABYLON;
  18998. (function (BABYLON) {
  18999. var EffectFallbacks = (function () {
  19000. function EffectFallbacks() {
  19001. this._defines = {};
  19002. this._currentRank = 32;
  19003. this._maxRank = -1;
  19004. }
  19005. EffectFallbacks.prototype.addFallback = function (rank, define) {
  19006. if (!this._defines[rank]) {
  19007. if (rank < this._currentRank) {
  19008. this._currentRank = rank;
  19009. }
  19010. if (rank > this._maxRank) {
  19011. this._maxRank = rank;
  19012. }
  19013. this._defines[rank] = new Array();
  19014. }
  19015. this._defines[rank].push(define);
  19016. };
  19017. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19018. this._meshRank = rank;
  19019. this._mesh = mesh;
  19020. if (rank > this._maxRank) {
  19021. this._maxRank = rank;
  19022. }
  19023. };
  19024. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19025. get: function () {
  19026. return this._currentRank <= this._maxRank;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19032. var currentFallbacks = this._defines[this._currentRank];
  19033. for (var index = 0; index < currentFallbacks.length; index++) {
  19034. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19035. }
  19036. if (this._mesh && this._currentRank === this._meshRank) {
  19037. this._mesh.computeBonesUsingShaders = false;
  19038. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19039. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19040. }
  19041. this._currentRank++;
  19042. return currentDefines;
  19043. };
  19044. return EffectFallbacks;
  19045. })();
  19046. BABYLON.EffectFallbacks = EffectFallbacks;
  19047. var Effect = (function () {
  19048. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19049. var _this = this;
  19050. this._isReady = false;
  19051. this._compilationError = "";
  19052. this._valueCache = [];
  19053. this._engine = engine;
  19054. this.name = baseName;
  19055. this.defines = defines;
  19056. this._uniformsNames = uniformsNames.concat(samplers);
  19057. this._samplers = samplers;
  19058. this._attributesNames = attributesNames;
  19059. this.onError = onError;
  19060. this.onCompiled = onCompiled;
  19061. var vertexSource;
  19062. var fragmentSource;
  19063. if (baseName.vertexElement) {
  19064. vertexSource = document.getElementById(baseName.vertexElement);
  19065. if (!vertexSource) {
  19066. vertexSource = baseName.vertexElement;
  19067. }
  19068. }
  19069. else {
  19070. vertexSource = baseName.vertex || baseName;
  19071. }
  19072. if (baseName.fragmentElement) {
  19073. fragmentSource = document.getElementById(baseName.fragmentElement);
  19074. if (!fragmentSource) {
  19075. fragmentSource = baseName.fragmentElement;
  19076. }
  19077. }
  19078. else {
  19079. fragmentSource = baseName.fragment || baseName;
  19080. }
  19081. this._loadVertexShader(vertexSource, function (vertexCode) {
  19082. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19083. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19084. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19085. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19086. });
  19087. });
  19088. });
  19089. });
  19090. }
  19091. // Properties
  19092. Effect.prototype.isReady = function () {
  19093. return this._isReady;
  19094. };
  19095. Effect.prototype.getProgram = function () {
  19096. return this._program;
  19097. };
  19098. Effect.prototype.getAttributesNames = function () {
  19099. return this._attributesNames;
  19100. };
  19101. Effect.prototype.getAttributeLocation = function (index) {
  19102. return this._attributes[index];
  19103. };
  19104. Effect.prototype.getAttributeLocationByName = function (name) {
  19105. var index = this._attributesNames.indexOf(name);
  19106. return this._attributes[index];
  19107. };
  19108. Effect.prototype.getAttributesCount = function () {
  19109. return this._attributes.length;
  19110. };
  19111. Effect.prototype.getUniformIndex = function (uniformName) {
  19112. return this._uniformsNames.indexOf(uniformName);
  19113. };
  19114. Effect.prototype.getUniform = function (uniformName) {
  19115. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19116. };
  19117. Effect.prototype.getSamplers = function () {
  19118. return this._samplers;
  19119. };
  19120. Effect.prototype.getCompilationError = function () {
  19121. return this._compilationError;
  19122. };
  19123. // Methods
  19124. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19125. // DOM element ?
  19126. if (vertex instanceof HTMLElement) {
  19127. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19128. callback(vertexCode);
  19129. return;
  19130. }
  19131. // Is in local store ?
  19132. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19133. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19134. return;
  19135. }
  19136. var vertexShaderUrl;
  19137. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19138. vertexShaderUrl = vertex;
  19139. }
  19140. else {
  19141. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19142. }
  19143. // Vertex shader
  19144. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19145. };
  19146. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19147. // DOM element ?
  19148. if (fragment instanceof HTMLElement) {
  19149. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19150. callback(fragmentCode);
  19151. return;
  19152. }
  19153. // Is in local store ?
  19154. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19155. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19156. return;
  19157. }
  19158. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19159. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19160. return;
  19161. }
  19162. var fragmentShaderUrl;
  19163. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19164. fragmentShaderUrl = fragment;
  19165. }
  19166. else {
  19167. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19168. }
  19169. // Fragment shader
  19170. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19171. };
  19172. Effect.prototype._dumpShadersName = function () {
  19173. if (this.name.vertexElement) {
  19174. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19175. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19176. }
  19177. else if (this.name.vertex) {
  19178. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19179. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19180. }
  19181. else {
  19182. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19183. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19184. }
  19185. };
  19186. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19187. var _this = this;
  19188. var regex = /#include<(.+)>(\((.*)\))*/g;
  19189. var match = regex.exec(sourceCode);
  19190. var returnValue = new String(sourceCode);
  19191. while (match != null) {
  19192. var includeFile = match[1];
  19193. if (Effect.IncludesShadersStore[includeFile]) {
  19194. // Substitution
  19195. var includeContent = Effect.IncludesShadersStore[includeFile];
  19196. if (match[2]) {
  19197. var splits = match[2].substr(1, match[2].length - 2).split(",");
  19198. for (var index = 0; index < splits.length; index += 2) {
  19199. var source = new RegExp(splits[index], "g");
  19200. var dest = splits[index + 1];
  19201. includeContent = includeContent.replace(source, dest);
  19202. }
  19203. }
  19204. // Replace
  19205. returnValue = returnValue.replace(match[0], includeContent);
  19206. }
  19207. else {
  19208. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19209. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19210. Effect.IncludesShadersStore[includeFile] = fileContent;
  19211. _this._processIncludes(returnValue, callback);
  19212. });
  19213. return;
  19214. }
  19215. match = regex.exec(sourceCode);
  19216. }
  19217. callback(returnValue);
  19218. };
  19219. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19220. try {
  19221. var engine = this._engine;
  19222. // Precision
  19223. if (!engine.getCaps().highPrecisionShaderSupported) {
  19224. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19225. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19226. }
  19227. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19228. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19229. this._attributes = engine.getAttributes(this._program, attributesNames);
  19230. for (var index = 0; index < this._samplers.length; index++) {
  19231. var sampler = this.getUniform(this._samplers[index]);
  19232. if (sampler == null) {
  19233. this._samplers.splice(index, 1);
  19234. index--;
  19235. }
  19236. }
  19237. engine.bindSamplers(this);
  19238. this._isReady = true;
  19239. if (this.onCompiled) {
  19240. this.onCompiled(this);
  19241. }
  19242. }
  19243. catch (e) {
  19244. // Is it a problem with precision?
  19245. if (e.message.indexOf("highp") !== -1) {
  19246. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19247. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19248. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19249. return;
  19250. }
  19251. // Let's go through fallbacks then
  19252. if (fallbacks && fallbacks.isMoreFallbacks) {
  19253. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19254. this._dumpShadersName();
  19255. defines = fallbacks.reduce(defines);
  19256. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19257. }
  19258. else {
  19259. BABYLON.Tools.Error("Unable to compile effect: ");
  19260. this._dumpShadersName();
  19261. BABYLON.Tools.Error("Defines: " + defines);
  19262. BABYLON.Tools.Error("Error: " + e.message);
  19263. this._compilationError = e.message;
  19264. if (this.onError) {
  19265. this.onError(this, this._compilationError);
  19266. }
  19267. }
  19268. }
  19269. };
  19270. Object.defineProperty(Effect.prototype, "isSupported", {
  19271. get: function () {
  19272. return this._compilationError === "";
  19273. },
  19274. enumerable: true,
  19275. configurable: true
  19276. });
  19277. Effect.prototype._bindTexture = function (channel, texture) {
  19278. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19279. };
  19280. Effect.prototype.setTexture = function (channel, texture) {
  19281. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19282. };
  19283. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19284. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19285. };
  19286. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19287. if (!this._valueCache[uniformName]) {
  19288. this._valueCache[uniformName] = new BABYLON.Matrix();
  19289. }
  19290. for (var index = 0; index < 16; index++) {
  19291. this._valueCache[uniformName].m[index] = matrix.m[index];
  19292. }
  19293. };
  19294. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19295. if (!this._valueCache[uniformName]) {
  19296. this._valueCache[uniformName] = [x, y];
  19297. return;
  19298. }
  19299. this._valueCache[uniformName][0] = x;
  19300. this._valueCache[uniformName][1] = y;
  19301. };
  19302. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19303. if (!this._valueCache[uniformName]) {
  19304. this._valueCache[uniformName] = [x, y, z];
  19305. return;
  19306. }
  19307. this._valueCache[uniformName][0] = x;
  19308. this._valueCache[uniformName][1] = y;
  19309. this._valueCache[uniformName][2] = z;
  19310. };
  19311. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19312. if (!this._valueCache[uniformName]) {
  19313. this._valueCache[uniformName] = [x, y, z, w];
  19314. return;
  19315. }
  19316. this._valueCache[uniformName][0] = x;
  19317. this._valueCache[uniformName][1] = y;
  19318. this._valueCache[uniformName][2] = z;
  19319. this._valueCache[uniformName][3] = w;
  19320. };
  19321. Effect.prototype.setArray = function (uniformName, array) {
  19322. this._engine.setArray(this.getUniform(uniformName), array);
  19323. return this;
  19324. };
  19325. Effect.prototype.setArray2 = function (uniformName, array) {
  19326. this._engine.setArray2(this.getUniform(uniformName), array);
  19327. return this;
  19328. };
  19329. Effect.prototype.setArray3 = function (uniformName, array) {
  19330. this._engine.setArray3(this.getUniform(uniformName), array);
  19331. return this;
  19332. };
  19333. Effect.prototype.setArray4 = function (uniformName, array) {
  19334. this._engine.setArray4(this.getUniform(uniformName), array);
  19335. return this;
  19336. };
  19337. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19338. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19339. return this;
  19340. };
  19341. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19342. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19343. // return this;
  19344. // this._cacheMatrix(uniformName, matrix);
  19345. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19346. return this;
  19347. };
  19348. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19349. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19350. return this;
  19351. };
  19352. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19353. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19354. return this;
  19355. };
  19356. Effect.prototype.setFloat = function (uniformName, value) {
  19357. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19358. return this;
  19359. this._valueCache[uniformName] = value;
  19360. this._engine.setFloat(this.getUniform(uniformName), value);
  19361. return this;
  19362. };
  19363. Effect.prototype.setBool = function (uniformName, bool) {
  19364. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19365. return this;
  19366. this._valueCache[uniformName] = bool;
  19367. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19368. return this;
  19369. };
  19370. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19371. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19372. return this;
  19373. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19374. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19375. return this;
  19376. };
  19377. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19378. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19379. return this;
  19380. this._cacheFloat2(uniformName, x, y);
  19381. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19382. return this;
  19383. };
  19384. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19385. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19386. return this;
  19387. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19388. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19389. return this;
  19390. };
  19391. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19392. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19393. return this;
  19394. this._cacheFloat3(uniformName, x, y, z);
  19395. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19396. return this;
  19397. };
  19398. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19399. 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)
  19400. return this;
  19401. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19402. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19403. return this;
  19404. };
  19405. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19406. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19407. return this;
  19408. this._cacheFloat4(uniformName, x, y, z, w);
  19409. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19410. return this;
  19411. };
  19412. Effect.prototype.setColor3 = function (uniformName, color3) {
  19413. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19414. return this;
  19415. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19416. this._engine.setColor3(this.getUniform(uniformName), color3);
  19417. return this;
  19418. };
  19419. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19420. 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)
  19421. return this;
  19422. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19423. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19424. return this;
  19425. };
  19426. // Statics
  19427. Effect.ShadersStore = {};
  19428. Effect.IncludesShadersStore = {};
  19429. return Effect;
  19430. })();
  19431. BABYLON.Effect = Effect;
  19432. })(BABYLON || (BABYLON = {}));
  19433. var BABYLON;
  19434. (function (BABYLON) {
  19435. var maxSimultaneousLights = 4;
  19436. var MaterialHelper = (function () {
  19437. function MaterialHelper() {
  19438. }
  19439. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19440. var lightIndex = 0;
  19441. var needNormals = false;
  19442. for (var index = 0; index < scene.lights.length; index++) {
  19443. var light = scene.lights[index];
  19444. if (!light.isEnabled()) {
  19445. continue;
  19446. }
  19447. // Excluded check
  19448. if (light._excludedMeshesIds.length > 0) {
  19449. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19450. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19451. if (excludedMesh) {
  19452. light.excludedMeshes.push(excludedMesh);
  19453. }
  19454. }
  19455. light._excludedMeshesIds = [];
  19456. }
  19457. // Included check
  19458. if (light._includedOnlyMeshesIds.length > 0) {
  19459. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19460. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19461. if (includedOnlyMesh) {
  19462. light.includedOnlyMeshes.push(includedOnlyMesh);
  19463. }
  19464. }
  19465. light._includedOnlyMeshesIds = [];
  19466. }
  19467. if (!light.canAffectMesh(mesh)) {
  19468. continue;
  19469. }
  19470. needNormals = true;
  19471. defines["LIGHT" + lightIndex] = true;
  19472. var type;
  19473. if (light instanceof BABYLON.SpotLight) {
  19474. type = "SPOTLIGHT" + lightIndex;
  19475. }
  19476. else if (light instanceof BABYLON.HemisphericLight) {
  19477. type = "HEMILIGHT" + lightIndex;
  19478. }
  19479. else if (light instanceof BABYLON.PointLight) {
  19480. type = "POINTLIGHT" + lightIndex;
  19481. }
  19482. else {
  19483. type = "DIRLIGHT" + lightIndex;
  19484. }
  19485. defines[type] = true;
  19486. // Specular
  19487. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19488. defines["SPECULARTERM"] = true;
  19489. }
  19490. // Shadows
  19491. if (scene.shadowsEnabled) {
  19492. var shadowGenerator = light.getShadowGenerator();
  19493. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19494. defines["SHADOW" + lightIndex] = true;
  19495. defines["SHADOWS"] = true;
  19496. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19497. defines["SHADOWVSM" + lightIndex] = true;
  19498. }
  19499. if (shadowGenerator.usePoissonSampling) {
  19500. defines["SHADOWPCF" + lightIndex] = true;
  19501. }
  19502. }
  19503. }
  19504. lightIndex++;
  19505. if (lightIndex === maxSimultaneousLights)
  19506. break;
  19507. }
  19508. return needNormals;
  19509. };
  19510. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19511. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19512. if (!defines["LIGHT" + lightIndex]) {
  19513. continue;
  19514. }
  19515. if (lightIndex > 0) {
  19516. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19517. }
  19518. if (defines["SHADOW" + lightIndex]) {
  19519. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19520. }
  19521. if (defines["SHADOWPCF" + lightIndex]) {
  19522. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19523. }
  19524. if (defines["SHADOWVSM" + lightIndex]) {
  19525. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19526. }
  19527. }
  19528. };
  19529. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19530. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19531. fallbacks.addCPUSkinningFallback(0, mesh);
  19532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19534. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19537. }
  19538. }
  19539. };
  19540. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19541. if (defines["INSTANCES"]) {
  19542. attribs.push("world0");
  19543. attribs.push("world1");
  19544. attribs.push("world2");
  19545. attribs.push("world3");
  19546. }
  19547. };
  19548. // Bindings
  19549. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19550. var shadowGenerator = light.getShadowGenerator();
  19551. if (mesh.receiveShadows && shadowGenerator) {
  19552. if (!light.needCube()) {
  19553. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19554. }
  19555. else {
  19556. if (!depthValuesAlreadySet) {
  19557. depthValuesAlreadySet = true;
  19558. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19559. }
  19560. }
  19561. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19562. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19563. }
  19564. return depthValuesAlreadySet;
  19565. };
  19566. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19567. if (light instanceof BABYLON.PointLight) {
  19568. // Point Light
  19569. light.transferToEffect(effect, "vLightData" + lightIndex);
  19570. }
  19571. else if (light instanceof BABYLON.DirectionalLight) {
  19572. // Directional Light
  19573. light.transferToEffect(effect, "vLightData" + lightIndex);
  19574. }
  19575. else if (light instanceof BABYLON.SpotLight) {
  19576. // Spot Light
  19577. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19578. }
  19579. else if (light instanceof BABYLON.HemisphericLight) {
  19580. // Hemispheric Light
  19581. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19582. }
  19583. };
  19584. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19585. var lightIndex = 0;
  19586. var depthValuesAlreadySet = false;
  19587. for (var index = 0; index < scene.lights.length; index++) {
  19588. var light = scene.lights[index];
  19589. if (!light.isEnabled()) {
  19590. continue;
  19591. }
  19592. if (!light.canAffectMesh(mesh)) {
  19593. continue;
  19594. }
  19595. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19596. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19597. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19598. if (defines["SPECULARTERM"]) {
  19599. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19600. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19601. }
  19602. // Shadows
  19603. if (scene.shadowsEnabled) {
  19604. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19605. }
  19606. lightIndex++;
  19607. if (lightIndex === maxSimultaneousLights)
  19608. break;
  19609. }
  19610. };
  19611. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19612. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19613. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19614. effect.setColor3("vFogColor", scene.fogColor);
  19615. }
  19616. };
  19617. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19618. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19619. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19620. }
  19621. };
  19622. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19623. if (defines["LOGARITHMICDEPTH"]) {
  19624. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19625. }
  19626. };
  19627. MaterialHelper.BindClipPlane = function (effect, scene) {
  19628. if (scene.clipPlane) {
  19629. var clipPlane = scene.clipPlane;
  19630. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19631. }
  19632. };
  19633. return MaterialHelper;
  19634. })();
  19635. BABYLON.MaterialHelper = MaterialHelper;
  19636. })(BABYLON || (BABYLON = {}));
  19637. var BABYLON;
  19638. (function (BABYLON) {
  19639. var FresnelParameters = (function () {
  19640. function FresnelParameters() {
  19641. this.isEnabled = true;
  19642. this.leftColor = BABYLON.Color3.White();
  19643. this.rightColor = BABYLON.Color3.Black();
  19644. this.bias = 0;
  19645. this.power = 1;
  19646. }
  19647. FresnelParameters.prototype.clone = function () {
  19648. var newFresnelParameters = new FresnelParameters();
  19649. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19650. return new FresnelParameters;
  19651. };
  19652. FresnelParameters.prototype.serialize = function () {
  19653. var serializationObject = {};
  19654. serializationObject.isEnabled = this.isEnabled;
  19655. serializationObject.leftColor = this.leftColor;
  19656. serializationObject.rightColor = this.rightColor;
  19657. serializationObject.bias = this.bias;
  19658. serializationObject.power = this.power;
  19659. return serializationObject;
  19660. };
  19661. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19662. var fresnelParameters = new FresnelParameters();
  19663. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19664. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19665. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19666. fresnelParameters.bias = parsedFresnelParameters.bias;
  19667. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19668. return fresnelParameters;
  19669. };
  19670. return FresnelParameters;
  19671. })();
  19672. BABYLON.FresnelParameters = FresnelParameters;
  19673. })(BABYLON || (BABYLON = {}));
  19674. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19675. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19676. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19677. 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;
  19678. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19679. };
  19680. var BABYLON;
  19681. (function (BABYLON) {
  19682. var MaterialDefines = (function () {
  19683. function MaterialDefines() {
  19684. }
  19685. MaterialDefines.prototype.isEqual = function (other) {
  19686. for (var index = 0; index < this._keys.length; index++) {
  19687. var prop = this._keys[index];
  19688. if (this[prop] !== other[prop]) {
  19689. return false;
  19690. }
  19691. }
  19692. return true;
  19693. };
  19694. MaterialDefines.prototype.cloneTo = function (other) {
  19695. for (var index = 0; index < this._keys.length; index++) {
  19696. var prop = this._keys[index];
  19697. other[prop] = this[prop];
  19698. }
  19699. };
  19700. MaterialDefines.prototype.reset = function () {
  19701. for (var index = 0; index < this._keys.length; index++) {
  19702. var prop = this._keys[index];
  19703. if (typeof (this[prop]) === "number") {
  19704. this[prop] = 0;
  19705. }
  19706. else {
  19707. this[prop] = false;
  19708. }
  19709. }
  19710. };
  19711. MaterialDefines.prototype.toString = function () {
  19712. var result = "";
  19713. for (var index = 0; index < this._keys.length; index++) {
  19714. var prop = this._keys[index];
  19715. if (typeof (this[prop]) === "number") {
  19716. result += "#define " + prop + " " + this[prop] + "\n";
  19717. }
  19718. else if (this[prop]) {
  19719. result += "#define " + prop + "\n";
  19720. }
  19721. }
  19722. return result;
  19723. };
  19724. return MaterialDefines;
  19725. })();
  19726. BABYLON.MaterialDefines = MaterialDefines;
  19727. var Material = (function () {
  19728. function Material(name, scene, doNotAdd) {
  19729. this.name = name;
  19730. this.checkReadyOnEveryCall = false;
  19731. this.checkReadyOnlyOnce = false;
  19732. this.state = "";
  19733. this.alpha = 1.0;
  19734. this.backFaceCulling = true;
  19735. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19736. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19737. this.disableDepthWrite = false;
  19738. this.fogEnabled = true;
  19739. this.pointSize = 1.0;
  19740. this.zOffset = 0;
  19741. this._wasPreviouslyReady = false;
  19742. this._fillMode = Material.TriangleFillMode;
  19743. this.id = name;
  19744. this._scene = scene;
  19745. if (!doNotAdd) {
  19746. scene.materials.push(this);
  19747. }
  19748. }
  19749. Object.defineProperty(Material, "TriangleFillMode", {
  19750. get: function () {
  19751. return Material._TriangleFillMode;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(Material, "WireFrameFillMode", {
  19757. get: function () {
  19758. return Material._WireFrameFillMode;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Material, "PointFillMode", {
  19764. get: function () {
  19765. return Material._PointFillMode;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19771. get: function () {
  19772. return Material._ClockWiseSideOrientation;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19778. get: function () {
  19779. return Material._CounterClockWiseSideOrientation;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(Material.prototype, "wireframe", {
  19785. get: function () {
  19786. return this._fillMode === Material.WireFrameFillMode;
  19787. },
  19788. set: function (value) {
  19789. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Material.prototype, "pointsCloud", {
  19795. get: function () {
  19796. return this._fillMode === Material.PointFillMode;
  19797. },
  19798. set: function (value) {
  19799. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Material.prototype, "fillMode", {
  19805. get: function () {
  19806. return this._fillMode;
  19807. },
  19808. set: function (value) {
  19809. this._fillMode = value;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Material.prototype, "isFrozen", {
  19815. get: function () {
  19816. return this.checkReadyOnlyOnce;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Material.prototype.freeze = function () {
  19822. this.checkReadyOnlyOnce = true;
  19823. };
  19824. Material.prototype.unfreeze = function () {
  19825. this.checkReadyOnlyOnce = false;
  19826. };
  19827. Material.prototype.isReady = function (mesh, useInstances) {
  19828. return true;
  19829. };
  19830. Material.prototype.getEffect = function () {
  19831. return this._effect;
  19832. };
  19833. Material.prototype.getScene = function () {
  19834. return this._scene;
  19835. };
  19836. Material.prototype.needAlphaBlending = function () {
  19837. return (this.alpha < 1.0);
  19838. };
  19839. Material.prototype.needAlphaTesting = function () {
  19840. return false;
  19841. };
  19842. Material.prototype.getAlphaTestTexture = function () {
  19843. return null;
  19844. };
  19845. Material.prototype.trackCreation = function (onCompiled, onError) {
  19846. };
  19847. Material.prototype.markDirty = function () {
  19848. this._wasPreviouslyReady = false;
  19849. };
  19850. Material.prototype._preBind = function () {
  19851. var engine = this._scene.getEngine();
  19852. engine.enableEffect(this._effect);
  19853. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19854. };
  19855. Material.prototype.bind = function (world, mesh) {
  19856. this._scene._cachedMaterial = this;
  19857. if (this.onBind) {
  19858. this.onBind(this, mesh);
  19859. }
  19860. if (this.disableDepthWrite) {
  19861. var engine = this._scene.getEngine();
  19862. this._cachedDepthWriteState = engine.getDepthWrite();
  19863. engine.setDepthWrite(false);
  19864. }
  19865. };
  19866. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19867. };
  19868. Material.prototype.unbind = function () {
  19869. if (this.disableDepthWrite) {
  19870. var engine = this._scene.getEngine();
  19871. engine.setDepthWrite(this._cachedDepthWriteState);
  19872. }
  19873. };
  19874. Material.prototype.clone = function (name) {
  19875. return null;
  19876. };
  19877. Material.prototype.getBindedMeshes = function () {
  19878. var result = new Array();
  19879. for (var index = 0; index < this._scene.meshes.length; index++) {
  19880. var mesh = this._scene.meshes[index];
  19881. if (mesh.material === this) {
  19882. result.push(mesh);
  19883. }
  19884. }
  19885. return result;
  19886. };
  19887. Material.prototype.dispose = function (forceDisposeEffect) {
  19888. // Animations
  19889. this.getScene().stopAnimation(this);
  19890. // Remove from scene
  19891. var index = this._scene.materials.indexOf(this);
  19892. if (index >= 0) {
  19893. this._scene.materials.splice(index, 1);
  19894. }
  19895. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19896. if (forceDisposeEffect && this._effect) {
  19897. this._scene.getEngine()._releaseEffect(this._effect);
  19898. this._effect = null;
  19899. }
  19900. // Remove from meshes
  19901. for (index = 0; index < this._scene.meshes.length; index++) {
  19902. var mesh = this._scene.meshes[index];
  19903. if (mesh.material === this) {
  19904. mesh.material = null;
  19905. }
  19906. }
  19907. // Callback
  19908. if (this.onDispose) {
  19909. this.onDispose();
  19910. }
  19911. };
  19912. Material.prototype.serialize = function () {
  19913. return BABYLON.SerializationHelper.Serialize(this);
  19914. };
  19915. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19916. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19917. multiMaterial.id = parsedMultiMaterial.id;
  19918. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19919. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19920. var subMatId = parsedMultiMaterial.materials[matIndex];
  19921. if (subMatId) {
  19922. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19923. }
  19924. else {
  19925. multiMaterial.subMaterials.push(null);
  19926. }
  19927. }
  19928. return multiMaterial;
  19929. };
  19930. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19931. if (!parsedMaterial.customType) {
  19932. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19933. }
  19934. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19935. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19936. ;
  19937. };
  19938. Material._TriangleFillMode = 0;
  19939. Material._WireFrameFillMode = 1;
  19940. Material._PointFillMode = 2;
  19941. Material._ClockWiseSideOrientation = 0;
  19942. Material._CounterClockWiseSideOrientation = 1;
  19943. __decorate([
  19944. BABYLON.serialize()
  19945. ], Material.prototype, "id", void 0);
  19946. __decorate([
  19947. BABYLON.serialize()
  19948. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19949. __decorate([
  19950. BABYLON.serialize()
  19951. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19952. __decorate([
  19953. BABYLON.serialize()
  19954. ], Material.prototype, "state", void 0);
  19955. __decorate([
  19956. BABYLON.serialize()
  19957. ], Material.prototype, "alpha", void 0);
  19958. __decorate([
  19959. BABYLON.serialize()
  19960. ], Material.prototype, "backFaceCulling", void 0);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Material.prototype, "sideOrientation", void 0);
  19964. __decorate([
  19965. BABYLON.serialize()
  19966. ], Material.prototype, "alphaMode", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Material.prototype, "disableDepthWrite", void 0);
  19970. __decorate([
  19971. BABYLON.serialize()
  19972. ], Material.prototype, "fogEnabled", void 0);
  19973. __decorate([
  19974. BABYLON.serialize()
  19975. ], Material.prototype, "pointSize", void 0);
  19976. __decorate([
  19977. BABYLON.serialize()
  19978. ], Material.prototype, "zOffset", void 0);
  19979. __decorate([
  19980. BABYLON.serialize()
  19981. ], Material.prototype, "wireframe", null);
  19982. __decorate([
  19983. BABYLON.serialize()
  19984. ], Material.prototype, "pointsCloud", null);
  19985. __decorate([
  19986. BABYLON.serialize()
  19987. ], Material.prototype, "fillMode", null);
  19988. return Material;
  19989. })();
  19990. BABYLON.Material = Material;
  19991. })(BABYLON || (BABYLON = {}));
  19992. var BABYLON;
  19993. (function (BABYLON) {
  19994. var StandardMaterialDefines = (function (_super) {
  19995. __extends(StandardMaterialDefines, _super);
  19996. function StandardMaterialDefines() {
  19997. _super.call(this);
  19998. this.DIFFUSE = false;
  19999. this.AMBIENT = false;
  20000. this.OPACITY = false;
  20001. this.OPACITYRGB = false;
  20002. this.REFLECTION = false;
  20003. this.EMISSIVE = false;
  20004. this.SPECULAR = false;
  20005. this.BUMP = false;
  20006. this.PARALLAX = false;
  20007. this.PARALLAXOCCLUSION = false;
  20008. this.SPECULAROVERALPHA = false;
  20009. this.CLIPPLANE = false;
  20010. this.ALPHATEST = false;
  20011. this.ALPHAFROMDIFFUSE = false;
  20012. this.POINTSIZE = false;
  20013. this.FOG = false;
  20014. this.LIGHT0 = false;
  20015. this.LIGHT1 = false;
  20016. this.LIGHT2 = false;
  20017. this.LIGHT3 = false;
  20018. this.SPOTLIGHT0 = false;
  20019. this.SPOTLIGHT1 = false;
  20020. this.SPOTLIGHT2 = false;
  20021. this.SPOTLIGHT3 = false;
  20022. this.HEMILIGHT0 = false;
  20023. this.HEMILIGHT1 = false;
  20024. this.HEMILIGHT2 = false;
  20025. this.HEMILIGHT3 = false;
  20026. this.POINTLIGHT0 = false;
  20027. this.POINTLIGHT1 = false;
  20028. this.POINTLIGHT2 = false;
  20029. this.POINTLIGHT3 = false;
  20030. this.DIRLIGHT0 = false;
  20031. this.DIRLIGHT1 = false;
  20032. this.DIRLIGHT2 = false;
  20033. this.DIRLIGHT3 = false;
  20034. this.SPECULARTERM = false;
  20035. this.SHADOW0 = false;
  20036. this.SHADOW1 = false;
  20037. this.SHADOW2 = false;
  20038. this.SHADOW3 = false;
  20039. this.SHADOWS = false;
  20040. this.SHADOWVSM0 = false;
  20041. this.SHADOWVSM1 = false;
  20042. this.SHADOWVSM2 = false;
  20043. this.SHADOWVSM3 = false;
  20044. this.SHADOWPCF0 = false;
  20045. this.SHADOWPCF1 = false;
  20046. this.SHADOWPCF2 = false;
  20047. this.SHADOWPCF3 = false;
  20048. this.DIFFUSEFRESNEL = false;
  20049. this.OPACITYFRESNEL = false;
  20050. this.REFLECTIONFRESNEL = false;
  20051. this.REFRACTIONFRESNEL = false;
  20052. this.EMISSIVEFRESNEL = false;
  20053. this.FRESNEL = false;
  20054. this.NORMAL = false;
  20055. this.UV1 = false;
  20056. this.UV2 = false;
  20057. this.VERTEXCOLOR = false;
  20058. this.VERTEXALPHA = false;
  20059. this.NUM_BONE_INFLUENCERS = 0;
  20060. this.BonesPerMesh = 0;
  20061. this.INSTANCES = false;
  20062. this.GLOSSINESS = false;
  20063. this.ROUGHNESS = false;
  20064. this.EMISSIVEASILLUMINATION = false;
  20065. this.LINKEMISSIVEWITHDIFFUSE = false;
  20066. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20067. this.LIGHTMAP = false;
  20068. this.USELIGHTMAPASSHADOWMAP = false;
  20069. this.REFLECTIONMAP_3D = false;
  20070. this.REFLECTIONMAP_SPHERICAL = false;
  20071. this.REFLECTIONMAP_PLANAR = false;
  20072. this.REFLECTIONMAP_CUBIC = false;
  20073. this.REFLECTIONMAP_PROJECTION = false;
  20074. this.REFLECTIONMAP_SKYBOX = false;
  20075. this.REFLECTIONMAP_EXPLICIT = false;
  20076. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20077. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20078. this.INVERTCUBICMAP = false;
  20079. this.LOGARITHMICDEPTH = false;
  20080. this.REFRACTION = false;
  20081. this.REFRACTIONMAP_3D = false;
  20082. this.REFLECTIONOVERALPHA = false;
  20083. this._keys = Object.keys(this);
  20084. }
  20085. return StandardMaterialDefines;
  20086. })(BABYLON.MaterialDefines);
  20087. var StandardMaterial = (function (_super) {
  20088. __extends(StandardMaterial, _super);
  20089. function StandardMaterial(name, scene) {
  20090. var _this = this;
  20091. _super.call(this, name, scene);
  20092. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20093. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20094. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20095. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20096. this.specularPower = 64;
  20097. this.useAlphaFromDiffuseTexture = false;
  20098. this.useEmissiveAsIllumination = false;
  20099. this.linkEmissiveWithDiffuse = false;
  20100. this.useReflectionFresnelFromSpecular = false;
  20101. this.useSpecularOverAlpha = false;
  20102. this.useReflectionOverAlpha = false;
  20103. this.disableLighting = false;
  20104. this.useParallax = false;
  20105. this.useParallaxOcclusion = false;
  20106. this.parallaxScaleBias = 0.05;
  20107. this.roughness = 0;
  20108. this.indexOfRefraction = 0.98;
  20109. this.invertRefractionY = true;
  20110. this.useLightmapAsShadowmap = false;
  20111. this.useGlossinessFromSpecularMapAlpha = false;
  20112. this._renderTargets = new BABYLON.SmartArray(16);
  20113. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20114. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20115. this._defines = new StandardMaterialDefines();
  20116. this._cachedDefines = new StandardMaterialDefines();
  20117. this._cachedDefines.BonesPerMesh = -1;
  20118. this.getRenderTargetTextures = function () {
  20119. _this._renderTargets.reset();
  20120. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20121. _this._renderTargets.push(_this.reflectionTexture);
  20122. }
  20123. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20124. _this._renderTargets.push(_this.refractionTexture);
  20125. }
  20126. return _this._renderTargets;
  20127. };
  20128. }
  20129. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20130. get: function () {
  20131. return this._useLogarithmicDepth;
  20132. },
  20133. set: function (value) {
  20134. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. StandardMaterial.prototype.needAlphaBlending = function () {
  20140. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20141. };
  20142. StandardMaterial.prototype.needAlphaTesting = function () {
  20143. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20144. };
  20145. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20146. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20147. };
  20148. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20149. return this.diffuseTexture;
  20150. };
  20151. // Methods
  20152. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20153. if (!mesh) {
  20154. return true;
  20155. }
  20156. if (this._defines.INSTANCES !== useInstances) {
  20157. return false;
  20158. }
  20159. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20160. return true;
  20161. }
  20162. return false;
  20163. };
  20164. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20165. if (this.isFrozen) {
  20166. if (this._wasPreviouslyReady) {
  20167. return true;
  20168. }
  20169. }
  20170. var scene = this.getScene();
  20171. if (!this.checkReadyOnEveryCall) {
  20172. if (this._renderId === scene.getRenderId()) {
  20173. if (this._checkCache(scene, mesh, useInstances)) {
  20174. return true;
  20175. }
  20176. }
  20177. }
  20178. var engine = scene.getEngine();
  20179. var needNormals = false;
  20180. var needUVs = false;
  20181. this._defines.reset();
  20182. // Textures
  20183. if (scene.texturesEnabled) {
  20184. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20185. if (!this.diffuseTexture.isReady()) {
  20186. return false;
  20187. }
  20188. else {
  20189. needUVs = true;
  20190. this._defines.DIFFUSE = true;
  20191. }
  20192. }
  20193. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20194. if (!this.ambientTexture.isReady()) {
  20195. return false;
  20196. }
  20197. else {
  20198. needUVs = true;
  20199. this._defines.AMBIENT = true;
  20200. }
  20201. }
  20202. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20203. if (!this.opacityTexture.isReady()) {
  20204. return false;
  20205. }
  20206. else {
  20207. needUVs = true;
  20208. this._defines.OPACITY = true;
  20209. if (this.opacityTexture.getAlphaFromRGB) {
  20210. this._defines.OPACITYRGB = true;
  20211. }
  20212. }
  20213. }
  20214. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20215. if (!this.reflectionTexture.isReady()) {
  20216. return false;
  20217. }
  20218. else {
  20219. needNormals = true;
  20220. this._defines.REFLECTION = true;
  20221. if (this.roughness > 0) {
  20222. this._defines.ROUGHNESS = true;
  20223. }
  20224. if (this.useReflectionOverAlpha) {
  20225. this._defines.REFLECTIONOVERALPHA = true;
  20226. }
  20227. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20228. this._defines.INVERTCUBICMAP = true;
  20229. }
  20230. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20231. switch (this.reflectionTexture.coordinatesMode) {
  20232. case BABYLON.Texture.CUBIC_MODE:
  20233. case BABYLON.Texture.INVCUBIC_MODE:
  20234. this._defines.REFLECTIONMAP_CUBIC = true;
  20235. break;
  20236. case BABYLON.Texture.EXPLICIT_MODE:
  20237. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20238. break;
  20239. case BABYLON.Texture.PLANAR_MODE:
  20240. this._defines.REFLECTIONMAP_PLANAR = true;
  20241. break;
  20242. case BABYLON.Texture.PROJECTION_MODE:
  20243. this._defines.REFLECTIONMAP_PROJECTION = true;
  20244. break;
  20245. case BABYLON.Texture.SKYBOX_MODE:
  20246. this._defines.REFLECTIONMAP_SKYBOX = true;
  20247. break;
  20248. case BABYLON.Texture.SPHERICAL_MODE:
  20249. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20250. break;
  20251. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20252. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20253. break;
  20254. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20255. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20256. break;
  20257. }
  20258. }
  20259. }
  20260. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20261. if (!this.emissiveTexture.isReady()) {
  20262. return false;
  20263. }
  20264. else {
  20265. needUVs = true;
  20266. this._defines.EMISSIVE = true;
  20267. }
  20268. }
  20269. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20270. if (!this.lightmapTexture.isReady()) {
  20271. return false;
  20272. }
  20273. else {
  20274. needUVs = true;
  20275. this._defines.LIGHTMAP = true;
  20276. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20277. }
  20278. }
  20279. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20280. if (!this.specularTexture.isReady()) {
  20281. return false;
  20282. }
  20283. else {
  20284. needUVs = true;
  20285. this._defines.SPECULAR = true;
  20286. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20287. }
  20288. }
  20289. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20290. if (!this.bumpTexture.isReady()) {
  20291. return false;
  20292. }
  20293. else {
  20294. needUVs = true;
  20295. this._defines.BUMP = true;
  20296. if (this.useParallax) {
  20297. this._defines.PARALLAX = true;
  20298. if (this.useParallaxOcclusion) {
  20299. this._defines.PARALLAXOCCLUSION = true;
  20300. }
  20301. }
  20302. }
  20303. }
  20304. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20305. if (!this.refractionTexture.isReady()) {
  20306. return false;
  20307. }
  20308. else {
  20309. needUVs = true;
  20310. this._defines.REFRACTION = true;
  20311. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20312. }
  20313. }
  20314. }
  20315. // Effect
  20316. if (scene.clipPlane) {
  20317. this._defines.CLIPPLANE = true;
  20318. }
  20319. if (engine.getAlphaTesting()) {
  20320. this._defines.ALPHATEST = true;
  20321. }
  20322. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20323. this._defines.ALPHAFROMDIFFUSE = true;
  20324. }
  20325. if (this.useEmissiveAsIllumination) {
  20326. this._defines.EMISSIVEASILLUMINATION = true;
  20327. }
  20328. if (this.linkEmissiveWithDiffuse) {
  20329. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20330. }
  20331. if (this.useLogarithmicDepth) {
  20332. this._defines.LOGARITHMICDEPTH = true;
  20333. }
  20334. // Point size
  20335. if (this.pointsCloud || scene.forcePointsCloud) {
  20336. this._defines.POINTSIZE = true;
  20337. }
  20338. // Fog
  20339. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20340. this._defines.FOG = true;
  20341. }
  20342. if (scene.lightsEnabled && !this.disableLighting) {
  20343. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20344. }
  20345. if (StandardMaterial.FresnelEnabled) {
  20346. // Fresnel
  20347. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20348. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20349. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20350. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20351. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20352. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20353. this._defines.DIFFUSEFRESNEL = true;
  20354. }
  20355. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20356. this._defines.OPACITYFRESNEL = true;
  20357. }
  20358. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20359. this._defines.REFLECTIONFRESNEL = true;
  20360. if (this.useReflectionFresnelFromSpecular) {
  20361. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20362. }
  20363. }
  20364. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20365. this._defines.REFRACTIONFRESNEL = true;
  20366. }
  20367. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20368. this._defines.EMISSIVEFRESNEL = true;
  20369. }
  20370. needNormals = true;
  20371. this._defines.FRESNEL = true;
  20372. }
  20373. }
  20374. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20375. this._defines.SPECULAROVERALPHA = true;
  20376. }
  20377. // Attribs
  20378. if (mesh) {
  20379. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20380. this._defines.NORMAL = true;
  20381. }
  20382. if (needUVs) {
  20383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20384. this._defines.UV1 = true;
  20385. }
  20386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20387. this._defines.UV2 = true;
  20388. }
  20389. }
  20390. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20391. this._defines.VERTEXCOLOR = true;
  20392. if (mesh.hasVertexAlpha) {
  20393. this._defines.VERTEXALPHA = true;
  20394. }
  20395. }
  20396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20397. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20398. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20399. }
  20400. // Instances
  20401. if (useInstances) {
  20402. this._defines.INSTANCES = true;
  20403. }
  20404. }
  20405. // Get correct effect
  20406. if (!this._defines.isEqual(this._cachedDefines)) {
  20407. this._defines.cloneTo(this._cachedDefines);
  20408. scene.resetCachedMaterial();
  20409. // Fallbacks
  20410. var fallbacks = new BABYLON.EffectFallbacks();
  20411. if (this._defines.REFLECTION) {
  20412. fallbacks.addFallback(0, "REFLECTION");
  20413. }
  20414. if (this._defines.SPECULAR) {
  20415. fallbacks.addFallback(0, "SPECULAR");
  20416. }
  20417. if (this._defines.BUMP) {
  20418. fallbacks.addFallback(0, "BUMP");
  20419. }
  20420. if (this._defines.PARALLAX) {
  20421. fallbacks.addFallback(1, "PARALLAX");
  20422. }
  20423. if (this._defines.PARALLAXOCCLUSION) {
  20424. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20425. }
  20426. if (this._defines.SPECULAROVERALPHA) {
  20427. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20428. }
  20429. if (this._defines.FOG) {
  20430. fallbacks.addFallback(1, "FOG");
  20431. }
  20432. if (this._defines.POINTSIZE) {
  20433. fallbacks.addFallback(0, "POINTSIZE");
  20434. }
  20435. if (this._defines.LOGARITHMICDEPTH) {
  20436. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20437. }
  20438. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20439. if (this._defines.SPECULARTERM) {
  20440. fallbacks.addFallback(0, "SPECULARTERM");
  20441. }
  20442. if (this._defines.DIFFUSEFRESNEL) {
  20443. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20444. }
  20445. if (this._defines.OPACITYFRESNEL) {
  20446. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20447. }
  20448. if (this._defines.REFLECTIONFRESNEL) {
  20449. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20450. }
  20451. if (this._defines.EMISSIVEFRESNEL) {
  20452. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20453. }
  20454. if (this._defines.FRESNEL) {
  20455. fallbacks.addFallback(4, "FRESNEL");
  20456. }
  20457. //Attributes
  20458. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20459. if (this._defines.NORMAL) {
  20460. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20461. }
  20462. if (this._defines.UV1) {
  20463. attribs.push(BABYLON.VertexBuffer.UVKind);
  20464. }
  20465. if (this._defines.UV2) {
  20466. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20467. }
  20468. if (this._defines.VERTEXCOLOR) {
  20469. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20470. }
  20471. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20472. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20473. // Legacy browser patch
  20474. var shaderName = "default";
  20475. if (!scene.getEngine().getCaps().standardDerivatives) {
  20476. shaderName = "legacydefault";
  20477. }
  20478. var join = this._defines.toString();
  20479. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20480. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20481. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20482. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20483. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20484. "vFogInfos", "vFogColor", "pointSize",
  20485. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20486. "mBones",
  20487. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20488. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20489. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20490. "logarithmicDepthConstant"
  20491. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20492. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20493. ], join, fallbacks, this.onCompiled, this.onError);
  20494. }
  20495. if (!this._effect.isReady()) {
  20496. return false;
  20497. }
  20498. this._renderId = scene.getRenderId();
  20499. this._wasPreviouslyReady = true;
  20500. if (mesh) {
  20501. if (!mesh._materialDefines) {
  20502. mesh._materialDefines = new StandardMaterialDefines();
  20503. }
  20504. this._defines.cloneTo(mesh._materialDefines);
  20505. }
  20506. return true;
  20507. };
  20508. StandardMaterial.prototype.unbind = function () {
  20509. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20510. this._effect.setTexture("reflection2DSampler", null);
  20511. }
  20512. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20513. this._effect.setTexture("refraction2DSampler", null);
  20514. }
  20515. _super.prototype.unbind.call(this);
  20516. };
  20517. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20518. this._effect.setMatrix("world", world);
  20519. };
  20520. StandardMaterial.prototype.bind = function (world, mesh) {
  20521. var scene = this.getScene();
  20522. // Matrices
  20523. this.bindOnlyWorldMatrix(world);
  20524. // Bones
  20525. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20526. if (scene.getCachedMaterial() !== this) {
  20527. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20528. if (StandardMaterial.FresnelEnabled) {
  20529. // Fresnel
  20530. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20531. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20532. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20533. }
  20534. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20535. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20536. }
  20537. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20538. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20539. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20540. }
  20541. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20542. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20543. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20544. }
  20545. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20546. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20547. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20548. }
  20549. }
  20550. // Textures
  20551. if (scene.texturesEnabled) {
  20552. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20553. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20554. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20555. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20556. }
  20557. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20558. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20559. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20560. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20561. }
  20562. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20563. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20564. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20565. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20566. }
  20567. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20568. if (this.reflectionTexture.isCube) {
  20569. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20570. }
  20571. else {
  20572. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20573. }
  20574. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20575. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20576. }
  20577. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20578. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20579. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20580. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20581. }
  20582. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20583. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20584. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20585. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20586. }
  20587. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20588. this._effect.setTexture("specularSampler", this.specularTexture);
  20589. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20590. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20591. }
  20592. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20593. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20594. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20595. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20596. }
  20597. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20598. var depth = 1.0;
  20599. if (this.refractionTexture.isCube) {
  20600. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20601. }
  20602. else {
  20603. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20604. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20605. if (this.refractionTexture.depth) {
  20606. depth = this.refractionTexture.depth;
  20607. }
  20608. }
  20609. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20610. }
  20611. }
  20612. // Clip plane
  20613. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20614. // Point size
  20615. if (this.pointsCloud) {
  20616. this._effect.setFloat("pointSize", this.pointSize);
  20617. }
  20618. // Colors
  20619. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20620. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20621. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20622. if (this._defines.SPECULARTERM) {
  20623. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20624. }
  20625. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20626. }
  20627. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20628. // Diffuse
  20629. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20630. // Lights
  20631. if (scene.lightsEnabled && !this.disableLighting) {
  20632. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20633. }
  20634. // View
  20635. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20636. this._effect.setMatrix("view", scene.getViewMatrix());
  20637. }
  20638. // Fog
  20639. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20640. // Log. depth
  20641. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20642. }
  20643. _super.prototype.bind.call(this, world, mesh);
  20644. };
  20645. StandardMaterial.prototype.getAnimatables = function () {
  20646. var results = [];
  20647. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20648. results.push(this.diffuseTexture);
  20649. }
  20650. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20651. results.push(this.ambientTexture);
  20652. }
  20653. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20654. results.push(this.opacityTexture);
  20655. }
  20656. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20657. results.push(this.reflectionTexture);
  20658. }
  20659. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20660. results.push(this.emissiveTexture);
  20661. }
  20662. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20663. results.push(this.specularTexture);
  20664. }
  20665. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20666. results.push(this.bumpTexture);
  20667. }
  20668. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20669. results.push(this.lightmapTexture);
  20670. }
  20671. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20672. results.push(this.refractionTexture);
  20673. }
  20674. return results;
  20675. };
  20676. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20677. if (this.diffuseTexture) {
  20678. this.diffuseTexture.dispose();
  20679. }
  20680. if (this.ambientTexture) {
  20681. this.ambientTexture.dispose();
  20682. }
  20683. if (this.opacityTexture) {
  20684. this.opacityTexture.dispose();
  20685. }
  20686. if (this.reflectionTexture) {
  20687. this.reflectionTexture.dispose();
  20688. }
  20689. if (this.emissiveTexture) {
  20690. this.emissiveTexture.dispose();
  20691. }
  20692. if (this.specularTexture) {
  20693. this.specularTexture.dispose();
  20694. }
  20695. if (this.bumpTexture) {
  20696. this.bumpTexture.dispose();
  20697. }
  20698. if (this.lightmapTexture) {
  20699. this.lightmapTexture.dispose();
  20700. }
  20701. if (this.refractionTexture) {
  20702. this.refractionTexture.dispose();
  20703. }
  20704. _super.prototype.dispose.call(this, forceDisposeEffect);
  20705. };
  20706. StandardMaterial.prototype.clone = function (name) {
  20707. var _this = this;
  20708. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20709. };
  20710. StandardMaterial.prototype.serialize = function () {
  20711. return BABYLON.SerializationHelper.Serialize(this);
  20712. };
  20713. // Statics
  20714. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20715. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20716. };
  20717. // Flags used to enable or disable a type of texture for all Standard Materials
  20718. StandardMaterial.DiffuseTextureEnabled = true;
  20719. StandardMaterial.AmbientTextureEnabled = true;
  20720. StandardMaterial.OpacityTextureEnabled = true;
  20721. StandardMaterial.ReflectionTextureEnabled = true;
  20722. StandardMaterial.EmissiveTextureEnabled = true;
  20723. StandardMaterial.SpecularTextureEnabled = true;
  20724. StandardMaterial.BumpTextureEnabled = true;
  20725. StandardMaterial.FresnelEnabled = true;
  20726. StandardMaterial.LightmapTextureEnabled = true;
  20727. StandardMaterial.RefractionTextureEnabled = true;
  20728. __decorate([
  20729. BABYLON.serializeAsTexture()
  20730. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20731. __decorate([
  20732. BABYLON.serializeAsTexture()
  20733. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20734. __decorate([
  20735. BABYLON.serializeAsTexture()
  20736. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20737. __decorate([
  20738. BABYLON.serializeAsTexture()
  20739. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20740. __decorate([
  20741. BABYLON.serializeAsTexture()
  20742. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20743. __decorate([
  20744. BABYLON.serializeAsTexture()
  20745. ], StandardMaterial.prototype, "specularTexture", void 0);
  20746. __decorate([
  20747. BABYLON.serializeAsTexture()
  20748. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20749. __decorate([
  20750. BABYLON.serializeAsTexture()
  20751. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20752. __decorate([
  20753. BABYLON.serializeAsTexture()
  20754. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20755. __decorate([
  20756. BABYLON.serializeAsColor3("ambient")
  20757. ], StandardMaterial.prototype, "ambientColor", void 0);
  20758. __decorate([
  20759. BABYLON.serializeAsColor3("diffuse")
  20760. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20761. __decorate([
  20762. BABYLON.serializeAsColor3("specular")
  20763. ], StandardMaterial.prototype, "specularColor", void 0);
  20764. __decorate([
  20765. BABYLON.serializeAsColor3("emissive")
  20766. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20767. __decorate([
  20768. BABYLON.serialize()
  20769. ], StandardMaterial.prototype, "specularPower", void 0);
  20770. __decorate([
  20771. BABYLON.serialize()
  20772. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20773. __decorate([
  20774. BABYLON.serialize()
  20775. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20776. __decorate([
  20777. BABYLON.serialize()
  20778. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20779. __decorate([
  20780. BABYLON.serialize()
  20781. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20782. __decorate([
  20783. BABYLON.serialize()
  20784. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20785. __decorate([
  20786. BABYLON.serialize()
  20787. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20788. __decorate([
  20789. BABYLON.serialize()
  20790. ], StandardMaterial.prototype, "disableLighting", void 0);
  20791. __decorate([
  20792. BABYLON.serialize()
  20793. ], StandardMaterial.prototype, "useParallax", void 0);
  20794. __decorate([
  20795. BABYLON.serialize()
  20796. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20797. __decorate([
  20798. BABYLON.serialize()
  20799. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20800. __decorate([
  20801. BABYLON.serialize()
  20802. ], StandardMaterial.prototype, "roughness", void 0);
  20803. __decorate([
  20804. BABYLON.serialize()
  20805. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20806. __decorate([
  20807. BABYLON.serialize()
  20808. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20809. __decorate([
  20810. BABYLON.serialize()
  20811. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20812. __decorate([
  20813. BABYLON.serializeAsFresnelParameters()
  20814. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20815. __decorate([
  20816. BABYLON.serializeAsFresnelParameters()
  20817. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20818. __decorate([
  20819. BABYLON.serializeAsFresnelParameters()
  20820. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20821. __decorate([
  20822. BABYLON.serializeAsFresnelParameters()
  20823. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20824. __decorate([
  20825. BABYLON.serializeAsFresnelParameters()
  20826. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20827. __decorate([
  20828. BABYLON.serialize()
  20829. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20830. __decorate([
  20831. BABYLON.serialize()
  20832. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20833. return StandardMaterial;
  20834. })(BABYLON.Material);
  20835. BABYLON.StandardMaterial = StandardMaterial;
  20836. })(BABYLON || (BABYLON = {}));
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var MultiMaterial = (function (_super) {
  20840. __extends(MultiMaterial, _super);
  20841. function MultiMaterial(name, scene) {
  20842. _super.call(this, name, scene, true);
  20843. this.subMaterials = new Array();
  20844. scene.multiMaterials.push(this);
  20845. }
  20846. // Properties
  20847. MultiMaterial.prototype.getSubMaterial = function (index) {
  20848. if (index < 0 || index >= this.subMaterials.length) {
  20849. return this.getScene().defaultMaterial;
  20850. }
  20851. return this.subMaterials[index];
  20852. };
  20853. // Methods
  20854. MultiMaterial.prototype.isReady = function (mesh) {
  20855. for (var index = 0; index < this.subMaterials.length; index++) {
  20856. var subMaterial = this.subMaterials[index];
  20857. if (subMaterial) {
  20858. if (!this.subMaterials[index].isReady(mesh)) {
  20859. return false;
  20860. }
  20861. }
  20862. }
  20863. return true;
  20864. };
  20865. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20866. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20867. for (var index = 0; index < this.subMaterials.length; index++) {
  20868. var subMaterial = null;
  20869. if (cloneChildren) {
  20870. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20871. }
  20872. else {
  20873. subMaterial = this.subMaterials[index];
  20874. }
  20875. newMultiMaterial.subMaterials.push(subMaterial);
  20876. }
  20877. return newMultiMaterial;
  20878. };
  20879. MultiMaterial.prototype.serialize = function () {
  20880. var serializationObject = {};
  20881. serializationObject.name = this.name;
  20882. serializationObject.id = this.id;
  20883. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20884. serializationObject.materials = [];
  20885. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20886. var subMat = this.subMaterials[matIndex];
  20887. if (subMat) {
  20888. serializationObject.materials.push(subMat.id);
  20889. }
  20890. else {
  20891. serializationObject.materials.push(null);
  20892. }
  20893. }
  20894. return serializationObject;
  20895. };
  20896. return MultiMaterial;
  20897. })(BABYLON.Material);
  20898. BABYLON.MultiMaterial = MultiMaterial;
  20899. })(BABYLON || (BABYLON = {}));
  20900. var BABYLON;
  20901. (function (BABYLON) {
  20902. var SceneLoader = (function () {
  20903. function SceneLoader() {
  20904. }
  20905. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20906. get: function () {
  20907. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20908. },
  20909. set: function (value) {
  20910. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20916. get: function () {
  20917. return SceneLoader._ShowLoadingScreen;
  20918. },
  20919. set: function (value) {
  20920. SceneLoader._ShowLoadingScreen = value;
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20926. var dotPosition = sceneFilename.lastIndexOf(".");
  20927. var queryStringPosition = sceneFilename.indexOf("?");
  20928. if (queryStringPosition === -1) {
  20929. queryStringPosition = sceneFilename.length;
  20930. }
  20931. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20932. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20933. var plugin = this._registeredPlugins[index];
  20934. if (plugin.extensions.indexOf(extension) !== -1) {
  20935. return plugin;
  20936. }
  20937. }
  20938. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20939. };
  20940. // Public functions
  20941. SceneLoader.GetPluginForExtension = function (extension) {
  20942. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20943. var plugin = this._registeredPlugins[index];
  20944. if (plugin.extensions.indexOf(extension) !== -1) {
  20945. return plugin;
  20946. }
  20947. }
  20948. return null;
  20949. };
  20950. SceneLoader.RegisterPlugin = function (plugin) {
  20951. plugin.extensions = plugin.extensions.toLowerCase();
  20952. SceneLoader._registeredPlugins.push(plugin);
  20953. };
  20954. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20955. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20956. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20957. return;
  20958. }
  20959. var loadingToken = {};
  20960. scene._addPendingData(loadingToken);
  20961. var manifestChecked = function (success) {
  20962. scene.database = database;
  20963. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20964. var importMeshFromData = function (data) {
  20965. var meshes = [];
  20966. var particleSystems = [];
  20967. var skeletons = [];
  20968. try {
  20969. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20970. if (onerror) {
  20971. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20972. }
  20973. scene._removePendingData(loadingToken);
  20974. return;
  20975. }
  20976. }
  20977. catch (e) {
  20978. if (onerror) {
  20979. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20980. }
  20981. scene._removePendingData(loadingToken);
  20982. return;
  20983. }
  20984. if (onsuccess) {
  20985. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20986. onsuccess(meshes, particleSystems, skeletons);
  20987. scene._removePendingData(loadingToken);
  20988. }
  20989. };
  20990. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20991. // Direct load
  20992. importMeshFromData(sceneFilename.substr(5));
  20993. return;
  20994. }
  20995. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20996. importMeshFromData(data);
  20997. }, progressCallBack, database);
  20998. };
  20999. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21000. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21001. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21002. }
  21003. else {
  21004. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21005. manifestChecked(true);
  21006. }
  21007. };
  21008. /**
  21009. * Load a scene
  21010. * @param rootUrl a string that defines the root url for scene and resources
  21011. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21012. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21013. */
  21014. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21015. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21016. };
  21017. /**
  21018. * Append a scene
  21019. * @param rootUrl a string that defines the root url for scene and resources
  21020. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21021. * @param scene is the instance of BABYLON.Scene to append to
  21022. */
  21023. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21024. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21025. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21026. return;
  21027. }
  21028. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21029. var database;
  21030. var loadingToken = {};
  21031. scene._addPendingData(loadingToken);
  21032. if (SceneLoader.ShowLoadingScreen) {
  21033. scene.getEngine().displayLoadingUI();
  21034. }
  21035. var loadSceneFromData = function (data) {
  21036. scene.database = database;
  21037. if (!plugin.load(scene, data, rootUrl)) {
  21038. if (onerror) {
  21039. onerror(scene);
  21040. }
  21041. scene._removePendingData(loadingToken);
  21042. scene.getEngine().hideLoadingUI();
  21043. return;
  21044. }
  21045. if (onsuccess) {
  21046. onsuccess(scene);
  21047. }
  21048. scene._removePendingData(loadingToken);
  21049. if (SceneLoader.ShowLoadingScreen) {
  21050. scene.executeWhenReady(function () {
  21051. scene.getEngine().hideLoadingUI();
  21052. });
  21053. }
  21054. };
  21055. var manifestChecked = function (success) {
  21056. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21057. };
  21058. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21059. // Direct load
  21060. loadSceneFromData(sceneFilename.substr(5));
  21061. return;
  21062. }
  21063. if (rootUrl.indexOf("file:") === -1) {
  21064. if (scene.getEngine().enableOfflineSupport) {
  21065. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21066. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21067. }
  21068. else {
  21069. manifestChecked(true);
  21070. }
  21071. }
  21072. else {
  21073. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21074. }
  21075. };
  21076. // Flags
  21077. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21078. SceneLoader._ShowLoadingScreen = true;
  21079. // Members
  21080. SceneLoader._registeredPlugins = new Array();
  21081. return SceneLoader;
  21082. })();
  21083. BABYLON.SceneLoader = SceneLoader;
  21084. ;
  21085. })(BABYLON || (BABYLON = {}));
  21086. var BABYLON;
  21087. (function (BABYLON) {
  21088. var Internals;
  21089. (function (Internals) {
  21090. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21091. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21092. var parsedMaterial = parsedData.materials[index];
  21093. if (parsedMaterial.id === id) {
  21094. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21095. }
  21096. }
  21097. return null;
  21098. };
  21099. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21100. names = (names instanceof Array) ? names : [names];
  21101. for (var i in names) {
  21102. if (mesh.name === names[i]) {
  21103. hierarchyIds.push(mesh.id);
  21104. return true;
  21105. }
  21106. }
  21107. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21108. hierarchyIds.push(mesh.id);
  21109. return true;
  21110. }
  21111. return false;
  21112. };
  21113. BABYLON.SceneLoader.RegisterPlugin({
  21114. extensions: ".babylon",
  21115. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21116. var parsedData = JSON.parse(data);
  21117. var loadedSkeletonsIds = [];
  21118. var loadedMaterialsIds = [];
  21119. var hierarchyIds = [];
  21120. var index;
  21121. var cache;
  21122. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21123. var parsedMesh = parsedData.meshes[index];
  21124. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21125. if (meshesNames instanceof Array) {
  21126. // Remove found mesh name from list.
  21127. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21128. }
  21129. //Geometry?
  21130. if (parsedMesh.geometryId) {
  21131. //does the file contain geometries?
  21132. if (parsedData.geometries) {
  21133. //find the correct geometry and add it to the scene
  21134. var found = false;
  21135. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21136. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21137. return;
  21138. }
  21139. else {
  21140. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21141. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21142. switch (geometryType) {
  21143. case "boxes":
  21144. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21145. break;
  21146. case "spheres":
  21147. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21148. break;
  21149. case "cylinders":
  21150. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21151. break;
  21152. case "toruses":
  21153. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21154. break;
  21155. case "grounds":
  21156. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21157. break;
  21158. case "planes":
  21159. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21160. break;
  21161. case "torusKnots":
  21162. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21163. break;
  21164. case "vertexData":
  21165. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21166. break;
  21167. }
  21168. found = true;
  21169. }
  21170. });
  21171. }
  21172. });
  21173. if (!found) {
  21174. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21175. }
  21176. }
  21177. }
  21178. // Material ?
  21179. if (parsedMesh.materialId) {
  21180. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21181. if (!materialFound && parsedData.multiMaterials) {
  21182. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21183. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21184. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21185. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21186. var subMatId = parsedMultiMaterial.materials[matIndex];
  21187. loadedMaterialsIds.push(subMatId);
  21188. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21189. }
  21190. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21191. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21192. materialFound = true;
  21193. break;
  21194. }
  21195. }
  21196. }
  21197. if (!materialFound) {
  21198. loadedMaterialsIds.push(parsedMesh.materialId);
  21199. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21200. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21201. }
  21202. }
  21203. }
  21204. // Skeleton ?
  21205. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21206. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21207. if (!skeletonAlreadyLoaded) {
  21208. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21209. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21210. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21211. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21212. loadedSkeletonsIds.push(parsedSkeleton.id);
  21213. }
  21214. }
  21215. }
  21216. }
  21217. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21218. meshes.push(mesh);
  21219. }
  21220. }
  21221. // Connecting parents
  21222. var currentMesh;
  21223. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21224. currentMesh = scene.meshes[index];
  21225. if (currentMesh._waitingParentId) {
  21226. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21227. currentMesh._waitingParentId = undefined;
  21228. }
  21229. }
  21230. // freeze and compute world matrix application
  21231. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21232. currentMesh = scene.meshes[index];
  21233. if (currentMesh._waitingFreezeWorldMatrix) {
  21234. currentMesh.freezeWorldMatrix();
  21235. currentMesh._waitingFreezeWorldMatrix = undefined;
  21236. }
  21237. else {
  21238. currentMesh.computeWorldMatrix(true);
  21239. }
  21240. }
  21241. // Particles
  21242. if (parsedData.particleSystems) {
  21243. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21244. var parsedParticleSystem = parsedData.particleSystems[index];
  21245. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21246. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21247. }
  21248. }
  21249. }
  21250. return true;
  21251. },
  21252. load: function (scene, data, rootUrl) {
  21253. var parsedData = JSON.parse(data);
  21254. // Scene
  21255. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21256. scene.autoClear = parsedData.autoClear;
  21257. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21258. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21259. if (parsedData.gravity) {
  21260. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21261. }
  21262. // Fog
  21263. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21264. scene.fogMode = parsedData.fogMode;
  21265. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21266. scene.fogStart = parsedData.fogStart;
  21267. scene.fogEnd = parsedData.fogEnd;
  21268. scene.fogDensity = parsedData.fogDensity;
  21269. }
  21270. //Physics
  21271. if (parsedData.physicsEnabled) {
  21272. var physicsPlugin;
  21273. if (parsedData.physicsEngine === "cannon") {
  21274. physicsPlugin = new BABYLON.CannonJSPlugin();
  21275. }
  21276. else if (parsedData.physicsEngine === "oimo") {
  21277. physicsPlugin = new BABYLON.OimoJSPlugin();
  21278. }
  21279. //else - default engine, which is currently oimo
  21280. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21281. scene.enablePhysics(physicsGravity, physicsPlugin);
  21282. }
  21283. //collisions, if defined. otherwise, default is true
  21284. if (parsedData.collisionsEnabled != undefined) {
  21285. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21286. }
  21287. scene.workerCollisions = !!parsedData.workerCollisions;
  21288. var index;
  21289. var cache;
  21290. // Lights
  21291. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21292. var parsedLight = parsedData.lights[index];
  21293. BABYLON.Light.Parse(parsedLight, scene);
  21294. }
  21295. // Animations
  21296. if (parsedData.animations) {
  21297. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21298. var parsedAnimation = parsedData.animations[index];
  21299. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21300. }
  21301. }
  21302. // Materials
  21303. if (parsedData.materials) {
  21304. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21305. var parsedMaterial = parsedData.materials[index];
  21306. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21307. }
  21308. }
  21309. if (parsedData.multiMaterials) {
  21310. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21311. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21312. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21313. }
  21314. }
  21315. // Skeletons
  21316. if (parsedData.skeletons) {
  21317. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21318. var parsedSkeleton = parsedData.skeletons[index];
  21319. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21320. }
  21321. }
  21322. // Geometries
  21323. var geometries = parsedData.geometries;
  21324. if (geometries) {
  21325. // Boxes
  21326. var boxes = geometries.boxes;
  21327. if (boxes) {
  21328. for (index = 0, cache = boxes.length; index < cache; index++) {
  21329. var parsedBox = boxes[index];
  21330. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21331. }
  21332. }
  21333. // Spheres
  21334. var spheres = geometries.spheres;
  21335. if (spheres) {
  21336. for (index = 0, cache = spheres.length; index < cache; index++) {
  21337. var parsedSphere = spheres[index];
  21338. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21339. }
  21340. }
  21341. // Cylinders
  21342. var cylinders = geometries.cylinders;
  21343. if (cylinders) {
  21344. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21345. var parsedCylinder = cylinders[index];
  21346. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21347. }
  21348. }
  21349. // Toruses
  21350. var toruses = geometries.toruses;
  21351. if (toruses) {
  21352. for (index = 0, cache = toruses.length; index < cache; index++) {
  21353. var parsedTorus = toruses[index];
  21354. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21355. }
  21356. }
  21357. // Grounds
  21358. var grounds = geometries.grounds;
  21359. if (grounds) {
  21360. for (index = 0, cache = grounds.length; index < cache; index++) {
  21361. var parsedGround = grounds[index];
  21362. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21363. }
  21364. }
  21365. // Planes
  21366. var planes = geometries.planes;
  21367. if (planes) {
  21368. for (index = 0, cache = planes.length; index < cache; index++) {
  21369. var parsedPlane = planes[index];
  21370. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21371. }
  21372. }
  21373. // TorusKnots
  21374. var torusKnots = geometries.torusKnots;
  21375. if (torusKnots) {
  21376. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21377. var parsedTorusKnot = torusKnots[index];
  21378. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21379. }
  21380. }
  21381. // VertexData
  21382. var vertexData = geometries.vertexData;
  21383. if (vertexData) {
  21384. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21385. var parsedVertexData = vertexData[index];
  21386. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21387. }
  21388. }
  21389. }
  21390. // Meshes
  21391. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21392. var parsedMesh = parsedData.meshes[index];
  21393. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21394. }
  21395. // Cameras
  21396. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21397. var parsedCamera = parsedData.cameras[index];
  21398. BABYLON.Camera.Parse(parsedCamera, scene);
  21399. }
  21400. if (parsedData.activeCameraID) {
  21401. scene.setActiveCameraByID(parsedData.activeCameraID);
  21402. }
  21403. // Browsing all the graph to connect the dots
  21404. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21405. var camera = scene.cameras[index];
  21406. if (camera._waitingParentId) {
  21407. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21408. camera._waitingParentId = undefined;
  21409. }
  21410. }
  21411. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21412. var light = scene.lights[index];
  21413. if (light._waitingParentId) {
  21414. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21415. light._waitingParentId = undefined;
  21416. }
  21417. }
  21418. // Sounds
  21419. var loadedSounds = [];
  21420. var loadedSound;
  21421. if (BABYLON.AudioEngine && parsedData.sounds) {
  21422. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21423. var parsedSound = parsedData.sounds[index];
  21424. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21425. if (!parsedSound.url)
  21426. parsedSound.url = parsedSound.name;
  21427. if (!loadedSounds[parsedSound.url]) {
  21428. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21429. loadedSounds[parsedSound.url] = loadedSound;
  21430. }
  21431. else {
  21432. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21433. }
  21434. }
  21435. else {
  21436. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21437. }
  21438. }
  21439. }
  21440. loadedSounds = [];
  21441. // Connect parents & children and parse actions
  21442. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21443. var mesh = scene.meshes[index];
  21444. if (mesh._waitingParentId) {
  21445. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21446. mesh._waitingParentId = undefined;
  21447. }
  21448. if (mesh._waitingActions) {
  21449. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21450. mesh._waitingActions = undefined;
  21451. }
  21452. }
  21453. // freeze world matrix application
  21454. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21455. var currentMesh = scene.meshes[index];
  21456. if (currentMesh._waitingFreezeWorldMatrix) {
  21457. currentMesh.freezeWorldMatrix();
  21458. currentMesh._waitingFreezeWorldMatrix = undefined;
  21459. }
  21460. else {
  21461. currentMesh.computeWorldMatrix(true);
  21462. }
  21463. }
  21464. // Particles Systems
  21465. if (parsedData.particleSystems) {
  21466. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21467. var parsedParticleSystem = parsedData.particleSystems[index];
  21468. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21469. }
  21470. }
  21471. // Lens flares
  21472. if (parsedData.lensFlareSystems) {
  21473. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21474. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21475. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21476. }
  21477. }
  21478. // Shadows
  21479. if (parsedData.shadowGenerators) {
  21480. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21481. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21482. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21483. }
  21484. }
  21485. // Actions (scene)
  21486. if (parsedData.actions) {
  21487. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21488. }
  21489. // Finish
  21490. return true;
  21491. }
  21492. });
  21493. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21494. })(BABYLON || (BABYLON = {}));
  21495. var BABYLON;
  21496. (function (BABYLON) {
  21497. var SpriteManager = (function () {
  21498. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21500. this.name = name;
  21501. this.cellSize = cellSize;
  21502. this.sprites = new Array();
  21503. this.renderingGroupId = 0;
  21504. this.layerMask = 0x0FFFFFFF;
  21505. this.fogEnabled = true;
  21506. this.isPickable = false;
  21507. this._vertexDeclaration = [4, 4, 4, 4];
  21508. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21509. this._capacity = capacity;
  21510. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21511. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21512. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21513. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21514. this._scene = scene;
  21515. this._scene.spriteManagers.push(this);
  21516. // VBO
  21517. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21518. var indices = [];
  21519. var index = 0;
  21520. for (var count = 0; count < capacity; count++) {
  21521. indices.push(index);
  21522. indices.push(index + 1);
  21523. indices.push(index + 2);
  21524. indices.push(index);
  21525. indices.push(index + 2);
  21526. indices.push(index + 3);
  21527. index += 4;
  21528. }
  21529. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21530. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21531. // Effects
  21532. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21533. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21534. }
  21535. Object.defineProperty(SpriteManager.prototype, "texture", {
  21536. get: function () {
  21537. return this._spriteTexture;
  21538. },
  21539. set: function (value) {
  21540. this._spriteTexture = value;
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21546. var arrayOffset = index * 16;
  21547. if (offsetX === 0)
  21548. offsetX = this._epsilon;
  21549. else if (offsetX === 1)
  21550. offsetX = 1 - this._epsilon;
  21551. if (offsetY === 0)
  21552. offsetY = this._epsilon;
  21553. else if (offsetY === 1)
  21554. offsetY = 1 - this._epsilon;
  21555. this._vertices[arrayOffset] = sprite.position.x;
  21556. this._vertices[arrayOffset + 1] = sprite.position.y;
  21557. this._vertices[arrayOffset + 2] = sprite.position.z;
  21558. this._vertices[arrayOffset + 3] = sprite.angle;
  21559. this._vertices[arrayOffset + 4] = sprite.width;
  21560. this._vertices[arrayOffset + 5] = sprite.height;
  21561. this._vertices[arrayOffset + 6] = offsetX;
  21562. this._vertices[arrayOffset + 7] = offsetY;
  21563. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21564. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21565. var offset = (sprite.cellIndex / rowSize) >> 0;
  21566. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21567. this._vertices[arrayOffset + 11] = offset;
  21568. // Color
  21569. this._vertices[arrayOffset + 12] = sprite.color.r;
  21570. this._vertices[arrayOffset + 13] = sprite.color.g;
  21571. this._vertices[arrayOffset + 14] = sprite.color.b;
  21572. this._vertices[arrayOffset + 15] = sprite.color.a;
  21573. };
  21574. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21575. var count = Math.min(this._capacity, this.sprites.length);
  21576. var min = BABYLON.Vector3.Zero();
  21577. var max = BABYLON.Vector3.Zero();
  21578. var distance = Number.MAX_VALUE;
  21579. var currentSprite;
  21580. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21581. var cameraView = camera.getViewMatrix();
  21582. for (var index = 0; index < count; index++) {
  21583. var sprite = this.sprites[index];
  21584. if (!sprite) {
  21585. continue;
  21586. }
  21587. if (predicate) {
  21588. if (!predicate(sprite)) {
  21589. continue;
  21590. }
  21591. }
  21592. else if (!sprite.isPickable) {
  21593. continue;
  21594. }
  21595. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21596. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21597. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21598. if (ray.intersectsBoxMinMax(min, max)) {
  21599. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21600. if (distance > currentDistance) {
  21601. distance = currentDistance;
  21602. currentSprite = sprite;
  21603. if (fastCheck) {
  21604. break;
  21605. }
  21606. }
  21607. }
  21608. }
  21609. if (currentSprite) {
  21610. var result = new BABYLON.PickingInfo();
  21611. result.hit = true;
  21612. result.pickedSprite = currentSprite;
  21613. result.distance = distance;
  21614. return result;
  21615. }
  21616. return null;
  21617. };
  21618. SpriteManager.prototype.render = function () {
  21619. // Check
  21620. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21621. return;
  21622. var engine = this._scene.getEngine();
  21623. var baseSize = this._spriteTexture.getBaseSize();
  21624. // Sprites
  21625. var deltaTime = engine.getDeltaTime();
  21626. var max = Math.min(this._capacity, this.sprites.length);
  21627. var rowSize = baseSize.width / this.cellSize;
  21628. var offset = 0;
  21629. for (var index = 0; index < max; index++) {
  21630. var sprite = this.sprites[index];
  21631. if (!sprite) {
  21632. continue;
  21633. }
  21634. sprite._animate(deltaTime);
  21635. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21636. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21637. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21638. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21639. }
  21640. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21641. // Render
  21642. var effect = this._effectBase;
  21643. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21644. effect = this._effectFog;
  21645. }
  21646. engine.enableEffect(effect);
  21647. var viewMatrix = this._scene.getViewMatrix();
  21648. effect.setTexture("diffuseSampler", this._spriteTexture);
  21649. effect.setMatrix("view", viewMatrix);
  21650. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21651. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21652. // Fog
  21653. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21654. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21655. effect.setColor3("vFogColor", this._scene.fogColor);
  21656. }
  21657. // VBOs
  21658. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21659. // Draw order
  21660. engine.setDepthFunctionToLessOrEqual();
  21661. effect.setBool("alphaTest", true);
  21662. engine.setColorWrite(false);
  21663. engine.draw(true, 0, max * 6);
  21664. engine.setColorWrite(true);
  21665. effect.setBool("alphaTest", false);
  21666. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21667. engine.draw(true, 0, max * 6);
  21668. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21669. };
  21670. SpriteManager.prototype.dispose = function () {
  21671. if (this._vertexBuffer) {
  21672. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21673. this._vertexBuffer = null;
  21674. }
  21675. if (this._indexBuffer) {
  21676. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21677. this._indexBuffer = null;
  21678. }
  21679. if (this._spriteTexture) {
  21680. this._spriteTexture.dispose();
  21681. this._spriteTexture = null;
  21682. }
  21683. // Remove from scene
  21684. var index = this._scene.spriteManagers.indexOf(this);
  21685. this._scene.spriteManagers.splice(index, 1);
  21686. // Callback
  21687. if (this.onDispose) {
  21688. this.onDispose();
  21689. }
  21690. };
  21691. return SpriteManager;
  21692. })();
  21693. BABYLON.SpriteManager = SpriteManager;
  21694. })(BABYLON || (BABYLON = {}));
  21695. var BABYLON;
  21696. (function (BABYLON) {
  21697. var Sprite = (function () {
  21698. function Sprite(name, manager) {
  21699. this.name = name;
  21700. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21701. this.width = 1.0;
  21702. this.height = 1.0;
  21703. this.angle = 0;
  21704. this.cellIndex = 0;
  21705. this.invertU = 0;
  21706. this.invertV = 0;
  21707. this.animations = new Array();
  21708. this.isPickable = false;
  21709. this._animationStarted = false;
  21710. this._loopAnimation = false;
  21711. this._fromIndex = 0;
  21712. this._toIndex = 0;
  21713. this._delay = 0;
  21714. this._direction = 1;
  21715. this._frameCount = 0;
  21716. this._time = 0;
  21717. this._manager = manager;
  21718. this._manager.sprites.push(this);
  21719. this.position = BABYLON.Vector3.Zero();
  21720. }
  21721. Object.defineProperty(Sprite.prototype, "size", {
  21722. get: function () {
  21723. return this.width;
  21724. },
  21725. set: function (value) {
  21726. this.width = value;
  21727. this.height = value;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21733. this._fromIndex = from;
  21734. this._toIndex = to;
  21735. this._loopAnimation = loop;
  21736. this._delay = delay;
  21737. this._animationStarted = true;
  21738. this._direction = from < to ? 1 : -1;
  21739. this.cellIndex = from;
  21740. this._time = 0;
  21741. };
  21742. Sprite.prototype.stopAnimation = function () {
  21743. this._animationStarted = false;
  21744. };
  21745. Sprite.prototype._animate = function (deltaTime) {
  21746. if (!this._animationStarted)
  21747. return;
  21748. this._time += deltaTime;
  21749. if (this._time > this._delay) {
  21750. this._time = this._time % this._delay;
  21751. this.cellIndex += this._direction;
  21752. if (this.cellIndex == this._toIndex) {
  21753. if (this._loopAnimation) {
  21754. this.cellIndex = this._fromIndex;
  21755. }
  21756. else {
  21757. this._animationStarted = false;
  21758. if (this.disposeWhenFinishedAnimating) {
  21759. this.dispose();
  21760. }
  21761. }
  21762. }
  21763. }
  21764. };
  21765. Sprite.prototype.dispose = function () {
  21766. for (var i = 0; i < this._manager.sprites.length; i++) {
  21767. if (this._manager.sprites[i] == this) {
  21768. this._manager.sprites.splice(i, 1);
  21769. }
  21770. }
  21771. };
  21772. return Sprite;
  21773. })();
  21774. BABYLON.Sprite = Sprite;
  21775. })(BABYLON || (BABYLON = {}));
  21776. var BABYLON;
  21777. (function (BABYLON) {
  21778. var Layer = (function () {
  21779. function Layer(name, imgUrl, scene, isBackground, color) {
  21780. this.name = name;
  21781. this.scale = new BABYLON.Vector2(1, 1);
  21782. this.offset = new BABYLON.Vector2(0, 0);
  21783. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21784. this._vertexDeclaration = [2];
  21785. this._vertexStrideSize = 2 * 4;
  21786. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21787. this.isBackground = isBackground === undefined ? true : isBackground;
  21788. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21789. this._scene = scene;
  21790. this._scene.layers.push(this);
  21791. // VBO
  21792. var vertices = [];
  21793. vertices.push(1, 1);
  21794. vertices.push(-1, 1);
  21795. vertices.push(-1, -1);
  21796. vertices.push(1, -1);
  21797. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21798. // Indices
  21799. var indices = [];
  21800. indices.push(0);
  21801. indices.push(1);
  21802. indices.push(2);
  21803. indices.push(0);
  21804. indices.push(2);
  21805. indices.push(3);
  21806. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21807. // Effects
  21808. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21809. }
  21810. Layer.prototype.render = function () {
  21811. // Check
  21812. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21813. return;
  21814. var engine = this._scene.getEngine();
  21815. // Render
  21816. engine.enableEffect(this._effect);
  21817. engine.setState(false);
  21818. // Texture
  21819. this._effect.setTexture("textureSampler", this.texture);
  21820. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21821. // Color
  21822. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21823. // Scale / offset
  21824. this._effect.setVector2("offset", this.offset);
  21825. this._effect.setVector2("scale", this.scale);
  21826. // VBOs
  21827. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21828. // Draw order
  21829. engine.setAlphaMode(this.alphaBlendingMode);
  21830. engine.draw(true, 0, 6);
  21831. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21832. };
  21833. Layer.prototype.dispose = function () {
  21834. if (this._vertexBuffer) {
  21835. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21836. this._vertexBuffer = null;
  21837. }
  21838. if (this._indexBuffer) {
  21839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21840. this._indexBuffer = null;
  21841. }
  21842. if (this.texture) {
  21843. this.texture.dispose();
  21844. this.texture = null;
  21845. }
  21846. // Remove from scene
  21847. var index = this._scene.layers.indexOf(this);
  21848. this._scene.layers.splice(index, 1);
  21849. // Callback
  21850. if (this.onDispose) {
  21851. this.onDispose();
  21852. }
  21853. };
  21854. return Layer;
  21855. })();
  21856. BABYLON.Layer = Layer;
  21857. })(BABYLON || (BABYLON = {}));
  21858. var BABYLON;
  21859. (function (BABYLON) {
  21860. var Particle = (function () {
  21861. function Particle() {
  21862. this.position = BABYLON.Vector3.Zero();
  21863. this.direction = BABYLON.Vector3.Zero();
  21864. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21865. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21866. this.lifeTime = 1.0;
  21867. this.age = 0;
  21868. this.size = 0;
  21869. this.angle = 0;
  21870. this.angularSpeed = 0;
  21871. }
  21872. Particle.prototype.copyTo = function (other) {
  21873. other.position.copyFrom(this.position);
  21874. other.direction.copyFrom(this.direction);
  21875. other.color.copyFrom(this.color);
  21876. other.colorStep.copyFrom(this.colorStep);
  21877. other.lifeTime = this.lifeTime;
  21878. other.age = this.age;
  21879. other.size = this.size;
  21880. other.angle = this.angle;
  21881. other.angularSpeed = this.angularSpeed;
  21882. };
  21883. return Particle;
  21884. })();
  21885. BABYLON.Particle = Particle;
  21886. })(BABYLON || (BABYLON = {}));
  21887. var BABYLON;
  21888. (function (BABYLON) {
  21889. var randomNumber = function (min, max) {
  21890. if (min === max) {
  21891. return (min);
  21892. }
  21893. var random = Math.random();
  21894. return ((random * (max - min)) + min);
  21895. };
  21896. var ParticleSystem = (function () {
  21897. function ParticleSystem(name, capacity, scene, customEffect) {
  21898. var _this = this;
  21899. this.name = name;
  21900. // Members
  21901. this.animations = [];
  21902. this.renderingGroupId = 0;
  21903. this.emitter = null;
  21904. this.emitRate = 10;
  21905. this.manualEmitCount = -1;
  21906. this.updateSpeed = 0.01;
  21907. this.targetStopDuration = 0;
  21908. this.disposeOnStop = false;
  21909. this.minEmitPower = 1;
  21910. this.maxEmitPower = 1;
  21911. this.minLifeTime = 1;
  21912. this.maxLifeTime = 1;
  21913. this.minSize = 1;
  21914. this.maxSize = 1;
  21915. this.minAngularSpeed = 0;
  21916. this.maxAngularSpeed = 0;
  21917. this.layerMask = 0x0FFFFFFF;
  21918. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21919. this.forceDepthWrite = false;
  21920. this.gravity = BABYLON.Vector3.Zero();
  21921. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21922. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21923. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21924. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21925. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21926. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21927. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21928. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21929. this.particles = new Array();
  21930. this._vertexDeclaration = [3, 4, 4];
  21931. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21932. this._stockParticles = new Array();
  21933. this._newPartsExcess = 0;
  21934. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21935. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21936. this._scaledDirection = BABYLON.Vector3.Zero();
  21937. this._scaledGravity = BABYLON.Vector3.Zero();
  21938. this._currentRenderId = -1;
  21939. this._started = false;
  21940. this._stopped = false;
  21941. this._actualFrame = 0;
  21942. this.id = name;
  21943. this._capacity = capacity;
  21944. this._scene = scene;
  21945. this._customEffect = customEffect;
  21946. scene.particleSystems.push(this);
  21947. // VBO
  21948. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21949. var indices = [];
  21950. var index = 0;
  21951. for (var count = 0; count < capacity; count++) {
  21952. indices.push(index);
  21953. indices.push(index + 1);
  21954. indices.push(index + 2);
  21955. indices.push(index);
  21956. indices.push(index + 2);
  21957. indices.push(index + 3);
  21958. index += 4;
  21959. }
  21960. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21961. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21962. // Default behaviors
  21963. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21964. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21965. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21966. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21967. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21968. };
  21969. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21970. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21971. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21972. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21974. };
  21975. this.updateFunction = function (particles) {
  21976. for (var index = 0; index < particles.length; index++) {
  21977. var particle = particles[index];
  21978. particle.age += _this._scaledUpdateSpeed;
  21979. if (particle.age >= particle.lifeTime) {
  21980. _this.recycleParticle(particle);
  21981. index--;
  21982. continue;
  21983. }
  21984. else {
  21985. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21986. particle.color.addInPlace(_this._scaledColorStep);
  21987. if (particle.color.a < 0)
  21988. particle.color.a = 0;
  21989. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21990. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21991. particle.position.addInPlace(_this._scaledDirection);
  21992. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21993. particle.direction.addInPlace(_this._scaledGravity);
  21994. }
  21995. }
  21996. };
  21997. }
  21998. ParticleSystem.prototype.recycleParticle = function (particle) {
  21999. var lastParticle = this.particles.pop();
  22000. if (lastParticle !== particle) {
  22001. lastParticle.copyTo(particle);
  22002. this._stockParticles.push(lastParticle);
  22003. }
  22004. };
  22005. ParticleSystem.prototype.getCapacity = function () {
  22006. return this._capacity;
  22007. };
  22008. ParticleSystem.prototype.isAlive = function () {
  22009. return this._alive;
  22010. };
  22011. ParticleSystem.prototype.isStarted = function () {
  22012. return this._started;
  22013. };
  22014. ParticleSystem.prototype.start = function () {
  22015. this._started = true;
  22016. this._stopped = false;
  22017. this._actualFrame = 0;
  22018. };
  22019. ParticleSystem.prototype.stop = function () {
  22020. this._stopped = true;
  22021. };
  22022. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22023. var offset = index * 11;
  22024. this._vertices[offset] = particle.position.x;
  22025. this._vertices[offset + 1] = particle.position.y;
  22026. this._vertices[offset + 2] = particle.position.z;
  22027. this._vertices[offset + 3] = particle.color.r;
  22028. this._vertices[offset + 4] = particle.color.g;
  22029. this._vertices[offset + 5] = particle.color.b;
  22030. this._vertices[offset + 6] = particle.color.a;
  22031. this._vertices[offset + 7] = particle.angle;
  22032. this._vertices[offset + 8] = particle.size;
  22033. this._vertices[offset + 9] = offsetX;
  22034. this._vertices[offset + 10] = offsetY;
  22035. };
  22036. ParticleSystem.prototype._update = function (newParticles) {
  22037. // Update current
  22038. this._alive = this.particles.length > 0;
  22039. this.updateFunction(this.particles);
  22040. // Add new ones
  22041. var worldMatrix;
  22042. if (this.emitter.position) {
  22043. worldMatrix = this.emitter.getWorldMatrix();
  22044. }
  22045. else {
  22046. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22047. }
  22048. var particle;
  22049. for (var index = 0; index < newParticles; index++) {
  22050. if (this.particles.length === this._capacity) {
  22051. break;
  22052. }
  22053. if (this._stockParticles.length !== 0) {
  22054. particle = this._stockParticles.pop();
  22055. particle.age = 0;
  22056. }
  22057. else {
  22058. particle = new BABYLON.Particle();
  22059. }
  22060. this.particles.push(particle);
  22061. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22062. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22063. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22064. particle.size = randomNumber(this.minSize, this.maxSize);
  22065. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22066. this.startPositionFunction(worldMatrix, particle.position, particle);
  22067. var step = randomNumber(0, 1.0);
  22068. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22069. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22070. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22071. }
  22072. };
  22073. ParticleSystem.prototype._getEffect = function () {
  22074. if (this._customEffect) {
  22075. return this._customEffect;
  22076. }
  22077. ;
  22078. var defines = [];
  22079. if (this._scene.clipPlane) {
  22080. defines.push("#define CLIPPLANE");
  22081. }
  22082. // Effect
  22083. var join = defines.join("\n");
  22084. if (this._cachedDefines !== join) {
  22085. this._cachedDefines = join;
  22086. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22087. }
  22088. return this._effect;
  22089. };
  22090. ParticleSystem.prototype.animate = function () {
  22091. if (!this._started)
  22092. return;
  22093. var effect = this._getEffect();
  22094. // Check
  22095. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22096. return;
  22097. if (this._currentRenderId === this._scene.getRenderId()) {
  22098. return;
  22099. }
  22100. this._currentRenderId = this._scene.getRenderId();
  22101. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22102. // determine the number of particles we need to create
  22103. var newParticles;
  22104. if (this.manualEmitCount > -1) {
  22105. newParticles = this.manualEmitCount;
  22106. this._newPartsExcess = 0;
  22107. this.manualEmitCount = 0;
  22108. }
  22109. else {
  22110. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22111. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22112. }
  22113. if (this._newPartsExcess > 1.0) {
  22114. newParticles += this._newPartsExcess >> 0;
  22115. this._newPartsExcess -= this._newPartsExcess >> 0;
  22116. }
  22117. this._alive = false;
  22118. if (!this._stopped) {
  22119. this._actualFrame += this._scaledUpdateSpeed;
  22120. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22121. this.stop();
  22122. }
  22123. else {
  22124. newParticles = 0;
  22125. }
  22126. this._update(newParticles);
  22127. // Stopped?
  22128. if (this._stopped) {
  22129. if (!this._alive) {
  22130. this._started = false;
  22131. if (this.disposeOnStop) {
  22132. this._scene._toBeDisposed.push(this);
  22133. }
  22134. }
  22135. }
  22136. // Update VBO
  22137. var offset = 0;
  22138. for (var index = 0; index < this.particles.length; index++) {
  22139. var particle = this.particles[index];
  22140. this._appendParticleVertex(offset++, particle, 0, 0);
  22141. this._appendParticleVertex(offset++, particle, 1, 0);
  22142. this._appendParticleVertex(offset++, particle, 1, 1);
  22143. this._appendParticleVertex(offset++, particle, 0, 1);
  22144. }
  22145. var engine = this._scene.getEngine();
  22146. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22147. };
  22148. ParticleSystem.prototype.render = function () {
  22149. var effect = this._getEffect();
  22150. // Check
  22151. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22152. return 0;
  22153. var engine = this._scene.getEngine();
  22154. // Render
  22155. engine.enableEffect(effect);
  22156. engine.setState(false);
  22157. var viewMatrix = this._scene.getViewMatrix();
  22158. effect.setTexture("diffuseSampler", this.particleTexture);
  22159. effect.setMatrix("view", viewMatrix);
  22160. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22161. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22162. if (this._scene.clipPlane) {
  22163. var clipPlane = this._scene.clipPlane;
  22164. var invView = viewMatrix.clone();
  22165. invView.invert();
  22166. effect.setMatrix("invView", invView);
  22167. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22168. }
  22169. // VBOs
  22170. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22171. // Draw order
  22172. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22173. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22174. }
  22175. else {
  22176. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22177. }
  22178. if (this.forceDepthWrite) {
  22179. engine.setDepthWrite(true);
  22180. }
  22181. engine.draw(true, 0, this.particles.length * 6);
  22182. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22183. return this.particles.length;
  22184. };
  22185. ParticleSystem.prototype.dispose = function () {
  22186. if (this._vertexBuffer) {
  22187. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22188. this._vertexBuffer = null;
  22189. }
  22190. if (this._indexBuffer) {
  22191. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22192. this._indexBuffer = null;
  22193. }
  22194. if (this.particleTexture) {
  22195. this.particleTexture.dispose();
  22196. this.particleTexture = null;
  22197. }
  22198. // Remove from scene
  22199. var index = this._scene.particleSystems.indexOf(this);
  22200. this._scene.particleSystems.splice(index, 1);
  22201. // Callback
  22202. if (this.onDispose) {
  22203. this.onDispose();
  22204. }
  22205. };
  22206. // Clone
  22207. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22208. var result = new ParticleSystem(name, this._capacity, this._scene);
  22209. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22210. if (newEmitter === undefined) {
  22211. newEmitter = this.emitter;
  22212. }
  22213. result.emitter = newEmitter;
  22214. if (this.particleTexture) {
  22215. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22216. }
  22217. result.start();
  22218. return result;
  22219. };
  22220. ParticleSystem.prototype.serialize = function () {
  22221. var serializationObject = {};
  22222. serializationObject.name = this.name;
  22223. serializationObject.id = this.id;
  22224. // Emitter
  22225. if (this.emitter.position) {
  22226. serializationObject.emitterId = this.emitter.id;
  22227. }
  22228. else {
  22229. serializationObject.emitter = this.emitter.asArray();
  22230. }
  22231. serializationObject.capacity = this.getCapacity();
  22232. if (this.particleTexture) {
  22233. serializationObject.textureName = this.particleTexture.name;
  22234. }
  22235. // Animations
  22236. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22237. // Particle system
  22238. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22239. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22240. serializationObject.minSize = this.minSize;
  22241. serializationObject.maxSize = this.maxSize;
  22242. serializationObject.minEmitPower = this.minEmitPower;
  22243. serializationObject.maxEmitPower = this.maxEmitPower;
  22244. serializationObject.minLifeTime = this.minLifeTime;
  22245. serializationObject.maxLifeTime = this.maxLifeTime;
  22246. serializationObject.emitRate = this.emitRate;
  22247. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22248. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22249. serializationObject.gravity = this.gravity.asArray();
  22250. serializationObject.direction1 = this.direction1.asArray();
  22251. serializationObject.direction2 = this.direction2.asArray();
  22252. serializationObject.color1 = this.color1.asArray();
  22253. serializationObject.color2 = this.color2.asArray();
  22254. serializationObject.colorDead = this.colorDead.asArray();
  22255. serializationObject.updateSpeed = this.updateSpeed;
  22256. serializationObject.targetStopDuration = this.targetStopDuration;
  22257. serializationObject.textureMask = this.textureMask.asArray();
  22258. serializationObject.blendMode = this.blendMode;
  22259. return serializationObject;
  22260. };
  22261. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22262. var name = parsedParticleSystem.name;
  22263. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22264. if (parsedParticleSystem.id) {
  22265. particleSystem.id = parsedParticleSystem.id;
  22266. }
  22267. // Texture
  22268. if (parsedParticleSystem.textureName) {
  22269. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22270. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22271. }
  22272. // Emitter
  22273. if (parsedParticleSystem.emitterId) {
  22274. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22275. }
  22276. else {
  22277. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22278. }
  22279. // Animations
  22280. if (parsedParticleSystem.animations) {
  22281. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22282. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22283. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22284. }
  22285. }
  22286. // Particle system
  22287. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22288. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22289. particleSystem.minSize = parsedParticleSystem.minSize;
  22290. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22291. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22292. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22293. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22294. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22295. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22296. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22297. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22298. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22299. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22300. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22301. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22302. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22303. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22304. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22305. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22306. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22307. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22308. particleSystem.start();
  22309. return particleSystem;
  22310. };
  22311. // Statics
  22312. ParticleSystem.BLENDMODE_ONEONE = 0;
  22313. ParticleSystem.BLENDMODE_STANDARD = 1;
  22314. return ParticleSystem;
  22315. })();
  22316. BABYLON.ParticleSystem = ParticleSystem;
  22317. })(BABYLON || (BABYLON = {}));
  22318. var BABYLON;
  22319. (function (BABYLON) {
  22320. var AnimationRange = (function () {
  22321. function AnimationRange(name, from, to) {
  22322. this.name = name;
  22323. this.from = from;
  22324. this.to = to;
  22325. }
  22326. return AnimationRange;
  22327. })();
  22328. BABYLON.AnimationRange = AnimationRange;
  22329. /**
  22330. * Composed of a frame, and an action function
  22331. */
  22332. var AnimationEvent = (function () {
  22333. function AnimationEvent(frame, action, onlyOnce) {
  22334. this.frame = frame;
  22335. this.action = action;
  22336. this.onlyOnce = onlyOnce;
  22337. this.isDone = false;
  22338. }
  22339. return AnimationEvent;
  22340. })();
  22341. BABYLON.AnimationEvent = AnimationEvent;
  22342. var Animation = (function () {
  22343. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22344. this.name = name;
  22345. this.targetProperty = targetProperty;
  22346. this.framePerSecond = framePerSecond;
  22347. this.dataType = dataType;
  22348. this.loopMode = loopMode;
  22349. this._offsetsCache = {};
  22350. this._highLimitsCache = {};
  22351. this._stopped = false;
  22352. // The set of event that will be linked to this animation
  22353. this._events = new Array();
  22354. this.allowMatricesInterpolation = false;
  22355. this._ranges = {};
  22356. this.targetPropertyPath = targetProperty.split(".");
  22357. this.dataType = dataType;
  22358. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22359. }
  22360. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22361. var dataType = undefined;
  22362. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22363. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22364. }
  22365. else if (from instanceof BABYLON.Quaternion) {
  22366. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22367. }
  22368. else if (from instanceof BABYLON.Vector3) {
  22369. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22370. }
  22371. else if (from instanceof BABYLON.Vector2) {
  22372. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22373. }
  22374. else if (from instanceof BABYLON.Color3) {
  22375. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22376. }
  22377. if (dataType == undefined) {
  22378. return null;
  22379. }
  22380. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22381. var keys = [];
  22382. keys.push({ frame: 0, value: from });
  22383. keys.push({ frame: totalFrame, value: to });
  22384. animation.setKeys(keys);
  22385. if (easingFunction !== undefined) {
  22386. animation.setEasingFunction(easingFunction);
  22387. }
  22388. return animation;
  22389. };
  22390. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22391. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22392. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22393. };
  22394. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22395. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22396. node.animations.push(animation);
  22397. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22398. };
  22399. // Methods
  22400. /**
  22401. * Add an event to this animation.
  22402. */
  22403. Animation.prototype.addEvent = function (event) {
  22404. this._events.push(event);
  22405. };
  22406. /**
  22407. * Remove all events found at the given frame
  22408. * @param frame
  22409. */
  22410. Animation.prototype.removeEvents = function (frame) {
  22411. for (var index = 0; index < this._events.length; index++) {
  22412. if (this._events[index].frame === frame) {
  22413. this._events.splice(index, 1);
  22414. index--;
  22415. }
  22416. }
  22417. };
  22418. Animation.prototype.createRange = function (name, from, to) {
  22419. // check name not already in use; could happen for bones after serialized
  22420. if (!this._ranges[name]) {
  22421. this._ranges[name] = new AnimationRange(name, from, to);
  22422. }
  22423. };
  22424. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22425. if (deleteFrames === void 0) { deleteFrames = true; }
  22426. if (this._ranges[name]) {
  22427. if (deleteFrames) {
  22428. var from = this._ranges[name].from;
  22429. var to = this._ranges[name].to;
  22430. // this loop MUST go high to low for multiple splices to work
  22431. for (var key = this._keys.length - 1; key >= 0; key--) {
  22432. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22433. this._keys.splice(key, 1);
  22434. }
  22435. }
  22436. }
  22437. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22438. }
  22439. };
  22440. Animation.prototype.getRange = function (name) {
  22441. return this._ranges[name];
  22442. };
  22443. Animation.prototype.reset = function () {
  22444. this._offsetsCache = {};
  22445. this._highLimitsCache = {};
  22446. this.currentFrame = 0;
  22447. };
  22448. Animation.prototype.isStopped = function () {
  22449. return this._stopped;
  22450. };
  22451. Animation.prototype.getKeys = function () {
  22452. return this._keys;
  22453. };
  22454. Animation.prototype.getHighestFrame = function () {
  22455. var ret = 0;
  22456. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22457. if (ret < this._keys[key].frame) {
  22458. ret = this._keys[key].frame;
  22459. }
  22460. }
  22461. return ret;
  22462. };
  22463. Animation.prototype.getEasingFunction = function () {
  22464. return this._easingFunction;
  22465. };
  22466. Animation.prototype.setEasingFunction = function (easingFunction) {
  22467. this._easingFunction = easingFunction;
  22468. };
  22469. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22470. return startValue + (endValue - startValue) * gradient;
  22471. };
  22472. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22473. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22474. };
  22475. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22476. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22477. };
  22478. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22479. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22480. };
  22481. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22482. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22483. };
  22484. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22485. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22486. };
  22487. Animation.prototype.clone = function () {
  22488. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22489. if (this._keys) {
  22490. clone.setKeys(this._keys);
  22491. }
  22492. return clone;
  22493. };
  22494. Animation.prototype.setKeys = function (values) {
  22495. this._keys = values.slice(0);
  22496. this._offsetsCache = {};
  22497. this._highLimitsCache = {};
  22498. };
  22499. Animation.prototype._getKeyValue = function (value) {
  22500. if (typeof value === "function") {
  22501. return value();
  22502. }
  22503. return value;
  22504. };
  22505. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22506. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22507. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22508. }
  22509. this.currentFrame = currentFrame;
  22510. // Try to get a hash to find the right key
  22511. 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));
  22512. if (this._keys[startKey].frame >= currentFrame) {
  22513. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22514. startKey--;
  22515. }
  22516. }
  22517. for (var key = startKey; key < this._keys.length; key++) {
  22518. if (this._keys[key + 1].frame >= currentFrame) {
  22519. var startValue = this._getKeyValue(this._keys[key].value);
  22520. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22521. // gradient : percent of currentFrame between the frame inf and the frame sup
  22522. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22523. // check for easingFunction and correction of gradient
  22524. if (this._easingFunction != null) {
  22525. gradient = this._easingFunction.ease(gradient);
  22526. }
  22527. switch (this.dataType) {
  22528. // Float
  22529. case Animation.ANIMATIONTYPE_FLOAT:
  22530. switch (loopMode) {
  22531. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22532. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22533. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22534. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22535. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22536. }
  22537. break;
  22538. // Quaternion
  22539. case Animation.ANIMATIONTYPE_QUATERNION:
  22540. var quaternion = null;
  22541. switch (loopMode) {
  22542. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22543. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22544. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22545. break;
  22546. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22547. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22548. break;
  22549. }
  22550. return quaternion;
  22551. // Vector3
  22552. case Animation.ANIMATIONTYPE_VECTOR3:
  22553. switch (loopMode) {
  22554. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22555. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22556. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22557. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22558. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22559. }
  22560. // Vector2
  22561. case Animation.ANIMATIONTYPE_VECTOR2:
  22562. switch (loopMode) {
  22563. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22564. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22565. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22566. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22567. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22568. }
  22569. // Color3
  22570. case Animation.ANIMATIONTYPE_COLOR3:
  22571. switch (loopMode) {
  22572. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22573. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22574. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22576. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22577. }
  22578. // Matrix
  22579. case Animation.ANIMATIONTYPE_MATRIX:
  22580. switch (loopMode) {
  22581. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22582. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22583. if (this.allowMatricesInterpolation) {
  22584. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22585. }
  22586. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22587. return startValue;
  22588. }
  22589. default:
  22590. break;
  22591. }
  22592. break;
  22593. }
  22594. }
  22595. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22596. };
  22597. Animation.prototype.setValue = function (currentValue) {
  22598. // Set value
  22599. if (this.targetPropertyPath.length > 1) {
  22600. var property = this._target[this.targetPropertyPath[0]];
  22601. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22602. property = property[this.targetPropertyPath[index]];
  22603. }
  22604. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22605. }
  22606. else {
  22607. this._target[this.targetPropertyPath[0]] = currentValue;
  22608. }
  22609. if (this._target.markAsDirty) {
  22610. this._target.markAsDirty(this.targetProperty);
  22611. }
  22612. };
  22613. Animation.prototype.goToFrame = function (frame) {
  22614. if (frame < this._keys[0].frame) {
  22615. frame = this._keys[0].frame;
  22616. }
  22617. else if (frame > this._keys[this._keys.length - 1].frame) {
  22618. frame = this._keys[this._keys.length - 1].frame;
  22619. }
  22620. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22621. this.setValue(currentValue);
  22622. };
  22623. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22624. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22625. this._stopped = true;
  22626. return false;
  22627. }
  22628. var returnValue = true;
  22629. // Adding a start key at frame 0 if missing
  22630. if (this._keys[0].frame !== 0) {
  22631. var newKey = { frame: 0, value: this._keys[0].value };
  22632. this._keys.splice(0, 0, newKey);
  22633. }
  22634. // Check limits
  22635. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22636. from = this._keys[0].frame;
  22637. }
  22638. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22639. to = this._keys[this._keys.length - 1].frame;
  22640. }
  22641. // Compute ratio
  22642. var range = to - from;
  22643. var offsetValue;
  22644. // ratio represents the frame delta between from and to
  22645. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22646. var highLimitValue = 0;
  22647. if (ratio > range && !loop) {
  22648. returnValue = false;
  22649. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22650. }
  22651. else {
  22652. // Get max value if required
  22653. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22654. var keyOffset = to.toString() + from.toString();
  22655. if (!this._offsetsCache[keyOffset]) {
  22656. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22657. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22658. switch (this.dataType) {
  22659. // Float
  22660. case Animation.ANIMATIONTYPE_FLOAT:
  22661. this._offsetsCache[keyOffset] = toValue - fromValue;
  22662. break;
  22663. // Quaternion
  22664. case Animation.ANIMATIONTYPE_QUATERNION:
  22665. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22666. break;
  22667. // Vector3
  22668. case Animation.ANIMATIONTYPE_VECTOR3:
  22669. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22670. // Vector2
  22671. case Animation.ANIMATIONTYPE_VECTOR2:
  22672. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22673. // Color3
  22674. case Animation.ANIMATIONTYPE_COLOR3:
  22675. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22676. default:
  22677. break;
  22678. }
  22679. this._highLimitsCache[keyOffset] = toValue;
  22680. }
  22681. highLimitValue = this._highLimitsCache[keyOffset];
  22682. offsetValue = this._offsetsCache[keyOffset];
  22683. }
  22684. }
  22685. if (offsetValue === undefined) {
  22686. switch (this.dataType) {
  22687. // Float
  22688. case Animation.ANIMATIONTYPE_FLOAT:
  22689. offsetValue = 0;
  22690. break;
  22691. // Quaternion
  22692. case Animation.ANIMATIONTYPE_QUATERNION:
  22693. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22694. break;
  22695. // Vector3
  22696. case Animation.ANIMATIONTYPE_VECTOR3:
  22697. offsetValue = BABYLON.Vector3.Zero();
  22698. break;
  22699. // Vector2
  22700. case Animation.ANIMATIONTYPE_VECTOR2:
  22701. offsetValue = BABYLON.Vector2.Zero();
  22702. break;
  22703. // Color3
  22704. case Animation.ANIMATIONTYPE_COLOR3:
  22705. offsetValue = BABYLON.Color3.Black();
  22706. }
  22707. }
  22708. // Compute value
  22709. var repeatCount = (ratio / range) >> 0;
  22710. var currentFrame = returnValue ? from + ratio % range : to;
  22711. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22712. // Set value
  22713. this.setValue(currentValue);
  22714. // Check events
  22715. for (var index = 0; index < this._events.length; index++) {
  22716. if (currentFrame >= this._events[index].frame) {
  22717. var event = this._events[index];
  22718. if (!event.isDone) {
  22719. // If event should be done only once, remove it.
  22720. if (event.onlyOnce) {
  22721. this._events.splice(index, 1);
  22722. index--;
  22723. }
  22724. event.isDone = true;
  22725. event.action();
  22726. } // Don't do anything if the event has already be done.
  22727. }
  22728. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22729. // reset event, the animation is looping
  22730. this._events[index].isDone = false;
  22731. }
  22732. }
  22733. if (!returnValue) {
  22734. this._stopped = true;
  22735. }
  22736. return returnValue;
  22737. };
  22738. Animation.prototype.serialize = function () {
  22739. var serializationObject = {};
  22740. serializationObject.name = this.name;
  22741. serializationObject.property = this.targetProperty;
  22742. serializationObject.framePerSecond = this.framePerSecond;
  22743. serializationObject.dataType = this.dataType;
  22744. serializationObject.loopBehavior = this.loopMode;
  22745. var dataType = this.dataType;
  22746. serializationObject.keys = [];
  22747. var keys = this.getKeys();
  22748. for (var index = 0; index < keys.length; index++) {
  22749. var animationKey = keys[index];
  22750. var key = {};
  22751. key.frame = animationKey.frame;
  22752. switch (dataType) {
  22753. case Animation.ANIMATIONTYPE_FLOAT:
  22754. key.values = [animationKey.value];
  22755. break;
  22756. case Animation.ANIMATIONTYPE_QUATERNION:
  22757. case Animation.ANIMATIONTYPE_MATRIX:
  22758. case Animation.ANIMATIONTYPE_VECTOR3:
  22759. case Animation.ANIMATIONTYPE_COLOR3:
  22760. key.values = animationKey.value.asArray();
  22761. break;
  22762. }
  22763. serializationObject.keys.push(key);
  22764. }
  22765. serializationObject.ranges = [];
  22766. for (var name in this._ranges) {
  22767. var range = {};
  22768. range.name = name;
  22769. range.from = this._ranges[name].from;
  22770. range.to = this._ranges[name].to;
  22771. serializationObject.ranges.push(range);
  22772. }
  22773. return serializationObject;
  22774. };
  22775. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22776. get: function () {
  22777. return Animation._ANIMATIONTYPE_FLOAT;
  22778. },
  22779. enumerable: true,
  22780. configurable: true
  22781. });
  22782. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22783. get: function () {
  22784. return Animation._ANIMATIONTYPE_VECTOR3;
  22785. },
  22786. enumerable: true,
  22787. configurable: true
  22788. });
  22789. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22790. get: function () {
  22791. return Animation._ANIMATIONTYPE_VECTOR2;
  22792. },
  22793. enumerable: true,
  22794. configurable: true
  22795. });
  22796. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22797. get: function () {
  22798. return Animation._ANIMATIONTYPE_QUATERNION;
  22799. },
  22800. enumerable: true,
  22801. configurable: true
  22802. });
  22803. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22804. get: function () {
  22805. return Animation._ANIMATIONTYPE_MATRIX;
  22806. },
  22807. enumerable: true,
  22808. configurable: true
  22809. });
  22810. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22811. get: function () {
  22812. return Animation._ANIMATIONTYPE_COLOR3;
  22813. },
  22814. enumerable: true,
  22815. configurable: true
  22816. });
  22817. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22818. get: function () {
  22819. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22820. },
  22821. enumerable: true,
  22822. configurable: true
  22823. });
  22824. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22825. get: function () {
  22826. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22827. },
  22828. enumerable: true,
  22829. configurable: true
  22830. });
  22831. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22832. get: function () {
  22833. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22834. },
  22835. enumerable: true,
  22836. configurable: true
  22837. });
  22838. Animation.Parse = function (parsedAnimation) {
  22839. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22840. var dataType = parsedAnimation.dataType;
  22841. var keys = [];
  22842. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22843. var key = parsedAnimation.keys[index];
  22844. var data;
  22845. switch (dataType) {
  22846. case Animation.ANIMATIONTYPE_FLOAT:
  22847. data = key.values[0];
  22848. break;
  22849. case Animation.ANIMATIONTYPE_QUATERNION:
  22850. data = BABYLON.Quaternion.FromArray(key.values);
  22851. break;
  22852. case Animation.ANIMATIONTYPE_MATRIX:
  22853. data = BABYLON.Matrix.FromArray(key.values);
  22854. break;
  22855. case Animation.ANIMATIONTYPE_COLOR3:
  22856. data = BABYLON.Color3.FromArray(key.values);
  22857. break;
  22858. case Animation.ANIMATIONTYPE_VECTOR3:
  22859. default:
  22860. data = BABYLON.Vector3.FromArray(key.values);
  22861. break;
  22862. }
  22863. keys.push({
  22864. frame: key.frame,
  22865. value: data
  22866. });
  22867. }
  22868. animation.setKeys(keys);
  22869. if (parsedAnimation.ranges) {
  22870. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22871. data = parsedAnimation.ranges[index];
  22872. animation.createRange(data.name, data.from, data.to);
  22873. }
  22874. }
  22875. return animation;
  22876. };
  22877. Animation.AppendSerializedAnimations = function (source, destination) {
  22878. if (source.animations) {
  22879. destination.animations = [];
  22880. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22881. var animation = source.animations[animationIndex];
  22882. destination.animations.push(animation.serialize());
  22883. }
  22884. }
  22885. };
  22886. // Statics
  22887. Animation._ANIMATIONTYPE_FLOAT = 0;
  22888. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22889. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22890. Animation._ANIMATIONTYPE_MATRIX = 3;
  22891. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22892. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22893. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22894. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22895. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22896. return Animation;
  22897. })();
  22898. BABYLON.Animation = Animation;
  22899. })(BABYLON || (BABYLON = {}));
  22900. var BABYLON;
  22901. (function (BABYLON) {
  22902. var Animatable = (function () {
  22903. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22904. if (fromFrame === void 0) { fromFrame = 0; }
  22905. if (toFrame === void 0) { toFrame = 100; }
  22906. if (loopAnimation === void 0) { loopAnimation = false; }
  22907. if (speedRatio === void 0) { speedRatio = 1.0; }
  22908. this.target = target;
  22909. this.fromFrame = fromFrame;
  22910. this.toFrame = toFrame;
  22911. this.loopAnimation = loopAnimation;
  22912. this.speedRatio = speedRatio;
  22913. this.onAnimationEnd = onAnimationEnd;
  22914. this._animations = new Array();
  22915. this._paused = false;
  22916. this.animationStarted = false;
  22917. if (animations) {
  22918. this.appendAnimations(target, animations);
  22919. }
  22920. this._scene = scene;
  22921. scene._activeAnimatables.push(this);
  22922. }
  22923. // Methods
  22924. Animatable.prototype.getAnimations = function () {
  22925. return this._animations;
  22926. };
  22927. Animatable.prototype.appendAnimations = function (target, animations) {
  22928. for (var index = 0; index < animations.length; index++) {
  22929. var animation = animations[index];
  22930. animation._target = target;
  22931. this._animations.push(animation);
  22932. }
  22933. };
  22934. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22935. var animations = this._animations;
  22936. for (var index = 0; index < animations.length; index++) {
  22937. if (animations[index].targetProperty === property) {
  22938. return animations[index];
  22939. }
  22940. }
  22941. return null;
  22942. };
  22943. Animatable.prototype.reset = function () {
  22944. var animations = this._animations;
  22945. for (var index = 0; index < animations.length; index++) {
  22946. animations[index].reset();
  22947. }
  22948. this._localDelayOffset = null;
  22949. this._pausedDelay = null;
  22950. };
  22951. Animatable.prototype.goToFrame = function (frame) {
  22952. var animations = this._animations;
  22953. for (var index = 0; index < animations.length; index++) {
  22954. animations[index].goToFrame(frame);
  22955. }
  22956. };
  22957. Animatable.prototype.pause = function () {
  22958. if (this._paused) {
  22959. return;
  22960. }
  22961. this._paused = true;
  22962. };
  22963. Animatable.prototype.restart = function () {
  22964. this._paused = false;
  22965. };
  22966. Animatable.prototype.stop = function () {
  22967. var index = this._scene._activeAnimatables.indexOf(this);
  22968. if (index > -1) {
  22969. this._scene._activeAnimatables.splice(index, 1);
  22970. if (this.onAnimationEnd) {
  22971. this.onAnimationEnd();
  22972. }
  22973. }
  22974. };
  22975. Animatable.prototype._animate = function (delay) {
  22976. if (this._paused) {
  22977. this.animationStarted = false;
  22978. if (!this._pausedDelay) {
  22979. this._pausedDelay = delay;
  22980. }
  22981. return true;
  22982. }
  22983. if (!this._localDelayOffset) {
  22984. this._localDelayOffset = delay;
  22985. }
  22986. else if (this._pausedDelay) {
  22987. this._localDelayOffset += delay - this._pausedDelay;
  22988. this._pausedDelay = null;
  22989. }
  22990. // Animating
  22991. var running = false;
  22992. var animations = this._animations;
  22993. var index;
  22994. for (index = 0; index < animations.length; index++) {
  22995. var animation = animations[index];
  22996. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22997. running = running || isRunning;
  22998. }
  22999. this.animationStarted = running;
  23000. if (!running) {
  23001. // Remove from active animatables
  23002. index = this._scene._activeAnimatables.indexOf(this);
  23003. this._scene._activeAnimatables.splice(index, 1);
  23004. }
  23005. if (!running && this.onAnimationEnd) {
  23006. this.onAnimationEnd();
  23007. this.onAnimationEnd = null;
  23008. }
  23009. return running;
  23010. };
  23011. return Animatable;
  23012. })();
  23013. BABYLON.Animatable = Animatable;
  23014. })(BABYLON || (BABYLON = {}));
  23015. var BABYLON;
  23016. (function (BABYLON) {
  23017. var EasingFunction = (function () {
  23018. function EasingFunction() {
  23019. // Properties
  23020. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23021. }
  23022. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23023. get: function () {
  23024. return EasingFunction._EASINGMODE_EASEIN;
  23025. },
  23026. enumerable: true,
  23027. configurable: true
  23028. });
  23029. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23030. get: function () {
  23031. return EasingFunction._EASINGMODE_EASEOUT;
  23032. },
  23033. enumerable: true,
  23034. configurable: true
  23035. });
  23036. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23037. get: function () {
  23038. return EasingFunction._EASINGMODE_EASEINOUT;
  23039. },
  23040. enumerable: true,
  23041. configurable: true
  23042. });
  23043. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23044. var n = Math.min(Math.max(easingMode, 0), 2);
  23045. this._easingMode = n;
  23046. };
  23047. EasingFunction.prototype.getEasingMode = function () {
  23048. return this._easingMode;
  23049. };
  23050. EasingFunction.prototype.easeInCore = function (gradient) {
  23051. throw new Error('You must implement this method');
  23052. };
  23053. EasingFunction.prototype.ease = function (gradient) {
  23054. switch (this._easingMode) {
  23055. case EasingFunction.EASINGMODE_EASEIN:
  23056. return this.easeInCore(gradient);
  23057. case EasingFunction.EASINGMODE_EASEOUT:
  23058. return (1 - this.easeInCore(1 - gradient));
  23059. }
  23060. if (gradient >= 0.5) {
  23061. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23062. }
  23063. return (this.easeInCore(gradient * 2) * 0.5);
  23064. };
  23065. //Statics
  23066. EasingFunction._EASINGMODE_EASEIN = 0;
  23067. EasingFunction._EASINGMODE_EASEOUT = 1;
  23068. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23069. return EasingFunction;
  23070. })();
  23071. BABYLON.EasingFunction = EasingFunction;
  23072. var CircleEase = (function (_super) {
  23073. __extends(CircleEase, _super);
  23074. function CircleEase() {
  23075. _super.apply(this, arguments);
  23076. }
  23077. CircleEase.prototype.easeInCore = function (gradient) {
  23078. gradient = Math.max(0, Math.min(1, gradient));
  23079. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23080. };
  23081. return CircleEase;
  23082. })(EasingFunction);
  23083. BABYLON.CircleEase = CircleEase;
  23084. var BackEase = (function (_super) {
  23085. __extends(BackEase, _super);
  23086. function BackEase(amplitude) {
  23087. if (amplitude === void 0) { amplitude = 1; }
  23088. _super.call(this);
  23089. this.amplitude = amplitude;
  23090. }
  23091. BackEase.prototype.easeInCore = function (gradient) {
  23092. var num = Math.max(0, this.amplitude);
  23093. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23094. };
  23095. return BackEase;
  23096. })(EasingFunction);
  23097. BABYLON.BackEase = BackEase;
  23098. var BounceEase = (function (_super) {
  23099. __extends(BounceEase, _super);
  23100. function BounceEase(bounces, bounciness) {
  23101. if (bounces === void 0) { bounces = 3; }
  23102. if (bounciness === void 0) { bounciness = 2; }
  23103. _super.call(this);
  23104. this.bounces = bounces;
  23105. this.bounciness = bounciness;
  23106. }
  23107. BounceEase.prototype.easeInCore = function (gradient) {
  23108. var y = Math.max(0.0, this.bounces);
  23109. var bounciness = this.bounciness;
  23110. if (bounciness <= 1.0) {
  23111. bounciness = 1.001;
  23112. }
  23113. var num9 = Math.pow(bounciness, y);
  23114. var num5 = 1.0 - bounciness;
  23115. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23116. var num15 = gradient * num4;
  23117. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23118. var num3 = Math.floor(num65);
  23119. var num13 = num3 + 1.0;
  23120. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23121. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23122. var num7 = (num8 + num12) * 0.5;
  23123. var num6 = gradient - num7;
  23124. var num2 = num7 - num8;
  23125. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23126. };
  23127. return BounceEase;
  23128. })(EasingFunction);
  23129. BABYLON.BounceEase = BounceEase;
  23130. var CubicEase = (function (_super) {
  23131. __extends(CubicEase, _super);
  23132. function CubicEase() {
  23133. _super.apply(this, arguments);
  23134. }
  23135. CubicEase.prototype.easeInCore = function (gradient) {
  23136. return (gradient * gradient * gradient);
  23137. };
  23138. return CubicEase;
  23139. })(EasingFunction);
  23140. BABYLON.CubicEase = CubicEase;
  23141. var ElasticEase = (function (_super) {
  23142. __extends(ElasticEase, _super);
  23143. function ElasticEase(oscillations, springiness) {
  23144. if (oscillations === void 0) { oscillations = 3; }
  23145. if (springiness === void 0) { springiness = 3; }
  23146. _super.call(this);
  23147. this.oscillations = oscillations;
  23148. this.springiness = springiness;
  23149. }
  23150. ElasticEase.prototype.easeInCore = function (gradient) {
  23151. var num2;
  23152. var num3 = Math.max(0.0, this.oscillations);
  23153. var num = Math.max(0.0, this.springiness);
  23154. if (num == 0) {
  23155. num2 = gradient;
  23156. }
  23157. else {
  23158. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23159. }
  23160. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23161. };
  23162. return ElasticEase;
  23163. })(EasingFunction);
  23164. BABYLON.ElasticEase = ElasticEase;
  23165. var ExponentialEase = (function (_super) {
  23166. __extends(ExponentialEase, _super);
  23167. function ExponentialEase(exponent) {
  23168. if (exponent === void 0) { exponent = 2; }
  23169. _super.call(this);
  23170. this.exponent = exponent;
  23171. }
  23172. ExponentialEase.prototype.easeInCore = function (gradient) {
  23173. if (this.exponent <= 0) {
  23174. return gradient;
  23175. }
  23176. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23177. };
  23178. return ExponentialEase;
  23179. })(EasingFunction);
  23180. BABYLON.ExponentialEase = ExponentialEase;
  23181. var PowerEase = (function (_super) {
  23182. __extends(PowerEase, _super);
  23183. function PowerEase(power) {
  23184. if (power === void 0) { power = 2; }
  23185. _super.call(this);
  23186. this.power = power;
  23187. }
  23188. PowerEase.prototype.easeInCore = function (gradient) {
  23189. var y = Math.max(0.0, this.power);
  23190. return Math.pow(gradient, y);
  23191. };
  23192. return PowerEase;
  23193. })(EasingFunction);
  23194. BABYLON.PowerEase = PowerEase;
  23195. var QuadraticEase = (function (_super) {
  23196. __extends(QuadraticEase, _super);
  23197. function QuadraticEase() {
  23198. _super.apply(this, arguments);
  23199. }
  23200. QuadraticEase.prototype.easeInCore = function (gradient) {
  23201. return (gradient * gradient);
  23202. };
  23203. return QuadraticEase;
  23204. })(EasingFunction);
  23205. BABYLON.QuadraticEase = QuadraticEase;
  23206. var QuarticEase = (function (_super) {
  23207. __extends(QuarticEase, _super);
  23208. function QuarticEase() {
  23209. _super.apply(this, arguments);
  23210. }
  23211. QuarticEase.prototype.easeInCore = function (gradient) {
  23212. return (gradient * gradient * gradient * gradient);
  23213. };
  23214. return QuarticEase;
  23215. })(EasingFunction);
  23216. BABYLON.QuarticEase = QuarticEase;
  23217. var QuinticEase = (function (_super) {
  23218. __extends(QuinticEase, _super);
  23219. function QuinticEase() {
  23220. _super.apply(this, arguments);
  23221. }
  23222. QuinticEase.prototype.easeInCore = function (gradient) {
  23223. return (gradient * gradient * gradient * gradient * gradient);
  23224. };
  23225. return QuinticEase;
  23226. })(EasingFunction);
  23227. BABYLON.QuinticEase = QuinticEase;
  23228. var SineEase = (function (_super) {
  23229. __extends(SineEase, _super);
  23230. function SineEase() {
  23231. _super.apply(this, arguments);
  23232. }
  23233. SineEase.prototype.easeInCore = function (gradient) {
  23234. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23235. };
  23236. return SineEase;
  23237. })(EasingFunction);
  23238. BABYLON.SineEase = SineEase;
  23239. var BezierCurveEase = (function (_super) {
  23240. __extends(BezierCurveEase, _super);
  23241. function BezierCurveEase(x1, y1, x2, y2) {
  23242. if (x1 === void 0) { x1 = 0; }
  23243. if (y1 === void 0) { y1 = 0; }
  23244. if (x2 === void 0) { x2 = 1; }
  23245. if (y2 === void 0) { y2 = 1; }
  23246. _super.call(this);
  23247. this.x1 = x1;
  23248. this.y1 = y1;
  23249. this.x2 = x2;
  23250. this.y2 = y2;
  23251. }
  23252. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23253. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23254. };
  23255. return BezierCurveEase;
  23256. })(EasingFunction);
  23257. BABYLON.BezierCurveEase = BezierCurveEase;
  23258. })(BABYLON || (BABYLON = {}));
  23259. var BABYLON;
  23260. (function (BABYLON) {
  23261. var Bone = (function (_super) {
  23262. __extends(Bone, _super);
  23263. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23264. _super.call(this, name, skeleton.getScene());
  23265. this.name = name;
  23266. this.children = new Array();
  23267. this.animations = new Array();
  23268. this._worldTransform = new BABYLON.Matrix();
  23269. this._absoluteTransform = new BABYLON.Matrix();
  23270. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23271. this._skeleton = skeleton;
  23272. this._matrix = matrix;
  23273. this._baseMatrix = matrix;
  23274. this._restPose = restPose ? restPose : matrix.clone();
  23275. skeleton.bones.push(this);
  23276. if (parentBone) {
  23277. this._parent = parentBone;
  23278. parentBone.children.push(this);
  23279. }
  23280. else {
  23281. this._parent = null;
  23282. }
  23283. this._updateDifferenceMatrix();
  23284. }
  23285. // Members
  23286. Bone.prototype.getParent = function () {
  23287. return this._parent;
  23288. };
  23289. Bone.prototype.getLocalMatrix = function () {
  23290. return this._matrix;
  23291. };
  23292. Bone.prototype.getBaseMatrix = function () {
  23293. return this._baseMatrix;
  23294. };
  23295. Bone.prototype.getRestPose = function () {
  23296. return this._restPose;
  23297. };
  23298. Bone.prototype.returnToRest = function () {
  23299. this.updateMatrix(this._restPose.clone());
  23300. };
  23301. Bone.prototype.getWorldMatrix = function () {
  23302. return this._worldTransform;
  23303. };
  23304. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23305. return this._invertedAbsoluteTransform;
  23306. };
  23307. Bone.prototype.getAbsoluteTransform = function () {
  23308. return this._absoluteTransform;
  23309. };
  23310. // Methods
  23311. Bone.prototype.updateMatrix = function (matrix) {
  23312. this._baseMatrix = matrix.clone();
  23313. this._matrix = matrix.clone();
  23314. this._skeleton._markAsDirty();
  23315. this._updateDifferenceMatrix();
  23316. };
  23317. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23318. if (!rootMatrix) {
  23319. rootMatrix = this._baseMatrix;
  23320. }
  23321. if (this._parent) {
  23322. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23323. }
  23324. else {
  23325. this._absoluteTransform.copyFrom(rootMatrix);
  23326. }
  23327. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23328. for (var index = 0; index < this.children.length; index++) {
  23329. this.children[index]._updateDifferenceMatrix();
  23330. }
  23331. };
  23332. Bone.prototype.markAsDirty = function () {
  23333. this._currentRenderId++;
  23334. this._skeleton._markAsDirty();
  23335. };
  23336. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23337. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23338. // all animation may be coming from a library skeleton, so may need to create animation
  23339. if (this.animations.length === 0) {
  23340. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23341. }
  23342. // get animation info / verify there is such a range from the source bone
  23343. var sourceRange = source.animations[0].getRange(rangeName);
  23344. if (!sourceRange) {
  23345. return false;
  23346. }
  23347. var from = sourceRange.from;
  23348. var to = sourceRange.to;
  23349. var sourceKeys = source.animations[0].getKeys();
  23350. // rescaling prep
  23351. var sourceBoneLength = source.length;
  23352. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23353. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23354. var destKeys = this.animations[0].getKeys();
  23355. // loop vars declaration / initialization
  23356. var orig;
  23357. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23358. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23359. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23360. var mat;
  23361. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23362. orig = sourceKeys[key];
  23363. if (orig.frame >= from && orig.frame <= to) {
  23364. if (scalingReqd) {
  23365. orig.value.decompose(origScale, origRotation, origTranslation);
  23366. origTranslation.scaleInPlace(ratio);
  23367. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23368. }
  23369. else {
  23370. mat = orig.value;
  23371. }
  23372. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23373. }
  23374. }
  23375. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23376. return true;
  23377. };
  23378. return Bone;
  23379. })(BABYLON.Node);
  23380. BABYLON.Bone = Bone;
  23381. })(BABYLON || (BABYLON = {}));
  23382. var BABYLON;
  23383. (function (BABYLON) {
  23384. var Skeleton = (function () {
  23385. function Skeleton(name, id, scene) {
  23386. this.name = name;
  23387. this.id = id;
  23388. this.bones = new Array();
  23389. this.needInitialSkinMatrix = false;
  23390. this._isDirty = true;
  23391. this._meshesWithPoseMatrix = new Array();
  23392. this._identity = BABYLON.Matrix.Identity();
  23393. this._ranges = {};
  23394. this.bones = [];
  23395. this._scene = scene;
  23396. scene.skeletons.push(this);
  23397. this.prepare();
  23398. //make sure it will recalculate the matrix next time prepare is called.
  23399. this._isDirty = true;
  23400. }
  23401. // Members
  23402. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23403. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23404. return mesh._bonesTransformMatrices;
  23405. }
  23406. return this._transformMatrices;
  23407. };
  23408. Skeleton.prototype.getScene = function () {
  23409. return this._scene;
  23410. };
  23411. // Methods
  23412. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23413. // check name not already in use
  23414. if (!this._ranges[name]) {
  23415. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23416. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23417. if (this.bones[i].animations[0]) {
  23418. this.bones[i].animations[0].createRange(name, from, to);
  23419. }
  23420. }
  23421. }
  23422. };
  23423. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23424. if (deleteFrames === void 0) { deleteFrames = true; }
  23425. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23426. if (this.bones[i].animations[0]) {
  23427. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23428. }
  23429. }
  23430. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23431. };
  23432. Skeleton.prototype.getAnimationRange = function (name) {
  23433. return this._ranges[name];
  23434. };
  23435. /**
  23436. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23437. */
  23438. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23439. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23440. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23441. return false;
  23442. }
  23443. var ret = true;
  23444. var frameOffset = this._getHighestAnimationFrame() + 1;
  23445. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23446. var boneDict = {};
  23447. var sourceBones = source.bones;
  23448. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23449. boneDict[sourceBones[i].name] = sourceBones[i];
  23450. }
  23451. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23452. var boneName = this.bones[i].name;
  23453. var sourceBone = boneDict[boneName];
  23454. if (sourceBone) {
  23455. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23456. }
  23457. else {
  23458. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23459. ret = false;
  23460. }
  23461. }
  23462. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23463. var range = source.getAnimationRange(name);
  23464. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23465. return ret;
  23466. };
  23467. Skeleton.prototype.returnToRest = function () {
  23468. for (var index = 0; index < this.bones.length; index++) {
  23469. this.bones[index].returnToRest();
  23470. }
  23471. };
  23472. Skeleton.prototype._getHighestAnimationFrame = function () {
  23473. var ret = 0;
  23474. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23475. if (this.bones[i].animations[0]) {
  23476. var highest = this.bones[i].animations[0].getHighestFrame();
  23477. if (ret < highest) {
  23478. ret = highest;
  23479. }
  23480. }
  23481. }
  23482. return ret;
  23483. };
  23484. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23485. var range = this.getAnimationRange(name);
  23486. if (!range) {
  23487. return null;
  23488. }
  23489. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23490. };
  23491. Skeleton.prototype._markAsDirty = function () {
  23492. this._isDirty = true;
  23493. };
  23494. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23495. this._meshesWithPoseMatrix.push(mesh);
  23496. };
  23497. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23498. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23499. if (index > -1) {
  23500. this._meshesWithPoseMatrix.splice(index, 1);
  23501. }
  23502. };
  23503. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23504. for (var index = 0; index < this.bones.length; index++) {
  23505. var bone = this.bones[index];
  23506. var parentBone = bone.getParent();
  23507. if (parentBone) {
  23508. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23509. }
  23510. else {
  23511. if (initialSkinMatrix) {
  23512. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23513. }
  23514. else {
  23515. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23516. }
  23517. }
  23518. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23519. }
  23520. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23521. };
  23522. Skeleton.prototype.prepare = function () {
  23523. if (!this._isDirty) {
  23524. return;
  23525. }
  23526. if (this.needInitialSkinMatrix) {
  23527. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23528. var mesh = this._meshesWithPoseMatrix[index];
  23529. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23530. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23531. }
  23532. var poseMatrix = mesh.getPoseMatrix();
  23533. // Prepare bones
  23534. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23535. var bone = this.bones[boneIndex];
  23536. if (!bone.getParent()) {
  23537. var matrix = bone.getBaseMatrix();
  23538. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23539. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23540. }
  23541. }
  23542. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23543. }
  23544. }
  23545. else {
  23546. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23547. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23548. }
  23549. this._computeTransformMatrices(this._transformMatrices, null);
  23550. }
  23551. this._isDirty = false;
  23552. this._scene._activeBones += this.bones.length;
  23553. };
  23554. Skeleton.prototype.getAnimatables = function () {
  23555. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23556. this._animatables = [];
  23557. for (var index = 0; index < this.bones.length; index++) {
  23558. this._animatables.push(this.bones[index]);
  23559. }
  23560. }
  23561. return this._animatables;
  23562. };
  23563. Skeleton.prototype.clone = function (name, id) {
  23564. var result = new Skeleton(name, id || name, this._scene);
  23565. for (var index = 0; index < this.bones.length; index++) {
  23566. var source = this.bones[index];
  23567. var parentBone = null;
  23568. if (source.getParent()) {
  23569. var parentIndex = this.bones.indexOf(source.getParent());
  23570. parentBone = result.bones[parentIndex];
  23571. }
  23572. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23573. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23574. }
  23575. return result;
  23576. };
  23577. Skeleton.prototype.dispose = function () {
  23578. this._meshesWithPoseMatrix = [];
  23579. // Animations
  23580. this.getScene().stopAnimation(this);
  23581. // Remove from scene
  23582. this.getScene().removeSkeleton(this);
  23583. };
  23584. Skeleton.prototype.serialize = function () {
  23585. var serializationObject = {};
  23586. serializationObject.name = this.name;
  23587. serializationObject.id = this.id;
  23588. serializationObject.bones = [];
  23589. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23590. for (var index = 0; index < this.bones.length; index++) {
  23591. var bone = this.bones[index];
  23592. var serializedBone = {
  23593. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23594. name: bone.name,
  23595. matrix: bone.getLocalMatrix().toArray(),
  23596. rest: bone.getRestPose().toArray()
  23597. };
  23598. serializationObject.bones.push(serializedBone);
  23599. if (bone.length) {
  23600. serializedBone.length = bone.length;
  23601. }
  23602. if (bone.animations && bone.animations.length > 0) {
  23603. serializedBone.animation = bone.animations[0].serialize();
  23604. }
  23605. serializationObject.ranges = [];
  23606. for (var name in this._ranges) {
  23607. var range = {};
  23608. range.name = name;
  23609. range.from = this._ranges[name].from;
  23610. range.to = this._ranges[name].to;
  23611. serializationObject.ranges.push(range);
  23612. }
  23613. }
  23614. return serializationObject;
  23615. };
  23616. Skeleton.Parse = function (parsedSkeleton, scene) {
  23617. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23618. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23619. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23620. var parsedBone = parsedSkeleton.bones[index];
  23621. var parentBone = null;
  23622. if (parsedBone.parentBoneIndex > -1) {
  23623. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23624. }
  23625. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23626. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23627. if (parsedBone.length) {
  23628. bone.length = parsedBone.length;
  23629. }
  23630. if (parsedBone.animation) {
  23631. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23632. }
  23633. }
  23634. // placed after bones, so createAnimationRange can cascade down
  23635. if (parsedSkeleton.ranges) {
  23636. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23637. var data = parsedSkeleton.ranges[index];
  23638. skeleton.createAnimationRange(data.name, data.from, data.to);
  23639. }
  23640. }
  23641. return skeleton;
  23642. };
  23643. return Skeleton;
  23644. })();
  23645. BABYLON.Skeleton = Skeleton;
  23646. })(BABYLON || (BABYLON = {}));
  23647. var BABYLON;
  23648. (function (BABYLON) {
  23649. var PostProcess = (function () {
  23650. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23652. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23653. this.name = name;
  23654. this.width = -1;
  23655. this.height = -1;
  23656. this._reusable = false;
  23657. this._textures = new BABYLON.SmartArray(2);
  23658. this._currentRenderTextureInd = 0;
  23659. if (camera != null) {
  23660. this._camera = camera;
  23661. this._scene = camera.getScene();
  23662. camera.attachPostProcess(this);
  23663. this._engine = this._scene.getEngine();
  23664. }
  23665. else {
  23666. this._engine = engine;
  23667. }
  23668. this._renderRatio = ratio;
  23669. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23670. this._reusable = reusable || false;
  23671. this._textureType = textureType;
  23672. this._samplers = samplers || [];
  23673. this._samplers.push("textureSampler");
  23674. this._fragmentUrl = fragmentUrl;
  23675. this._parameters = parameters || [];
  23676. this.updateEffect(defines);
  23677. }
  23678. PostProcess.prototype.updateEffect = function (defines) {
  23679. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23680. };
  23681. PostProcess.prototype.isReusable = function () {
  23682. return this._reusable;
  23683. };
  23684. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23685. camera = camera || this._camera;
  23686. var scene = camera.getScene();
  23687. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23688. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23689. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23690. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23691. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23692. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23693. if (this._textures.length > 0) {
  23694. for (var i = 0; i < this._textures.length; i++) {
  23695. this._engine._releaseTexture(this._textures.data[i]);
  23696. }
  23697. this._textures.reset();
  23698. }
  23699. this.width = desiredWidth;
  23700. this.height = desiredHeight;
  23701. 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 }));
  23702. if (this._reusable) {
  23703. 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 }));
  23704. }
  23705. if (this.onSizeChanged) {
  23706. this.onSizeChanged();
  23707. }
  23708. }
  23709. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23710. if (this.onActivate) {
  23711. this.onActivate(camera);
  23712. }
  23713. // Clear
  23714. if (this.clearColor) {
  23715. this._engine.clear(this.clearColor, true, true);
  23716. }
  23717. else {
  23718. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23719. }
  23720. if (this._reusable) {
  23721. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23722. }
  23723. };
  23724. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23725. get: function () {
  23726. return this._effect.isSupported;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. PostProcess.prototype.apply = function () {
  23732. // Check
  23733. if (!this._effect.isReady())
  23734. return null;
  23735. // States
  23736. this._engine.enableEffect(this._effect);
  23737. this._engine.setState(false);
  23738. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23739. this._engine.setDepthBuffer(false);
  23740. this._engine.setDepthWrite(false);
  23741. // Texture
  23742. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23743. // Parameters
  23744. if (this.onApply) {
  23745. this.onApply(this._effect);
  23746. }
  23747. return this._effect;
  23748. };
  23749. PostProcess.prototype.dispose = function (camera) {
  23750. camera = camera || this._camera;
  23751. if (this._textures.length > 0) {
  23752. for (var i = 0; i < this._textures.length; i++) {
  23753. this._engine._releaseTexture(this._textures.data[i]);
  23754. }
  23755. this._textures.reset();
  23756. }
  23757. if (!camera) {
  23758. return;
  23759. }
  23760. camera.detachPostProcess(this);
  23761. var index = camera._postProcesses.indexOf(this);
  23762. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23763. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23764. }
  23765. };
  23766. return PostProcess;
  23767. })();
  23768. BABYLON.PostProcess = PostProcess;
  23769. })(BABYLON || (BABYLON = {}));
  23770. var BABYLON;
  23771. (function (BABYLON) {
  23772. var PostProcessManager = (function () {
  23773. function PostProcessManager(scene) {
  23774. this._vertexDeclaration = [2];
  23775. this._vertexStrideSize = 2 * 4;
  23776. this._scene = scene;
  23777. }
  23778. PostProcessManager.prototype._prepareBuffers = function () {
  23779. if (this._vertexBuffer) {
  23780. return;
  23781. }
  23782. // VBO
  23783. var vertices = [];
  23784. vertices.push(1, 1);
  23785. vertices.push(-1, 1);
  23786. vertices.push(-1, -1);
  23787. vertices.push(1, -1);
  23788. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23789. // Indices
  23790. var indices = [];
  23791. indices.push(0);
  23792. indices.push(1);
  23793. indices.push(2);
  23794. indices.push(0);
  23795. indices.push(2);
  23796. indices.push(3);
  23797. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23798. };
  23799. // Methods
  23800. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23801. var postProcesses = this._scene.activeCamera._postProcesses;
  23802. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23803. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23804. return false;
  23805. }
  23806. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23807. return true;
  23808. };
  23809. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23810. var engine = this._scene.getEngine();
  23811. for (var index = 0; index < postProcesses.length; index++) {
  23812. if (index < postProcesses.length - 1) {
  23813. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23814. }
  23815. else {
  23816. if (targetTexture) {
  23817. engine.bindFramebuffer(targetTexture);
  23818. }
  23819. else {
  23820. engine.restoreDefaultFramebuffer();
  23821. }
  23822. }
  23823. var pp = postProcesses[index];
  23824. var effect = pp.apply();
  23825. if (effect) {
  23826. if (pp.onBeforeRender) {
  23827. pp.onBeforeRender(effect);
  23828. }
  23829. // VBOs
  23830. this._prepareBuffers();
  23831. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23832. // Draw order
  23833. engine.draw(true, 0, 6);
  23834. if (pp.onAfterRender) {
  23835. pp.onAfterRender(effect);
  23836. }
  23837. }
  23838. }
  23839. // Restore depth buffer
  23840. engine.setDepthBuffer(true);
  23841. engine.setDepthWrite(true);
  23842. };
  23843. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23844. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23845. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23846. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23847. return;
  23848. }
  23849. var engine = this._scene.getEngine();
  23850. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23851. if (index < postProcessesTakenIndices.length - 1) {
  23852. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23853. }
  23854. else {
  23855. if (targetTexture) {
  23856. engine.bindFramebuffer(targetTexture, faceIndex);
  23857. }
  23858. else {
  23859. engine.restoreDefaultFramebuffer();
  23860. }
  23861. }
  23862. if (doNotPresent) {
  23863. break;
  23864. }
  23865. var pp = postProcesses[postProcessesTakenIndices[index]];
  23866. var effect = pp.apply();
  23867. if (effect) {
  23868. if (pp.onBeforeRender) {
  23869. pp.onBeforeRender(effect);
  23870. }
  23871. // VBOs
  23872. this._prepareBuffers();
  23873. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23874. // Draw order
  23875. engine.draw(true, 0, 6);
  23876. if (pp.onAfterRender) {
  23877. pp.onAfterRender(effect);
  23878. }
  23879. }
  23880. }
  23881. // Restore depth buffer
  23882. engine.setDepthBuffer(true);
  23883. engine.setDepthWrite(true);
  23884. };
  23885. PostProcessManager.prototype.dispose = function () {
  23886. if (this._vertexBuffer) {
  23887. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23888. this._vertexBuffer = null;
  23889. }
  23890. if (this._indexBuffer) {
  23891. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23892. this._indexBuffer = null;
  23893. }
  23894. };
  23895. return PostProcessManager;
  23896. })();
  23897. BABYLON.PostProcessManager = PostProcessManager;
  23898. })(BABYLON || (BABYLON = {}));
  23899. var BABYLON;
  23900. (function (BABYLON) {
  23901. var PassPostProcess = (function (_super) {
  23902. __extends(PassPostProcess, _super);
  23903. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23904. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23905. }
  23906. return PassPostProcess;
  23907. })(BABYLON.PostProcess);
  23908. BABYLON.PassPostProcess = PassPostProcess;
  23909. })(BABYLON || (BABYLON = {}));
  23910. var BABYLON;
  23911. (function (BABYLON) {
  23912. var PhysicsJoint = (function () {
  23913. function PhysicsJoint(type, jointData) {
  23914. this.type = type;
  23915. this.jointData = jointData;
  23916. jointData.nativeParams = jointData.nativeParams || {};
  23917. }
  23918. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  23919. get: function () {
  23920. return this._physicsJoint;
  23921. },
  23922. set: function (newJoint) {
  23923. if (this._physicsJoint) {
  23924. }
  23925. this._physicsJoint = newJoint;
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. //TODO check if the native joints are the same
  23931. //Joint Types
  23932. PhysicsJoint.DistanceJoint = 0;
  23933. PhysicsJoint.HingeJoint = 1;
  23934. PhysicsJoint.BallAndSocketJoint = 2;
  23935. PhysicsJoint.WheelJoint = 3;
  23936. PhysicsJoint.SliderJoint = 4;
  23937. //OIMO
  23938. PhysicsJoint.PrismaticJoint = 5;
  23939. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  23940. PhysicsJoint.UniversalJoint = 6;
  23941. PhysicsJoint.Hinge2Joint = 7;
  23942. //Cannon
  23943. //Similar to a Ball-Joint. Different in params
  23944. //TODO check!!
  23945. PhysicsJoint.PointToPointJoint = 8;
  23946. return PhysicsJoint;
  23947. })();
  23948. BABYLON.PhysicsJoint = PhysicsJoint;
  23949. })(BABYLON || (BABYLON = {}));
  23950. var BABYLON;
  23951. (function (BABYLON) {
  23952. var PhysicsImpostor = (function () {
  23953. function PhysicsImpostor(_mesh, type, _options) {
  23954. var _this = this;
  23955. if (_options === void 0) { _options = { mass: 0 }; }
  23956. this._mesh = _mesh;
  23957. this.type = type;
  23958. this._options = _options;
  23959. this._bodyUpdateRequired = false;
  23960. this._onBeforePhysicsStepCallbacks = new Array();
  23961. this._onAfterPhysicsStepCallbacks = new Array();
  23962. this._onPhysicsCollideCallbacks = [];
  23963. this._deltaPosition = BABYLON.Vector3.Zero();
  23964. this._deltaRotation = new BABYLON.Quaternion();
  23965. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  23966. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  23967. /**
  23968. * this function is executed by the physics engine.
  23969. */
  23970. this.beforeStep = function () {
  23971. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  23972. //conjugate deltaRotation
  23973. _this._tmpRotationWithDelta.copyFrom(_this._deltaRotation);
  23974. _this._tmpRotationWithDelta.multiplyInPlace(_this.mesh.rotationQuaternion);
  23975. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  23976. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  23977. func(_this);
  23978. });
  23979. };
  23980. /**
  23981. * this function is executed by the physics engine.
  23982. */
  23983. this.afterStep = function () {
  23984. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  23985. func(_this);
  23986. });
  23987. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  23988. _this.mesh.position.addInPlace(_this._deltaPosition);
  23989. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  23990. };
  23991. //event and body object due to cannon's event-based architecture.
  23992. this.onCollide = function (e) {
  23993. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  23994. if (otherImpostor) {
  23995. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  23996. return obj.otherImpostor === otherImpostor;
  23997. }).forEach(function (obj) {
  23998. obj.callback(_this, obj.otherImpostor);
  23999. });
  24000. }
  24001. };
  24002. //default options params
  24003. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24004. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24005. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24006. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24007. this._joints = [];
  24008. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24009. if (!this._mesh.parent) {
  24010. this._init();
  24011. }
  24012. }
  24013. /**
  24014. * This function will completly initialize this impostor.
  24015. * It will create a new body - but only if this mesh has no parent.
  24016. * If it has, this impostor will not be used other than to define the impostor
  24017. * of the child mesh.
  24018. */
  24019. PhysicsImpostor.prototype._init = function () {
  24020. this._physicsEngine.removeImpostor(this);
  24021. this.physicsBody = null;
  24022. this._parent = this._parent || this._getPhysicsParent();
  24023. if (!this.parent) {
  24024. this._physicsEngine.addImpostor(this);
  24025. }
  24026. };
  24027. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24028. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24029. var parentMesh = this.mesh.parent;
  24030. return parentMesh.getPhysicsImpostor();
  24031. }
  24032. return;
  24033. };
  24034. /**
  24035. * Should a new body be generated.
  24036. */
  24037. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24038. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24039. };
  24040. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24041. this.forceUpdate();
  24042. };
  24043. /**
  24044. * Force a regeneration of this or the parent's impostor's body.
  24045. * Use under cautious - This will remove all joints already implemented.
  24046. */
  24047. PhysicsImpostor.prototype.forceUpdate = function () {
  24048. this._init();
  24049. if (this.parent) {
  24050. this.parent.forceUpdate();
  24051. }
  24052. };
  24053. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24054. get: function () {
  24055. return this._mesh;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24061. /**
  24062. * Gets the body that holds this impostor. Either its own, or its parent.
  24063. */
  24064. get: function () {
  24065. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24066. },
  24067. /**
  24068. * Set the physics body. Used mainly by the physics engine/plugin
  24069. */
  24070. set: function (physicsBody) {
  24071. if (this._physicsBody) {
  24072. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24073. }
  24074. this._physicsBody = physicsBody;
  24075. this.resetUpdateFlags();
  24076. },
  24077. enumerable: true,
  24078. configurable: true
  24079. });
  24080. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24081. get: function () {
  24082. return this._parent;
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24088. this._bodyUpdateRequired = false;
  24089. };
  24090. /**
  24091. * Get a specific parametes from the options parameter.
  24092. */
  24093. PhysicsImpostor.prototype.getParam = function (paramName) {
  24094. return this._options[paramName];
  24095. };
  24096. /**
  24097. * Sets a specific parameter in the options given to the physics plugin
  24098. */
  24099. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24100. this._options[paramName] = value;
  24101. this._bodyUpdateRequired = true;
  24102. };
  24103. /**
  24104. * Set the body's velocity.
  24105. */
  24106. PhysicsImpostor.prototype.setVelocity = function (velocity) {
  24107. this._physicsEngine.getPhysicsPlugin().setVelocity(this, velocity);
  24108. };
  24109. /**
  24110. * Execute a function with the physics plugin native code.
  24111. * Provide a function the will have two variables - the world object and the physics body object.
  24112. */
  24113. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24114. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24115. };
  24116. /**
  24117. * Register a function that will be executed before the physics world is stepping forward.
  24118. */
  24119. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24120. this._onBeforePhysicsStepCallbacks.push(func);
  24121. };
  24122. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24123. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24124. if (index > -1) {
  24125. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24126. }
  24127. else {
  24128. BABYLON.Tools.Warn("Function to remove was not found");
  24129. }
  24130. };
  24131. /**
  24132. * Register a function that will be executed after the physics step
  24133. */
  24134. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24135. this._onAfterPhysicsStepCallbacks.push(func);
  24136. };
  24137. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24138. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24139. if (index > -1) {
  24140. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24141. }
  24142. else {
  24143. BABYLON.Tools.Warn("Function to remove was not found");
  24144. }
  24145. };
  24146. /**
  24147. * register a function that will be executed when this impostor collides against a different body.
  24148. */
  24149. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24150. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostor: collideAgainst });
  24151. };
  24152. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24153. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostor: collideAgainst });
  24154. if (index > -1) {
  24155. this._onPhysicsCollideCallbacks.splice(index, 1);
  24156. }
  24157. else {
  24158. BABYLON.Tools.Warn("Function to remove was not found");
  24159. }
  24160. };
  24161. /**
  24162. * Apply a force
  24163. */
  24164. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24165. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24166. };
  24167. /**
  24168. * Apply an impulse
  24169. */
  24170. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24171. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24172. };
  24173. /**
  24174. * A help function to create a joint.
  24175. */
  24176. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24177. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24178. this.addJoint(otherImpostor, joint);
  24179. };
  24180. /**
  24181. * Add a joint to this impostor with a different impostor.
  24182. */
  24183. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24184. this._joints.push({
  24185. otherImpostor: otherImpostor,
  24186. joint: joint
  24187. });
  24188. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24189. };
  24190. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24191. if (disposeChildren === void 0) { disposeChildren = true; }
  24192. this.physicsBody = null;
  24193. if (this.parent) {
  24194. this.parent.forceUpdate();
  24195. }
  24196. else {
  24197. this.mesh.getChildMeshes().forEach(function (mesh) {
  24198. if (mesh.physicsImpostor) {
  24199. if (disposeChildren) {
  24200. mesh.physicsImpostor.dispose();
  24201. mesh.physicsImpostor = null;
  24202. }
  24203. }
  24204. });
  24205. }
  24206. };
  24207. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24208. this._deltaPosition.copyFrom(position);
  24209. };
  24210. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24211. this._deltaRotation.copyFrom(rotation);
  24212. };
  24213. //Impostor types
  24214. PhysicsImpostor.NoImpostor = 0;
  24215. PhysicsImpostor.SphereImpostor = 1;
  24216. PhysicsImpostor.BoxImpostor = 2;
  24217. PhysicsImpostor.PlaneImpostor = 3;
  24218. PhysicsImpostor.MeshImpostor = 4;
  24219. PhysicsImpostor.CapsuleImpostor = 5;
  24220. PhysicsImpostor.ConeImpostor = 6;
  24221. PhysicsImpostor.CylinderImpostor = 7;
  24222. PhysicsImpostor.ConvexHullImpostor = 8;
  24223. PhysicsImpostor.HeightmapImpostor = 9;
  24224. return PhysicsImpostor;
  24225. })();
  24226. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24227. })(BABYLON || (BABYLON = {}));
  24228. var BABYLON;
  24229. (function (BABYLON) {
  24230. var PhysicsEngine = (function () {
  24231. function PhysicsEngine(gravity, _physicsPlugin) {
  24232. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24233. this._physicsPlugin = _physicsPlugin;
  24234. //new methods and parameters
  24235. this._impostors = [];
  24236. this._joints = [];
  24237. if (!this._physicsPlugin.isSupported()) {
  24238. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24239. + "Please make sure it is included.");
  24240. }
  24241. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24242. this.setGravity(gravity);
  24243. }
  24244. PhysicsEngine.prototype.setGravity = function (gravity) {
  24245. this.gravity = gravity;
  24246. this._physicsPlugin.setGravity(this.gravity);
  24247. };
  24248. PhysicsEngine.prototype.dispose = function () {
  24249. this._impostors.forEach(function (impostor) {
  24250. impostor.dispose();
  24251. });
  24252. this._physicsPlugin.dispose();
  24253. };
  24254. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24255. return this._physicsPlugin.name;
  24256. };
  24257. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24258. this._impostors.push(impostor);
  24259. //if no parent, generate the body
  24260. if (!impostor.parent) {
  24261. this._physicsPlugin.generatePhysicsBody(impostor);
  24262. }
  24263. };
  24264. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24265. var index = this._impostors.indexOf(impostor);
  24266. if (index > -1) {
  24267. var removed = this._impostors.splice(index, 1);
  24268. //Is it needed?
  24269. if (removed.length) {
  24270. //this will also remove it from the world.
  24271. removed[0].physicsBody = null;
  24272. }
  24273. }
  24274. };
  24275. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24276. var impostorJoint = {
  24277. mainImpostor: mainImpostor,
  24278. connectedImpostor: connectedImpostor,
  24279. joint: joint
  24280. };
  24281. this._joints.push(impostorJoint);
  24282. this._physicsPlugin.generateJoint(impostorJoint);
  24283. };
  24284. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24285. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24286. return (impostorJoint.connectedImpostor === connectedImpostor
  24287. && impostorJoint.joint === joint
  24288. && impostorJoint.mainImpostor === mainImpostor);
  24289. });
  24290. if (matchingJoints.length) {
  24291. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24292. }
  24293. };
  24294. /**
  24295. * Called by the scene. no need to call it.
  24296. */
  24297. PhysicsEngine.prototype._step = function (delta) {
  24298. var _this = this;
  24299. //check if any mesh has no body / requires an update
  24300. this._impostors.forEach(function (impostor) {
  24301. if (impostor.isBodyInitRequired()) {
  24302. _this._physicsPlugin.generatePhysicsBody(impostor);
  24303. }
  24304. });
  24305. if (delta > 0.1) {
  24306. delta = 0.1;
  24307. }
  24308. else if (delta <= 0) {
  24309. delta = 1.0 / 60.0;
  24310. }
  24311. this._physicsPlugin.executeStep(delta, this._impostors);
  24312. };
  24313. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24314. return this._physicsPlugin;
  24315. };
  24316. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24317. for (var i = 0; i < this._impostors.length; ++i) {
  24318. if (this._impostors[i].physicsBody === body) {
  24319. return this._impostors[i];
  24320. }
  24321. }
  24322. };
  24323. // Statics, Legacy support.
  24324. /**
  24325. * @Deprecated
  24326. *
  24327. */
  24328. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24329. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24330. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24331. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24332. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24333. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24334. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24335. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24336. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24337. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24338. PhysicsEngine.Epsilon = 0.001;
  24339. return PhysicsEngine;
  24340. })();
  24341. BABYLON.PhysicsEngine = PhysicsEngine;
  24342. })(BABYLON || (BABYLON = {}));
  24343. var BABYLON;
  24344. (function (BABYLON) {
  24345. var VertexData = (function () {
  24346. function VertexData() {
  24347. }
  24348. VertexData.prototype.set = function (data, kind) {
  24349. switch (kind) {
  24350. case BABYLON.VertexBuffer.PositionKind:
  24351. this.positions = data;
  24352. break;
  24353. case BABYLON.VertexBuffer.NormalKind:
  24354. this.normals = data;
  24355. break;
  24356. case BABYLON.VertexBuffer.UVKind:
  24357. this.uvs = data;
  24358. break;
  24359. case BABYLON.VertexBuffer.UV2Kind:
  24360. this.uvs2 = data;
  24361. break;
  24362. case BABYLON.VertexBuffer.UV3Kind:
  24363. this.uvs3 = data;
  24364. break;
  24365. case BABYLON.VertexBuffer.UV4Kind:
  24366. this.uvs4 = data;
  24367. break;
  24368. case BABYLON.VertexBuffer.UV5Kind:
  24369. this.uvs5 = data;
  24370. break;
  24371. case BABYLON.VertexBuffer.UV6Kind:
  24372. this.uvs6 = data;
  24373. break;
  24374. case BABYLON.VertexBuffer.ColorKind:
  24375. this.colors = data;
  24376. break;
  24377. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24378. this.matricesIndices = data;
  24379. break;
  24380. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24381. this.matricesWeights = data;
  24382. break;
  24383. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24384. this.matricesIndicesExtra = data;
  24385. break;
  24386. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24387. this.matricesWeightsExtra = data;
  24388. break;
  24389. }
  24390. };
  24391. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24392. this._applyTo(mesh, updatable);
  24393. };
  24394. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24395. this._applyTo(geometry, updatable);
  24396. };
  24397. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24398. this._update(mesh);
  24399. };
  24400. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24401. this._update(geometry);
  24402. };
  24403. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24404. if (this.positions) {
  24405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24406. }
  24407. if (this.normals) {
  24408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24409. }
  24410. if (this.uvs) {
  24411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24412. }
  24413. if (this.uvs2) {
  24414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24415. }
  24416. if (this.uvs3) {
  24417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24418. }
  24419. if (this.uvs4) {
  24420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24421. }
  24422. if (this.uvs5) {
  24423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24424. }
  24425. if (this.uvs6) {
  24426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24427. }
  24428. if (this.colors) {
  24429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24430. }
  24431. if (this.matricesIndices) {
  24432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24433. }
  24434. if (this.matricesWeights) {
  24435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24436. }
  24437. if (this.matricesIndicesExtra) {
  24438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24439. }
  24440. if (this.matricesWeightsExtra) {
  24441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24442. }
  24443. if (this.indices) {
  24444. meshOrGeometry.setIndices(this.indices);
  24445. }
  24446. };
  24447. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24448. if (this.positions) {
  24449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24450. }
  24451. if (this.normals) {
  24452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24453. }
  24454. if (this.uvs) {
  24455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24456. }
  24457. if (this.uvs2) {
  24458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24459. }
  24460. if (this.uvs3) {
  24461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24462. }
  24463. if (this.uvs4) {
  24464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24465. }
  24466. if (this.uvs5) {
  24467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24468. }
  24469. if (this.uvs6) {
  24470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24471. }
  24472. if (this.colors) {
  24473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24474. }
  24475. if (this.matricesIndices) {
  24476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24477. }
  24478. if (this.matricesWeights) {
  24479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24480. }
  24481. if (this.matricesIndicesExtra) {
  24482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24483. }
  24484. if (this.matricesWeightsExtra) {
  24485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24486. }
  24487. if (this.indices) {
  24488. meshOrGeometry.setIndices(this.indices);
  24489. }
  24490. };
  24491. VertexData.prototype.transform = function (matrix) {
  24492. var transformed = BABYLON.Vector3.Zero();
  24493. var index;
  24494. if (this.positions) {
  24495. var position = BABYLON.Vector3.Zero();
  24496. for (index = 0; index < this.positions.length; index += 3) {
  24497. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24498. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24499. this.positions[index] = transformed.x;
  24500. this.positions[index + 1] = transformed.y;
  24501. this.positions[index + 2] = transformed.z;
  24502. }
  24503. }
  24504. if (this.normals) {
  24505. var normal = BABYLON.Vector3.Zero();
  24506. for (index = 0; index < this.normals.length; index += 3) {
  24507. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24508. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24509. this.normals[index] = transformed.x;
  24510. this.normals[index + 1] = transformed.y;
  24511. this.normals[index + 2] = transformed.z;
  24512. }
  24513. }
  24514. };
  24515. VertexData.prototype.merge = function (other) {
  24516. if (other.indices) {
  24517. if (!this.indices) {
  24518. this.indices = [];
  24519. }
  24520. var offset = this.positions ? this.positions.length / 3 : 0;
  24521. for (var index = 0; index < other.indices.length; index++) {
  24522. //TODO check type - if Int32Array!
  24523. this.indices.push(other.indices[index] + offset);
  24524. }
  24525. }
  24526. this.positions = this._mergeElement(this.positions, other.positions);
  24527. this.normals = this._mergeElement(this.normals, other.normals);
  24528. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24529. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24530. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24531. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24532. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24533. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24534. this.colors = this._mergeElement(this.colors, other.colors);
  24535. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24536. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24537. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24538. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24539. };
  24540. VertexData.prototype._mergeElement = function (source, other) {
  24541. if (!other)
  24542. return source;
  24543. if (!source)
  24544. return other;
  24545. var len = other.length + source.length;
  24546. var isSrcTypedArray = source instanceof Float32Array;
  24547. var isOthTypedArray = other instanceof Float32Array;
  24548. // use non-loop method when the source is Float32Array
  24549. if (isSrcTypedArray) {
  24550. var ret32 = new Float32Array(len);
  24551. ret32.set(source);
  24552. ret32.set(other, source.length);
  24553. return ret32;
  24554. }
  24555. else if (!isOthTypedArray) {
  24556. return source.concat(other);
  24557. }
  24558. else {
  24559. var ret = source.slice(0); // copy source to a separate array
  24560. for (var i = 0, len = other.length; i < len; i++) {
  24561. ret.push(other[i]);
  24562. }
  24563. return ret;
  24564. }
  24565. };
  24566. VertexData.prototype.serialize = function () {
  24567. var serializationObject = this.serialize();
  24568. if (this.positions) {
  24569. serializationObject.positions = this.positions;
  24570. }
  24571. if (this.normals) {
  24572. serializationObject.normals = this.normals;
  24573. }
  24574. if (this.uvs) {
  24575. serializationObject.uvs = this.uvs;
  24576. }
  24577. if (this.uvs2) {
  24578. serializationObject.uvs2 = this.uvs2;
  24579. }
  24580. if (this.uvs3) {
  24581. serializationObject.uvs3 = this.uvs3;
  24582. }
  24583. if (this.uvs4) {
  24584. serializationObject.uvs4 = this.uvs4;
  24585. }
  24586. if (this.uvs5) {
  24587. serializationObject.uvs5 = this.uvs5;
  24588. }
  24589. if (this.uvs6) {
  24590. serializationObject.uvs6 = this.uvs6;
  24591. }
  24592. if (this.colors) {
  24593. serializationObject.colors = this.colors;
  24594. }
  24595. if (this.matricesIndices) {
  24596. serializationObject.matricesIndices = this.matricesIndices;
  24597. serializationObject.matricesIndices._isExpanded = true;
  24598. }
  24599. if (this.matricesWeights) {
  24600. serializationObject.matricesWeights = this.matricesWeights;
  24601. }
  24602. if (this.matricesIndicesExtra) {
  24603. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24604. serializationObject.matricesIndicesExtra._isExpanded = true;
  24605. }
  24606. if (this.matricesWeightsExtra) {
  24607. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24608. }
  24609. serializationObject.indices = this.indices;
  24610. return serializationObject;
  24611. };
  24612. // Statics
  24613. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24614. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24615. };
  24616. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24617. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24618. };
  24619. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24620. var result = new VertexData();
  24621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24622. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24623. }
  24624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24625. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24626. }
  24627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24628. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24629. }
  24630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24631. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24632. }
  24633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24634. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24635. }
  24636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24637. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24638. }
  24639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24640. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24641. }
  24642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24643. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24644. }
  24645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24646. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24647. }
  24648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24649. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24650. }
  24651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24652. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24653. }
  24654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24655. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24656. }
  24657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24658. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24659. }
  24660. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24661. return result;
  24662. };
  24663. VertexData.CreateRibbon = function (options) {
  24664. var pathArray = options.pathArray;
  24665. var closeArray = options.closeArray || false;
  24666. var closePath = options.closePath || false;
  24667. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24668. var offset = options.offset || defaultOffset;
  24669. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24670. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24671. var positions = [];
  24672. var indices = [];
  24673. var normals = [];
  24674. var uvs = [];
  24675. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24676. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24677. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24678. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24679. var minlg; // minimal length among all paths from pathArray
  24680. var lg = []; // array of path lengths : nb of vertex per path
  24681. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24682. var p; // path iterator
  24683. var i; // point iterator
  24684. var j; // point iterator
  24685. // if single path in pathArray
  24686. if (pathArray.length < 2) {
  24687. var ar1 = [];
  24688. var ar2 = [];
  24689. for (i = 0; i < pathArray[0].length - offset; i++) {
  24690. ar1.push(pathArray[0][i]);
  24691. ar2.push(pathArray[0][i + offset]);
  24692. }
  24693. pathArray = [ar1, ar2];
  24694. }
  24695. // positions and horizontal distances (u)
  24696. var idc = 0;
  24697. var closePathCorr = (closePath) ? 1 : 0;
  24698. var path;
  24699. var l;
  24700. minlg = pathArray[0].length;
  24701. var vectlg;
  24702. var dist;
  24703. for (p = 0; p < pathArray.length; p++) {
  24704. uTotalDistance[p] = 0;
  24705. us[p] = [0];
  24706. path = pathArray[p];
  24707. l = path.length;
  24708. minlg = (minlg < l) ? minlg : l;
  24709. j = 0;
  24710. while (j < l) {
  24711. positions.push(path[j].x, path[j].y, path[j].z);
  24712. if (j > 0) {
  24713. vectlg = path[j].subtract(path[j - 1]).length();
  24714. dist = vectlg + uTotalDistance[p];
  24715. us[p].push(dist);
  24716. uTotalDistance[p] = dist;
  24717. }
  24718. j++;
  24719. }
  24720. if (closePath) {
  24721. j--;
  24722. positions.push(path[0].x, path[0].y, path[0].z);
  24723. vectlg = path[j].subtract(path[0]).length();
  24724. dist = vectlg + uTotalDistance[p];
  24725. us[p].push(dist);
  24726. uTotalDistance[p] = dist;
  24727. }
  24728. lg[p] = l + closePathCorr;
  24729. idx[p] = idc;
  24730. idc += (l + closePathCorr);
  24731. }
  24732. // vertical distances (v)
  24733. var path1;
  24734. var path2;
  24735. var vertex1;
  24736. var vertex2;
  24737. for (i = 0; i < minlg + closePathCorr; i++) {
  24738. vTotalDistance[i] = 0;
  24739. vs[i] = [0];
  24740. for (p = 0; p < pathArray.length - 1; p++) {
  24741. path1 = pathArray[p];
  24742. path2 = pathArray[p + 1];
  24743. if (i === minlg) {
  24744. vertex1 = path1[0];
  24745. vertex2 = path2[0];
  24746. }
  24747. else {
  24748. vertex1 = path1[i];
  24749. vertex2 = path2[i];
  24750. }
  24751. vectlg = vertex2.subtract(vertex1).length();
  24752. dist = vectlg + vTotalDistance[i];
  24753. vs[i].push(dist);
  24754. vTotalDistance[i] = dist;
  24755. }
  24756. if (closeArray) {
  24757. path1 = pathArray[p];
  24758. path2 = pathArray[0];
  24759. if (i === minlg) {
  24760. vertex2 = path2[0];
  24761. }
  24762. vectlg = vertex2.subtract(vertex1).length();
  24763. dist = vectlg + vTotalDistance[i];
  24764. vTotalDistance[i] = dist;
  24765. }
  24766. }
  24767. // uvs
  24768. var u;
  24769. var v;
  24770. for (p = 0; p < pathArray.length; p++) {
  24771. for (i = 0; i < minlg + closePathCorr; i++) {
  24772. u = us[p][i] / uTotalDistance[p];
  24773. v = vs[i][p] / vTotalDistance[i];
  24774. uvs.push(u, v);
  24775. }
  24776. }
  24777. // indices
  24778. p = 0; // path index
  24779. var pi = 0; // positions array index
  24780. var l1 = lg[p] - 1; // path1 length
  24781. var l2 = lg[p + 1] - 1; // path2 length
  24782. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24783. var shft = idx[1] - idx[0]; // shift
  24784. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24785. while (pi <= min && p < path1nb) {
  24786. // 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
  24787. indices.push(pi, pi + shft, pi + 1);
  24788. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24789. pi += 1;
  24790. if (pi === min) {
  24791. p++;
  24792. if (p === lg.length - 1) {
  24793. shft = idx[0] - idx[p];
  24794. l1 = lg[p] - 1;
  24795. l2 = lg[0] - 1;
  24796. }
  24797. else {
  24798. shft = idx[p + 1] - idx[p];
  24799. l1 = lg[p] - 1;
  24800. l2 = lg[p + 1] - 1;
  24801. }
  24802. pi = idx[p];
  24803. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24804. }
  24805. }
  24806. // normals
  24807. VertexData.ComputeNormals(positions, indices, normals);
  24808. if (closePath) {
  24809. var indexFirst = 0;
  24810. var indexLast = 0;
  24811. for (p = 0; p < pathArray.length; p++) {
  24812. indexFirst = idx[p] * 3;
  24813. if (p + 1 < pathArray.length) {
  24814. indexLast = (idx[p + 1] - 1) * 3;
  24815. }
  24816. else {
  24817. indexLast = normals.length - 3;
  24818. }
  24819. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24820. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24821. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24822. normals[indexLast] = normals[indexFirst];
  24823. normals[indexLast + 1] = normals[indexFirst + 1];
  24824. normals[indexLast + 2] = normals[indexFirst + 2];
  24825. }
  24826. }
  24827. // sides
  24828. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24829. // Result
  24830. var vertexData = new VertexData();
  24831. vertexData.indices = indices;
  24832. vertexData.positions = positions;
  24833. vertexData.normals = normals;
  24834. vertexData.uvs = uvs;
  24835. if (closePath) {
  24836. vertexData._idx = idx;
  24837. }
  24838. return vertexData;
  24839. };
  24840. VertexData.CreateBox = function (options) {
  24841. var normalsSource = [
  24842. new BABYLON.Vector3(0, 0, 1),
  24843. new BABYLON.Vector3(0, 0, -1),
  24844. new BABYLON.Vector3(1, 0, 0),
  24845. new BABYLON.Vector3(-1, 0, 0),
  24846. new BABYLON.Vector3(0, 1, 0),
  24847. new BABYLON.Vector3(0, -1, 0)
  24848. ];
  24849. var indices = [];
  24850. var positions = [];
  24851. var normals = [];
  24852. var uvs = [];
  24853. var width = options.width || options.size || 1;
  24854. var height = options.height || options.size || 1;
  24855. var depth = options.depth || options.size || 1;
  24856. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24857. var faceUV = options.faceUV || new Array(6);
  24858. var faceColors = options.faceColors;
  24859. var colors = [];
  24860. // default face colors and UV if undefined
  24861. for (var f = 0; f < 6; f++) {
  24862. if (faceUV[f] === undefined) {
  24863. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24864. }
  24865. if (faceColors && faceColors[f] === undefined) {
  24866. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24867. }
  24868. }
  24869. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24870. // Create each face in turn.
  24871. for (var index = 0; index < normalsSource.length; index++) {
  24872. var normal = normalsSource[index];
  24873. // Get two vectors perpendicular to the face normal and to each other.
  24874. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24875. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24876. // Six indices (two triangles) per face.
  24877. var verticesLength = positions.length / 3;
  24878. indices.push(verticesLength);
  24879. indices.push(verticesLength + 1);
  24880. indices.push(verticesLength + 2);
  24881. indices.push(verticesLength);
  24882. indices.push(verticesLength + 2);
  24883. indices.push(verticesLength + 3);
  24884. // Four vertices per face.
  24885. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24886. positions.push(vertex.x, vertex.y, vertex.z);
  24887. normals.push(normal.x, normal.y, normal.z);
  24888. uvs.push(faceUV[index].z, faceUV[index].w);
  24889. if (faceColors) {
  24890. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24891. }
  24892. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24893. positions.push(vertex.x, vertex.y, vertex.z);
  24894. normals.push(normal.x, normal.y, normal.z);
  24895. uvs.push(faceUV[index].x, faceUV[index].w);
  24896. if (faceColors) {
  24897. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24898. }
  24899. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24900. positions.push(vertex.x, vertex.y, vertex.z);
  24901. normals.push(normal.x, normal.y, normal.z);
  24902. uvs.push(faceUV[index].x, faceUV[index].y);
  24903. if (faceColors) {
  24904. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24905. }
  24906. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24907. positions.push(vertex.x, vertex.y, vertex.z);
  24908. normals.push(normal.x, normal.y, normal.z);
  24909. uvs.push(faceUV[index].z, faceUV[index].y);
  24910. if (faceColors) {
  24911. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24912. }
  24913. }
  24914. // sides
  24915. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24916. // Result
  24917. var vertexData = new VertexData();
  24918. vertexData.indices = indices;
  24919. vertexData.positions = positions;
  24920. vertexData.normals = normals;
  24921. vertexData.uvs = uvs;
  24922. if (faceColors) {
  24923. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24924. vertexData.colors = totalColors;
  24925. }
  24926. return vertexData;
  24927. };
  24928. VertexData.CreateSphere = function (options) {
  24929. var segments = options.segments || 32;
  24930. var diameterX = options.diameterX || options.diameter || 1;
  24931. var diameterY = options.diameterY || options.diameter || 1;
  24932. var diameterZ = options.diameterZ || options.diameter || 1;
  24933. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24934. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24935. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24936. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24937. var totalZRotationSteps = 2 + segments;
  24938. var totalYRotationSteps = 2 * totalZRotationSteps;
  24939. var indices = [];
  24940. var positions = [];
  24941. var normals = [];
  24942. var uvs = [];
  24943. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24944. var normalizedZ = zRotationStep / totalZRotationSteps;
  24945. var angleZ = normalizedZ * Math.PI * slice;
  24946. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24947. var normalizedY = yRotationStep / totalYRotationSteps;
  24948. var angleY = normalizedY * Math.PI * 2 * arc;
  24949. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24950. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24951. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24952. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24953. var vertex = complete.multiply(radius);
  24954. var normal = complete.divide(radius).normalize();
  24955. positions.push(vertex.x, vertex.y, vertex.z);
  24956. normals.push(normal.x, normal.y, normal.z);
  24957. uvs.push(normalizedY, normalizedZ);
  24958. }
  24959. if (zRotationStep > 0) {
  24960. var verticesCount = positions.length / 3;
  24961. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24962. indices.push((firstIndex));
  24963. indices.push((firstIndex + 1));
  24964. indices.push(firstIndex + totalYRotationSteps + 1);
  24965. indices.push((firstIndex + totalYRotationSteps + 1));
  24966. indices.push((firstIndex + 1));
  24967. indices.push((firstIndex + totalYRotationSteps + 2));
  24968. }
  24969. }
  24970. }
  24971. // Sides
  24972. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24973. // Result
  24974. var vertexData = new VertexData();
  24975. vertexData.indices = indices;
  24976. vertexData.positions = positions;
  24977. vertexData.normals = normals;
  24978. vertexData.uvs = uvs;
  24979. return vertexData;
  24980. };
  24981. // Cylinder and cone
  24982. VertexData.CreateCylinder = function (options) {
  24983. var height = options.height || 2;
  24984. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24985. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24986. var tessellation = options.tessellation || 24;
  24987. var subdivisions = options.subdivisions || 1;
  24988. var hasRings = options.hasRings;
  24989. var enclose = options.enclose;
  24990. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24991. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24992. var faceUV = options.faceUV || new Array(3);
  24993. var faceColors = options.faceColors;
  24994. // default face colors and UV if undefined
  24995. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24996. var ringNb = (hasRings) ? subdivisions : 1;
  24997. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24998. var f;
  24999. for (f = 0; f < surfaceNb; f++) {
  25000. if (faceColors && faceColors[f] === undefined) {
  25001. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25002. }
  25003. }
  25004. for (f = 0; f < surfaceNb; f++) {
  25005. if (faceUV && faceUV[f] === undefined) {
  25006. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25007. }
  25008. }
  25009. var indices = [];
  25010. var positions = [];
  25011. var normals = [];
  25012. var uvs = [];
  25013. var colors = [];
  25014. var angle_step = Math.PI * 2 * arc / tessellation;
  25015. var angle;
  25016. var h;
  25017. var radius;
  25018. var tan = (diameterBottom - diameterTop) / 2 / height;
  25019. var ringVertex = BABYLON.Vector3.Zero();
  25020. var ringNormal = BABYLON.Vector3.Zero();
  25021. var ringFirstVertex = BABYLON.Vector3.Zero();
  25022. var ringFirstNormal = BABYLON.Vector3.Zero();
  25023. var quadNormal = BABYLON.Vector3.Zero();
  25024. var Y = BABYLON.Axis.Y;
  25025. // positions, normals, uvs
  25026. var i;
  25027. var j;
  25028. var r;
  25029. var ringIdx = 1;
  25030. var s = 1; // surface index
  25031. var cs = 0;
  25032. var v = 0;
  25033. for (i = 0; i <= subdivisions; i++) {
  25034. h = i / subdivisions;
  25035. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25036. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25037. for (r = 0; r < ringIdx; r++) {
  25038. if (hasRings) {
  25039. s += r;
  25040. }
  25041. if (enclose) {
  25042. s += 2 * r;
  25043. }
  25044. for (j = 0; j <= tessellation; j++) {
  25045. angle = j * angle_step;
  25046. // position
  25047. ringVertex.x = Math.cos(-angle) * radius;
  25048. ringVertex.y = -height / 2 + h * height;
  25049. ringVertex.z = Math.sin(-angle) * radius;
  25050. // normal
  25051. if (diameterTop === 0 && i === subdivisions) {
  25052. // if no top cap, reuse former normals
  25053. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25054. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25055. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25056. }
  25057. else {
  25058. ringNormal.x = ringVertex.x;
  25059. ringNormal.z = ringVertex.z;
  25060. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25061. ringNormal.normalize();
  25062. }
  25063. // keep first ring vertex values for enclose
  25064. if (j === 0) {
  25065. ringFirstVertex.copyFrom(ringVertex);
  25066. ringFirstNormal.copyFrom(ringNormal);
  25067. }
  25068. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25069. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25070. if (hasRings) {
  25071. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25072. }
  25073. else {
  25074. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25075. }
  25076. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25077. if (faceColors) {
  25078. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25079. }
  25080. }
  25081. // if enclose, add four vertices and their dedicated normals
  25082. if (arc !== 1 && enclose) {
  25083. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25084. positions.push(0, ringVertex.y, 0);
  25085. positions.push(0, ringVertex.y, 0);
  25086. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25087. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25088. quadNormal.normalize();
  25089. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25090. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25091. quadNormal.normalize();
  25092. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25093. if (hasRings) {
  25094. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25095. }
  25096. else {
  25097. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25098. }
  25099. uvs.push(faceUV[s + 1].x, v);
  25100. uvs.push(faceUV[s + 1].z, v);
  25101. if (hasRings) {
  25102. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25103. }
  25104. else {
  25105. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25106. }
  25107. uvs.push(faceUV[s + 2].x, v);
  25108. uvs.push(faceUV[s + 2].z, v);
  25109. if (faceColors) {
  25110. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25111. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25112. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25113. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25114. }
  25115. }
  25116. if (cs !== s) {
  25117. cs = s;
  25118. }
  25119. }
  25120. }
  25121. // indices
  25122. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25123. var s;
  25124. i = 0;
  25125. for (s = 0; s < subdivisions; s++) {
  25126. for (j = 0; j < tessellation; j++) {
  25127. var i0 = i * (e + 1) + j;
  25128. var i1 = (i + 1) * (e + 1) + j;
  25129. var i2 = i * (e + 1) + (j + 1);
  25130. var i3 = (i + 1) * (e + 1) + (j + 1);
  25131. indices.push(i0, i1, i2);
  25132. indices.push(i3, i2, i1);
  25133. }
  25134. if (arc !== 1 && enclose) {
  25135. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25136. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25137. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25138. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25139. }
  25140. i = (hasRings) ? (i + 2) : (i + 1);
  25141. }
  25142. // Caps
  25143. var createCylinderCap = function (isTop) {
  25144. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25145. if (radius === 0) {
  25146. return;
  25147. }
  25148. // Cap positions, normals & uvs
  25149. var angle;
  25150. var circleVector;
  25151. var i;
  25152. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25153. var c;
  25154. if (faceColors) {
  25155. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25156. }
  25157. // cap center
  25158. var vbase = positions.length / 3;
  25159. var offset = isTop ? height / 2 : -height / 2;
  25160. var center = new BABYLON.Vector3(0, offset, 0);
  25161. positions.push(center.x, center.y, center.z);
  25162. normals.push(0, isTop ? 1 : -1, 0);
  25163. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25164. if (faceColors) {
  25165. colors.push(c.r, c.g, c.b, c.a);
  25166. }
  25167. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25168. for (i = 0; i <= tessellation; i++) {
  25169. angle = Math.PI * 2 * i * arc / tessellation;
  25170. var cos = Math.cos(-angle);
  25171. var sin = Math.sin(-angle);
  25172. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25173. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25174. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25175. normals.push(0, isTop ? 1 : -1, 0);
  25176. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25177. if (faceColors) {
  25178. colors.push(c.r, c.g, c.b, c.a);
  25179. }
  25180. }
  25181. // Cap indices
  25182. for (i = 0; i < tessellation; i++) {
  25183. if (!isTop) {
  25184. indices.push(vbase);
  25185. indices.push(vbase + (i + 1));
  25186. indices.push(vbase + (i + 2));
  25187. }
  25188. else {
  25189. indices.push(vbase);
  25190. indices.push(vbase + (i + 2));
  25191. indices.push(vbase + (i + 1));
  25192. }
  25193. }
  25194. };
  25195. // add caps to geometry
  25196. createCylinderCap(false);
  25197. createCylinderCap(true);
  25198. // Sides
  25199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25200. var vertexData = new VertexData();
  25201. vertexData.indices = indices;
  25202. vertexData.positions = positions;
  25203. vertexData.normals = normals;
  25204. vertexData.uvs = uvs;
  25205. if (faceColors) {
  25206. vertexData.colors = colors;
  25207. }
  25208. return vertexData;
  25209. };
  25210. VertexData.CreateTorus = function (options) {
  25211. var indices = [];
  25212. var positions = [];
  25213. var normals = [];
  25214. var uvs = [];
  25215. var diameter = options.diameter || 1;
  25216. var thickness = options.thickness || 0.5;
  25217. var tessellation = options.tessellation || 16;
  25218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25219. var stride = tessellation + 1;
  25220. for (var i = 0; i <= tessellation; i++) {
  25221. var u = i / tessellation;
  25222. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25223. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25224. for (var j = 0; j <= tessellation; j++) {
  25225. var v = 1 - j / tessellation;
  25226. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25227. var dx = Math.cos(innerAngle);
  25228. var dy = Math.sin(innerAngle);
  25229. // Create a vertex.
  25230. var normal = new BABYLON.Vector3(dx, dy, 0);
  25231. var position = normal.scale(thickness / 2);
  25232. var textureCoordinate = new BABYLON.Vector2(u, v);
  25233. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25234. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25235. positions.push(position.x, position.y, position.z);
  25236. normals.push(normal.x, normal.y, normal.z);
  25237. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25238. // And create indices for two triangles.
  25239. var nextI = (i + 1) % stride;
  25240. var nextJ = (j + 1) % stride;
  25241. indices.push(i * stride + j);
  25242. indices.push(i * stride + nextJ);
  25243. indices.push(nextI * stride + j);
  25244. indices.push(i * stride + nextJ);
  25245. indices.push(nextI * stride + nextJ);
  25246. indices.push(nextI * stride + j);
  25247. }
  25248. }
  25249. // Sides
  25250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25251. // Result
  25252. var vertexData = new VertexData();
  25253. vertexData.indices = indices;
  25254. vertexData.positions = positions;
  25255. vertexData.normals = normals;
  25256. vertexData.uvs = uvs;
  25257. return vertexData;
  25258. };
  25259. VertexData.CreateLineSystem = function (options) {
  25260. var indices = [];
  25261. var positions = [];
  25262. var lines = options.lines;
  25263. var idx = 0;
  25264. for (var l = 0; l < lines.length; l++) {
  25265. var points = lines[l];
  25266. for (var index = 0; index < points.length; index++) {
  25267. positions.push(points[index].x, points[index].y, points[index].z);
  25268. if (index > 0) {
  25269. indices.push(idx - 1);
  25270. indices.push(idx);
  25271. }
  25272. idx++;
  25273. }
  25274. }
  25275. var vertexData = new VertexData();
  25276. vertexData.indices = indices;
  25277. vertexData.positions = positions;
  25278. return vertexData;
  25279. };
  25280. VertexData.CreateDashedLines = function (options) {
  25281. var dashSize = options.dashSize || 3;
  25282. var gapSize = options.gapSize || 1;
  25283. var dashNb = options.dashNb || 200;
  25284. var points = options.points;
  25285. var positions = new Array();
  25286. var indices = new Array();
  25287. var curvect = BABYLON.Vector3.Zero();
  25288. var lg = 0;
  25289. var nb = 0;
  25290. var shft = 0;
  25291. var dashshft = 0;
  25292. var curshft = 0;
  25293. var idx = 0;
  25294. var i = 0;
  25295. for (i = 0; i < points.length - 1; i++) {
  25296. points[i + 1].subtractToRef(points[i], curvect);
  25297. lg += curvect.length();
  25298. }
  25299. shft = lg / dashNb;
  25300. dashshft = dashSize * shft / (dashSize + gapSize);
  25301. for (i = 0; i < points.length - 1; i++) {
  25302. points[i + 1].subtractToRef(points[i], curvect);
  25303. nb = Math.floor(curvect.length() / shft);
  25304. curvect.normalize();
  25305. for (var j = 0; j < nb; j++) {
  25306. curshft = shft * j;
  25307. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25308. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25309. indices.push(idx, idx + 1);
  25310. idx += 2;
  25311. }
  25312. }
  25313. // Result
  25314. var vertexData = new VertexData();
  25315. vertexData.positions = positions;
  25316. vertexData.indices = indices;
  25317. return vertexData;
  25318. };
  25319. VertexData.CreateGround = function (options) {
  25320. var indices = [];
  25321. var positions = [];
  25322. var normals = [];
  25323. var uvs = [];
  25324. var row, col;
  25325. var width = options.width || 1;
  25326. var height = options.height || 1;
  25327. var subdivisions = options.subdivisions || 1;
  25328. for (row = 0; row <= subdivisions; row++) {
  25329. for (col = 0; col <= subdivisions; col++) {
  25330. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25331. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25332. positions.push(position.x, position.y, position.z);
  25333. normals.push(normal.x, normal.y, normal.z);
  25334. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25335. }
  25336. }
  25337. for (row = 0; row < subdivisions; row++) {
  25338. for (col = 0; col < subdivisions; col++) {
  25339. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25340. indices.push(col + 1 + row * (subdivisions + 1));
  25341. indices.push(col + row * (subdivisions + 1));
  25342. indices.push(col + (row + 1) * (subdivisions + 1));
  25343. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25344. indices.push(col + row * (subdivisions + 1));
  25345. }
  25346. }
  25347. // Result
  25348. var vertexData = new VertexData();
  25349. vertexData.indices = indices;
  25350. vertexData.positions = positions;
  25351. vertexData.normals = normals;
  25352. vertexData.uvs = uvs;
  25353. return vertexData;
  25354. };
  25355. VertexData.CreateTiledGround = function (options) {
  25356. var xmin = options.xmin;
  25357. var zmin = options.zmin;
  25358. var xmax = options.xmax;
  25359. var zmax = options.zmax;
  25360. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25361. var precision = options.precision || { w: 1, h: 1 };
  25362. var indices = [];
  25363. var positions = [];
  25364. var normals = [];
  25365. var uvs = [];
  25366. var row, col, tileRow, tileCol;
  25367. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25368. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25369. precision.w = (precision.w < 1) ? 1 : precision.w;
  25370. precision.h = (precision.h < 1) ? 1 : precision.h;
  25371. var tileSize = {
  25372. 'w': (xmax - xmin) / subdivisions.w,
  25373. 'h': (zmax - zmin) / subdivisions.h
  25374. };
  25375. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25376. // Indices
  25377. var base = positions.length / 3;
  25378. var rowLength = precision.w + 1;
  25379. for (row = 0; row < precision.h; row++) {
  25380. for (col = 0; col < precision.w; col++) {
  25381. var square = [
  25382. base + col + row * rowLength,
  25383. base + (col + 1) + row * rowLength,
  25384. base + (col + 1) + (row + 1) * rowLength,
  25385. base + col + (row + 1) * rowLength
  25386. ];
  25387. indices.push(square[1]);
  25388. indices.push(square[2]);
  25389. indices.push(square[3]);
  25390. indices.push(square[0]);
  25391. indices.push(square[1]);
  25392. indices.push(square[3]);
  25393. }
  25394. }
  25395. // Position, normals and uvs
  25396. var position = BABYLON.Vector3.Zero();
  25397. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25398. for (row = 0; row <= precision.h; row++) {
  25399. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25400. for (col = 0; col <= precision.w; col++) {
  25401. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25402. position.y = 0;
  25403. positions.push(position.x, position.y, position.z);
  25404. normals.push(normal.x, normal.y, normal.z);
  25405. uvs.push(col / precision.w, row / precision.h);
  25406. }
  25407. }
  25408. }
  25409. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25410. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25411. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25412. }
  25413. }
  25414. // Result
  25415. var vertexData = new VertexData();
  25416. vertexData.indices = indices;
  25417. vertexData.positions = positions;
  25418. vertexData.normals = normals;
  25419. vertexData.uvs = uvs;
  25420. return vertexData;
  25421. };
  25422. VertexData.CreateGroundFromHeightMap = function (options) {
  25423. var indices = [];
  25424. var positions = [];
  25425. var normals = [];
  25426. var uvs = [];
  25427. var row, col;
  25428. // Vertices
  25429. for (row = 0; row <= options.subdivisions; row++) {
  25430. for (col = 0; col <= options.subdivisions; col++) {
  25431. 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));
  25432. // Compute height
  25433. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25434. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25435. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25436. var r = options.buffer[pos] / 255.0;
  25437. var g = options.buffer[pos + 1] / 255.0;
  25438. var b = options.buffer[pos + 2] / 255.0;
  25439. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25440. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25441. // Add vertex
  25442. positions.push(position.x, position.y, position.z);
  25443. normals.push(0, 0, 0);
  25444. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25445. }
  25446. }
  25447. // Indices
  25448. for (row = 0; row < options.subdivisions; row++) {
  25449. for (col = 0; col < options.subdivisions; col++) {
  25450. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25451. indices.push(col + 1 + row * (options.subdivisions + 1));
  25452. indices.push(col + row * (options.subdivisions + 1));
  25453. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25454. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25455. indices.push(col + row * (options.subdivisions + 1));
  25456. }
  25457. }
  25458. // Normals
  25459. VertexData.ComputeNormals(positions, indices, normals);
  25460. // Result
  25461. var vertexData = new VertexData();
  25462. vertexData.indices = indices;
  25463. vertexData.positions = positions;
  25464. vertexData.normals = normals;
  25465. vertexData.uvs = uvs;
  25466. return vertexData;
  25467. };
  25468. VertexData.CreatePlane = function (options) {
  25469. var indices = [];
  25470. var positions = [];
  25471. var normals = [];
  25472. var uvs = [];
  25473. var width = options.width || options.size || 1;
  25474. var height = options.height || options.size || 1;
  25475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25476. // Vertices
  25477. var halfWidth = width / 2.0;
  25478. var halfHeight = height / 2.0;
  25479. positions.push(-halfWidth, -halfHeight, 0);
  25480. normals.push(0, 0, -1.0);
  25481. uvs.push(0.0, 0.0);
  25482. positions.push(halfWidth, -halfHeight, 0);
  25483. normals.push(0, 0, -1.0);
  25484. uvs.push(1.0, 0.0);
  25485. positions.push(halfWidth, halfHeight, 0);
  25486. normals.push(0, 0, -1.0);
  25487. uvs.push(1.0, 1.0);
  25488. positions.push(-halfWidth, halfHeight, 0);
  25489. normals.push(0, 0, -1.0);
  25490. uvs.push(0.0, 1.0);
  25491. // Indices
  25492. indices.push(0);
  25493. indices.push(1);
  25494. indices.push(2);
  25495. indices.push(0);
  25496. indices.push(2);
  25497. indices.push(3);
  25498. // Sides
  25499. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25500. // Result
  25501. var vertexData = new VertexData();
  25502. vertexData.indices = indices;
  25503. vertexData.positions = positions;
  25504. vertexData.normals = normals;
  25505. vertexData.uvs = uvs;
  25506. return vertexData;
  25507. };
  25508. VertexData.CreateDisc = function (options) {
  25509. var positions = [];
  25510. var indices = [];
  25511. var normals = [];
  25512. var uvs = [];
  25513. var radius = options.radius || 0.5;
  25514. var tessellation = options.tessellation || 64;
  25515. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25516. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25517. // positions and uvs
  25518. positions.push(0, 0, 0); // disc center first
  25519. uvs.push(0.5, 0.5);
  25520. var theta = Math.PI * 2 * arc;
  25521. var step = theta / tessellation;
  25522. for (var a = 0; a < theta; a += step) {
  25523. var x = Math.cos(a);
  25524. var y = Math.sin(a);
  25525. var u = (x + 1) / 2;
  25526. var v = (1 - y) / 2;
  25527. positions.push(radius * x, radius * y, 0);
  25528. uvs.push(u, v);
  25529. }
  25530. if (arc === 1) {
  25531. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25532. uvs.push(uvs[2], uvs[3]);
  25533. }
  25534. //indices
  25535. var vertexNb = positions.length / 3;
  25536. for (var i = 1; i < vertexNb - 1; i++) {
  25537. indices.push(i + 1, 0, i);
  25538. }
  25539. // result
  25540. VertexData.ComputeNormals(positions, indices, normals);
  25541. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25542. var vertexData = new VertexData();
  25543. vertexData.indices = indices;
  25544. vertexData.positions = positions;
  25545. vertexData.normals = normals;
  25546. vertexData.uvs = uvs;
  25547. return vertexData;
  25548. };
  25549. VertexData.CreateIcoSphere = function (options) {
  25550. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25551. var radius = options.radius || 1;
  25552. var flat = (options.flat === undefined) ? true : options.flat;
  25553. var subdivisions = options.subdivisions || 4;
  25554. var radiusX = options.radiusX || radius;
  25555. var radiusY = options.radiusY || radius;
  25556. var radiusZ = options.radiusZ || radius;
  25557. var t = (1 + Math.sqrt(5)) / 2;
  25558. // 12 vertex x,y,z
  25559. var ico_vertices = [
  25560. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25561. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25562. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25563. ];
  25564. // index of 3 vertex makes a face of icopshere
  25565. var ico_indices = [
  25566. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25567. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25568. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25569. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25570. ];
  25571. // vertex for uv have aliased position, not for UV
  25572. var vertices_unalias_id = [
  25573. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25574. // vertex alias
  25575. 0,
  25576. 2,
  25577. 3,
  25578. 3,
  25579. 3,
  25580. 4,
  25581. 7,
  25582. 8,
  25583. 9,
  25584. 9,
  25585. 10,
  25586. 11 // 23: B + 12
  25587. ];
  25588. // uv as integer step (not pixels !)
  25589. var ico_vertexuv = [
  25590. 5, 1, 3, 1, 6, 4, 0, 0,
  25591. 5, 3, 4, 2, 2, 2, 4, 0,
  25592. 2, 0, 1, 1, 6, 0, 6, 2,
  25593. // vertex alias (for same vertex on different faces)
  25594. 0, 4,
  25595. 3, 3,
  25596. 4, 4,
  25597. 3, 1,
  25598. 4, 2,
  25599. 4, 4,
  25600. 0, 2,
  25601. 1, 1,
  25602. 2, 2,
  25603. 3, 3,
  25604. 1, 3,
  25605. 2, 4 // 23: B + 12
  25606. ];
  25607. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25608. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25609. // First island of uv mapping
  25610. // v = 4h 3+ 2
  25611. // v = 3h 9+ 4
  25612. // v = 2h 9+ 5 B
  25613. // v = 1h 9 1 0
  25614. // v = 0h 3 8 7 A
  25615. // u = 0 1 2 3 4 5 6 *a
  25616. // Second island of uv mapping
  25617. // v = 4h 0+ B+ 4+
  25618. // v = 3h A+ 2+
  25619. // v = 2h 7+ 6 3+
  25620. // v = 1h 8+ 3+
  25621. // v = 0h
  25622. // u = 0 1 2 3 4 5 6 *a
  25623. // Face layout on texture UV mapping
  25624. // ============
  25625. // \ 4 /\ 16 / ======
  25626. // \ / \ / /\ 11 /
  25627. // \/ 7 \/ / \ /
  25628. // ======= / 10 \/
  25629. // /\ 17 /\ =======
  25630. // / \ / \ \ 15 /\
  25631. // / 8 \/ 12 \ \ / \
  25632. // ============ \/ 6 \
  25633. // \ 18 /\ ============
  25634. // \ / \ \ 5 /\ 0 /
  25635. // \/ 13 \ \ / \ /
  25636. // ======= \/ 1 \/
  25637. // =============
  25638. // /\ 19 /\ 2 /\
  25639. // / \ / \ / \
  25640. // / 14 \/ 9 \/ 3 \
  25641. // ===================
  25642. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25643. var ustep = 138 / 1024;
  25644. var vstep = 239 / 1024;
  25645. var uoffset = 60 / 1024;
  25646. var voffset = 26 / 1024;
  25647. // Second island should have margin, not to touch the first island
  25648. // avoid any borderline artefact in pixel rounding
  25649. var island_u_offset = -40 / 1024;
  25650. var island_v_offset = +20 / 1024;
  25651. // face is either island 0 or 1 :
  25652. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25653. var island = [
  25654. 0, 0, 0, 0, 1,
  25655. 0, 0, 1, 1, 0,
  25656. 0, 0, 1, 1, 0,
  25657. 0, 1, 1, 1, 0 // 15 - 19
  25658. ];
  25659. var indices = [];
  25660. var positions = [];
  25661. var normals = [];
  25662. var uvs = [];
  25663. var current_indice = 0;
  25664. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25665. var face_vertex_pos = new Array(3);
  25666. var face_vertex_uv = new Array(3);
  25667. var v012;
  25668. for (v012 = 0; v012 < 3; v012++) {
  25669. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25670. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25671. }
  25672. // create all with normals
  25673. for (var face = 0; face < 20; face++) {
  25674. // 3 vertex per face
  25675. for (v012 = 0; v012 < 3; v012++) {
  25676. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25677. var v_id = ico_indices[3 * face + v012];
  25678. // vertex have 3D position (x,y,z)
  25679. 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]);
  25680. // Normalize to get normal, then scale to radius
  25681. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25682. // uv Coordinates from vertex ID
  25683. 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);
  25684. }
  25685. // Subdivide the face (interpolate pos, norm, uv)
  25686. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25687. // - norm is linear interpolation of vertex corner normal
  25688. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25689. // - uv is linear interpolation
  25690. //
  25691. // Topology is as below for sub-divide by 2
  25692. // vertex shown as v0,v1,v2
  25693. // interp index is i1 to progress in range [v0,v1[
  25694. // interp index is i2 to progress in range [v0,v2[
  25695. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25696. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25697. //
  25698. //
  25699. // i2 v2
  25700. // ^ ^
  25701. // / / \
  25702. // / / \
  25703. // / / \
  25704. // / / (0,1) \
  25705. // / #---------\
  25706. // / / \ (0,0)'/ \
  25707. // / / \ / \
  25708. // / / \ / \
  25709. // / / (0,0) \ / (1,0) \
  25710. // / #---------#---------\
  25711. // v0 v1
  25712. //
  25713. // --------------------> i1
  25714. //
  25715. // interp of (i1,i2):
  25716. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25717. // along i1 : lerp(x0,x1, i1/(S-i2))
  25718. //
  25719. // centroid of triangle is needed to get help normal computation
  25720. // (c1,c2) are used for centroid location
  25721. var interp_vertex = function (i1, i2, c1, c2) {
  25722. // vertex is interpolated from
  25723. // - face_vertex_pos[0..2]
  25724. // - face_vertex_uv[0..2]
  25725. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25726. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25727. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25728. pos_interp.normalize();
  25729. var vertex_normal;
  25730. if (flat) {
  25731. // in flat mode, recalculate normal as face centroid normal
  25732. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25733. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25734. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25735. }
  25736. else {
  25737. // in smooth mode, recalculate normal from each single vertex position
  25738. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25739. }
  25740. // Vertex normal need correction due to X,Y,Z radius scaling
  25741. vertex_normal.x /= radiusX;
  25742. vertex_normal.y /= radiusY;
  25743. vertex_normal.z /= radiusZ;
  25744. vertex_normal.normalize();
  25745. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25746. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25747. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25748. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25749. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25750. uvs.push(uv_interp.x, uv_interp.y);
  25751. // push each vertex has member of a face
  25752. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25753. indices.push(current_indice);
  25754. current_indice++;
  25755. };
  25756. for (var i2 = 0; i2 < subdivisions; i2++) {
  25757. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25758. // face : (i1,i2) for /\ :
  25759. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25760. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25761. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25762. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25763. if (i1 + i2 + 1 < subdivisions) {
  25764. // face : (i1,i2)' for \/ :
  25765. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25766. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25767. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25768. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25769. }
  25770. }
  25771. }
  25772. }
  25773. // Sides
  25774. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25775. // Result
  25776. var vertexData = new VertexData();
  25777. vertexData.indices = indices;
  25778. vertexData.positions = positions;
  25779. vertexData.normals = normals;
  25780. vertexData.uvs = uvs;
  25781. return vertexData;
  25782. };
  25783. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25784. VertexData.CreatePolyhedron = function (options) {
  25785. // provided polyhedron types :
  25786. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25787. // 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)
  25788. var polyhedra = [];
  25789. 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]] };
  25790. 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]] };
  25791. polyhedra[2] = {
  25792. 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]],
  25793. 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]]
  25794. };
  25795. polyhedra[3] = {
  25796. 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]],
  25797. 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]]
  25798. };
  25799. polyhedra[4] = {
  25800. 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]],
  25801. 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]]
  25802. };
  25803. 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]] };
  25804. 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]] };
  25805. 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]] };
  25806. 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]] };
  25807. 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]] };
  25808. 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]] };
  25809. 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]] };
  25810. 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]] };
  25811. 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]] };
  25812. polyhedra[14] = {
  25813. 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]],
  25814. 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]]
  25815. };
  25816. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25817. var size = options.size;
  25818. var sizeX = options.sizeX || size || 1;
  25819. var sizeY = options.sizeY || size || 1;
  25820. var sizeZ = options.sizeZ || size || 1;
  25821. var data = options.custom || polyhedra[type];
  25822. var nbfaces = data.face.length;
  25823. var faceUV = options.faceUV || new Array(nbfaces);
  25824. var faceColors = options.faceColors;
  25825. var flat = (options.flat === undefined) ? true : options.flat;
  25826. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25827. var positions = [];
  25828. var indices = [];
  25829. var normals = [];
  25830. var uvs = [];
  25831. var colors = [];
  25832. var index = 0;
  25833. var faceIdx = 0; // face cursor in the array "indexes"
  25834. var indexes = [];
  25835. var i = 0;
  25836. var f = 0;
  25837. var u, v, ang, x, y, tmp;
  25838. // default face colors and UV if undefined
  25839. if (flat) {
  25840. for (f = 0; f < nbfaces; f++) {
  25841. if (faceColors && faceColors[f] === undefined) {
  25842. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25843. }
  25844. if (faceUV && faceUV[f] === undefined) {
  25845. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25846. }
  25847. }
  25848. }
  25849. if (!flat) {
  25850. for (i = 0; i < data.vertex.length; i++) {
  25851. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25852. uvs.push(0, 0);
  25853. }
  25854. for (f = 0; f < nbfaces; f++) {
  25855. for (i = 0; i < data.face[f].length - 2; i++) {
  25856. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25857. }
  25858. }
  25859. }
  25860. else {
  25861. for (f = 0; f < nbfaces; f++) {
  25862. var fl = data.face[f].length; // number of vertices of the current face
  25863. ang = 2 * Math.PI / fl;
  25864. x = 0.5 * Math.tan(ang / 2);
  25865. y = 0.5;
  25866. // positions, uvs, colors
  25867. for (i = 0; i < fl; i++) {
  25868. // positions
  25869. 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);
  25870. indexes.push(index);
  25871. index++;
  25872. // uvs
  25873. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25874. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25875. uvs.push(u, v);
  25876. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25877. y = x * Math.sin(ang) + y * Math.cos(ang);
  25878. x = tmp;
  25879. // colors
  25880. if (faceColors) {
  25881. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25882. }
  25883. }
  25884. // indices from indexes
  25885. for (i = 0; i < fl - 2; i++) {
  25886. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25887. }
  25888. faceIdx += fl;
  25889. }
  25890. }
  25891. VertexData.ComputeNormals(positions, indices, normals);
  25892. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25893. var vertexData = new VertexData();
  25894. vertexData.positions = positions;
  25895. vertexData.indices = indices;
  25896. vertexData.normals = normals;
  25897. vertexData.uvs = uvs;
  25898. if (faceColors && flat) {
  25899. vertexData.colors = colors;
  25900. }
  25901. return vertexData;
  25902. };
  25903. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25904. VertexData.CreateTorusKnot = function (options) {
  25905. var indices = [];
  25906. var positions = [];
  25907. var normals = [];
  25908. var uvs = [];
  25909. var radius = options.radius || 2;
  25910. var tube = options.tube || 0.5;
  25911. var radialSegments = options.radialSegments || 32;
  25912. var tubularSegments = options.tubularSegments || 32;
  25913. var p = options.p || 2;
  25914. var q = options.q || 3;
  25915. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25916. // Helper
  25917. var getPos = function (angle) {
  25918. var cu = Math.cos(angle);
  25919. var su = Math.sin(angle);
  25920. var quOverP = q / p * angle;
  25921. var cs = Math.cos(quOverP);
  25922. var tx = radius * (2 + cs) * 0.5 * cu;
  25923. var ty = radius * (2 + cs) * su * 0.5;
  25924. var tz = radius * Math.sin(quOverP) * 0.5;
  25925. return new BABYLON.Vector3(tx, ty, tz);
  25926. };
  25927. // Vertices
  25928. var i;
  25929. var j;
  25930. for (i = 0; i <= radialSegments; i++) {
  25931. var modI = i % radialSegments;
  25932. var u = modI / radialSegments * 2 * p * Math.PI;
  25933. var p1 = getPos(u);
  25934. var p2 = getPos(u + 0.01);
  25935. var tang = p2.subtract(p1);
  25936. var n = p2.add(p1);
  25937. var bitan = BABYLON.Vector3.Cross(tang, n);
  25938. n = BABYLON.Vector3.Cross(bitan, tang);
  25939. bitan.normalize();
  25940. n.normalize();
  25941. for (j = 0; j < tubularSegments; j++) {
  25942. var modJ = j % tubularSegments;
  25943. var v = modJ / tubularSegments * 2 * Math.PI;
  25944. var cx = -tube * Math.cos(v);
  25945. var cy = tube * Math.sin(v);
  25946. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25947. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25948. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25949. uvs.push(i / radialSegments);
  25950. uvs.push(j / tubularSegments);
  25951. }
  25952. }
  25953. for (i = 0; i < radialSegments; i++) {
  25954. for (j = 0; j < tubularSegments; j++) {
  25955. var jNext = (j + 1) % tubularSegments;
  25956. var a = i * tubularSegments + j;
  25957. var b = (i + 1) * tubularSegments + j;
  25958. var c = (i + 1) * tubularSegments + jNext;
  25959. var d = i * tubularSegments + jNext;
  25960. indices.push(d);
  25961. indices.push(b);
  25962. indices.push(a);
  25963. indices.push(d);
  25964. indices.push(c);
  25965. indices.push(b);
  25966. }
  25967. }
  25968. // Normals
  25969. VertexData.ComputeNormals(positions, indices, normals);
  25970. // Sides
  25971. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25972. // Result
  25973. var vertexData = new VertexData();
  25974. vertexData.indices = indices;
  25975. vertexData.positions = positions;
  25976. vertexData.normals = normals;
  25977. vertexData.uvs = uvs;
  25978. return vertexData;
  25979. };
  25980. // Tools
  25981. /**
  25982. * @param {any} - positions (number[] or Float32Array)
  25983. * @param {any} - indices (number[] or Uint16Array)
  25984. * @param {any} - normals (number[] or Float32Array)
  25985. */
  25986. VertexData.ComputeNormals = function (positions, indices, normals) {
  25987. var index = 0;
  25988. var p1p2x = 0.0;
  25989. var p1p2y = 0.0;
  25990. var p1p2z = 0.0;
  25991. var p3p2x = 0.0;
  25992. var p3p2y = 0.0;
  25993. var p3p2z = 0.0;
  25994. var faceNormalx = 0.0;
  25995. var faceNormaly = 0.0;
  25996. var faceNormalz = 0.0;
  25997. var length = 0.0;
  25998. var i1 = 0;
  25999. var i2 = 0;
  26000. var i3 = 0;
  26001. for (index = 0; index < positions.length; index++) {
  26002. normals[index] = 0.0;
  26003. }
  26004. // indice triplet = 1 face
  26005. var nbFaces = indices.length / 3;
  26006. for (index = 0; index < nbFaces; index++) {
  26007. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26008. i2 = indices[index * 3 + 1];
  26009. i3 = indices[index * 3 + 2];
  26010. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26011. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26012. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26013. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26014. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26015. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26016. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26017. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26018. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26019. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26020. length = (length === 0) ? 1.0 : length;
  26021. faceNormalx /= length; // normalize this normal
  26022. faceNormaly /= length;
  26023. faceNormalz /= length;
  26024. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26025. normals[i1 * 3 + 1] += faceNormaly;
  26026. normals[i1 * 3 + 2] += faceNormalz;
  26027. normals[i2 * 3] += faceNormalx;
  26028. normals[i2 * 3 + 1] += faceNormaly;
  26029. normals[i2 * 3 + 2] += faceNormalz;
  26030. normals[i3 * 3] += faceNormalx;
  26031. normals[i3 * 3 + 1] += faceNormaly;
  26032. normals[i3 * 3 + 2] += faceNormalz;
  26033. }
  26034. // last normalization of each normal
  26035. for (index = 0; index < normals.length / 3; index++) {
  26036. faceNormalx = normals[index * 3];
  26037. faceNormaly = normals[index * 3 + 1];
  26038. faceNormalz = normals[index * 3 + 2];
  26039. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26040. length = (length === 0) ? 1.0 : length;
  26041. faceNormalx /= length;
  26042. faceNormaly /= length;
  26043. faceNormalz /= length;
  26044. normals[index * 3] = faceNormalx;
  26045. normals[index * 3 + 1] = faceNormaly;
  26046. normals[index * 3 + 2] = faceNormalz;
  26047. }
  26048. };
  26049. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26050. var li = indices.length;
  26051. var ln = normals.length;
  26052. var i;
  26053. var n;
  26054. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26055. switch (sideOrientation) {
  26056. case BABYLON.Mesh.FRONTSIDE:
  26057. // nothing changed
  26058. break;
  26059. case BABYLON.Mesh.BACKSIDE:
  26060. var tmp;
  26061. // indices
  26062. for (i = 0; i < li; i += 3) {
  26063. tmp = indices[i];
  26064. indices[i] = indices[i + 2];
  26065. indices[i + 2] = tmp;
  26066. }
  26067. // normals
  26068. for (n = 0; n < ln; n++) {
  26069. normals[n] = -normals[n];
  26070. }
  26071. break;
  26072. case BABYLON.Mesh.DOUBLESIDE:
  26073. // positions
  26074. var lp = positions.length;
  26075. var l = lp / 3;
  26076. for (var p = 0; p < lp; p++) {
  26077. positions[lp + p] = positions[p];
  26078. }
  26079. // indices
  26080. for (i = 0; i < li; i += 3) {
  26081. indices[i + li] = indices[i + 2] + l;
  26082. indices[i + 1 + li] = indices[i + 1] + l;
  26083. indices[i + 2 + li] = indices[i] + l;
  26084. }
  26085. // normals
  26086. for (n = 0; n < ln; n++) {
  26087. normals[ln + n] = -normals[n];
  26088. }
  26089. // uvs
  26090. var lu = uvs.length;
  26091. for (var u = 0; u < lu; u++) {
  26092. uvs[u + lu] = uvs[u];
  26093. }
  26094. break;
  26095. }
  26096. };
  26097. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26098. var vertexData = new VertexData();
  26099. // positions
  26100. var positions = parsedVertexData.positions;
  26101. if (positions) {
  26102. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26103. }
  26104. // normals
  26105. var normals = parsedVertexData.normals;
  26106. if (normals) {
  26107. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26108. }
  26109. // uvs
  26110. var uvs = parsedVertexData.uvs;
  26111. if (uvs) {
  26112. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26113. }
  26114. // uv2s
  26115. var uv2s = parsedVertexData.uv2s;
  26116. if (uv2s) {
  26117. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26118. }
  26119. // uv3s
  26120. var uv3s = parsedVertexData.uv3s;
  26121. if (uv3s) {
  26122. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26123. }
  26124. // uv4s
  26125. var uv4s = parsedVertexData.uv4s;
  26126. if (uv4s) {
  26127. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26128. }
  26129. // uv5s
  26130. var uv5s = parsedVertexData.uv5s;
  26131. if (uv5s) {
  26132. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26133. }
  26134. // uv6s
  26135. var uv6s = parsedVertexData.uv6s;
  26136. if (uv6s) {
  26137. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26138. }
  26139. // colors
  26140. var colors = parsedVertexData.colors;
  26141. if (colors) {
  26142. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26143. }
  26144. // matricesIndices
  26145. var matricesIndices = parsedVertexData.matricesIndices;
  26146. if (matricesIndices) {
  26147. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26148. }
  26149. // matricesWeights
  26150. var matricesWeights = parsedVertexData.matricesWeights;
  26151. if (matricesWeights) {
  26152. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26153. }
  26154. // indices
  26155. var indices = parsedVertexData.indices;
  26156. if (indices) {
  26157. vertexData.indices = indices;
  26158. }
  26159. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26160. };
  26161. return VertexData;
  26162. })();
  26163. BABYLON.VertexData = VertexData;
  26164. })(BABYLON || (BABYLON = {}));
  26165. var BABYLON;
  26166. (function (BABYLON) {
  26167. var Tags = (function () {
  26168. function Tags() {
  26169. }
  26170. Tags.EnableFor = function (obj) {
  26171. obj._tags = obj._tags || {};
  26172. obj.hasTags = function () {
  26173. return Tags.HasTags(obj);
  26174. };
  26175. obj.addTags = function (tagsString) {
  26176. return Tags.AddTagsTo(obj, tagsString);
  26177. };
  26178. obj.removeTags = function (tagsString) {
  26179. return Tags.RemoveTagsFrom(obj, tagsString);
  26180. };
  26181. obj.matchesTagsQuery = function (tagsQuery) {
  26182. return Tags.MatchesQuery(obj, tagsQuery);
  26183. };
  26184. };
  26185. Tags.DisableFor = function (obj) {
  26186. delete obj._tags;
  26187. delete obj.hasTags;
  26188. delete obj.addTags;
  26189. delete obj.removeTags;
  26190. delete obj.matchesTagsQuery;
  26191. };
  26192. Tags.HasTags = function (obj) {
  26193. if (!obj._tags) {
  26194. return false;
  26195. }
  26196. return !BABYLON.Tools.IsEmpty(obj._tags);
  26197. };
  26198. Tags.GetTags = function (obj, asString) {
  26199. if (asString === void 0) { asString = true; }
  26200. if (!obj._tags) {
  26201. return null;
  26202. }
  26203. if (asString) {
  26204. var tagsArray = [];
  26205. for (var tag in obj._tags) {
  26206. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26207. tagsArray.push(tag);
  26208. }
  26209. }
  26210. return tagsArray.join(" ");
  26211. }
  26212. else {
  26213. return obj._tags;
  26214. }
  26215. };
  26216. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26217. // a tag cannot start with '||', '&&', and '!'
  26218. // it cannot contain whitespaces
  26219. Tags.AddTagsTo = function (obj, tagsString) {
  26220. if (!tagsString) {
  26221. return;
  26222. }
  26223. if (typeof tagsString !== "string") {
  26224. return;
  26225. }
  26226. var tags = tagsString.split(" ");
  26227. for (var t in tags) {
  26228. Tags._AddTagTo(obj, tags[t]);
  26229. }
  26230. };
  26231. Tags._AddTagTo = function (obj, tag) {
  26232. tag = tag.trim();
  26233. if (tag === "" || tag === "true" || tag === "false") {
  26234. return;
  26235. }
  26236. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26237. return;
  26238. }
  26239. Tags.EnableFor(obj);
  26240. obj._tags[tag] = true;
  26241. };
  26242. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26243. if (!Tags.HasTags(obj)) {
  26244. return;
  26245. }
  26246. var tags = tagsString.split(" ");
  26247. for (var t in tags) {
  26248. Tags._RemoveTagFrom(obj, tags[t]);
  26249. }
  26250. };
  26251. Tags._RemoveTagFrom = function (obj, tag) {
  26252. delete obj._tags[tag];
  26253. };
  26254. Tags.MatchesQuery = function (obj, tagsQuery) {
  26255. if (tagsQuery === undefined) {
  26256. return true;
  26257. }
  26258. if (tagsQuery === "") {
  26259. return Tags.HasTags(obj);
  26260. }
  26261. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26262. };
  26263. return Tags;
  26264. })();
  26265. BABYLON.Tags = Tags;
  26266. })(BABYLON || (BABYLON = {}));
  26267. var BABYLON;
  26268. (function (BABYLON) {
  26269. var Internals;
  26270. (function (Internals) {
  26271. var AndOrNotEvaluator = (function () {
  26272. function AndOrNotEvaluator() {
  26273. }
  26274. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26275. if (!query.match(/\([^\(\)]*\)/g)) {
  26276. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26277. }
  26278. else {
  26279. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26280. // remove parenthesis
  26281. r = r.slice(1, r.length - 1);
  26282. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26283. });
  26284. }
  26285. if (query === "true") {
  26286. return true;
  26287. }
  26288. if (query === "false") {
  26289. return false;
  26290. }
  26291. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26292. };
  26293. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26294. evaluateCallback = evaluateCallback || (function (r) {
  26295. return r === "true" ? true : false;
  26296. });
  26297. var result;
  26298. var or = parenthesisContent.split("||");
  26299. for (var i in or) {
  26300. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26301. var and = ori.split("&&");
  26302. if (and.length > 1) {
  26303. for (var j = 0; j < and.length; ++j) {
  26304. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26305. if (andj !== "true" && andj !== "false") {
  26306. if (andj[0] === "!") {
  26307. result = !evaluateCallback(andj.substring(1));
  26308. }
  26309. else {
  26310. result = evaluateCallback(andj);
  26311. }
  26312. }
  26313. else {
  26314. result = andj === "true" ? true : false;
  26315. }
  26316. if (!result) {
  26317. ori = "false";
  26318. break;
  26319. }
  26320. }
  26321. }
  26322. if (result || ori === "true") {
  26323. result = true;
  26324. break;
  26325. }
  26326. // result equals false (or undefined)
  26327. if (ori !== "true" && ori !== "false") {
  26328. if (ori[0] === "!") {
  26329. result = !evaluateCallback(ori.substring(1));
  26330. }
  26331. else {
  26332. result = evaluateCallback(ori);
  26333. }
  26334. }
  26335. else {
  26336. result = ori === "true" ? true : false;
  26337. }
  26338. }
  26339. // the whole parenthesis scope is replaced by 'true' or 'false'
  26340. return result ? "true" : "false";
  26341. };
  26342. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26343. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26344. // remove whitespaces
  26345. r = r.replace(/[\s]/g, function () { return ""; });
  26346. return r.length % 2 ? "!" : "";
  26347. });
  26348. booleanString = booleanString.trim();
  26349. if (booleanString === "!true") {
  26350. booleanString = "false";
  26351. }
  26352. else if (booleanString === "!false") {
  26353. booleanString = "true";
  26354. }
  26355. return booleanString;
  26356. };
  26357. return AndOrNotEvaluator;
  26358. })();
  26359. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26360. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26361. })(BABYLON || (BABYLON = {}));
  26362. var BABYLON;
  26363. (function (BABYLON) {
  26364. var PostProcessRenderPass = (function () {
  26365. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26366. this._enabled = true;
  26367. this._refCount = 0;
  26368. this._name = name;
  26369. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26370. this.setRenderList(renderList);
  26371. this._renderTexture.onBeforeRender = beforeRender;
  26372. this._renderTexture.onAfterRender = afterRender;
  26373. this._scene = scene;
  26374. this._renderList = renderList;
  26375. }
  26376. // private
  26377. PostProcessRenderPass.prototype._incRefCount = function () {
  26378. if (this._refCount === 0) {
  26379. this._scene.customRenderTargets.push(this._renderTexture);
  26380. }
  26381. return ++this._refCount;
  26382. };
  26383. PostProcessRenderPass.prototype._decRefCount = function () {
  26384. this._refCount--;
  26385. if (this._refCount <= 0) {
  26386. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26387. }
  26388. return this._refCount;
  26389. };
  26390. PostProcessRenderPass.prototype._update = function () {
  26391. this.setRenderList(this._renderList);
  26392. };
  26393. // public
  26394. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26395. this._renderTexture.renderList = renderList;
  26396. };
  26397. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26398. return this._renderTexture;
  26399. };
  26400. return PostProcessRenderPass;
  26401. })();
  26402. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26403. })(BABYLON || (BABYLON = {}));
  26404. var BABYLON;
  26405. (function (BABYLON) {
  26406. var PostProcessRenderEffect = (function () {
  26407. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26408. this._engine = engine;
  26409. this._name = name;
  26410. this._singleInstance = singleInstance || true;
  26411. this._getPostProcess = getPostProcess;
  26412. this._cameras = [];
  26413. this._indicesForCamera = [];
  26414. this._postProcesses = {};
  26415. this._renderPasses = {};
  26416. this._renderEffectAsPasses = {};
  26417. }
  26418. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26419. get: function () {
  26420. for (var index in this._postProcesses) {
  26421. if (!this._postProcesses[index].isSupported) {
  26422. return false;
  26423. }
  26424. }
  26425. return true;
  26426. },
  26427. enumerable: true,
  26428. configurable: true
  26429. });
  26430. PostProcessRenderEffect.prototype._update = function () {
  26431. for (var renderPassName in this._renderPasses) {
  26432. this._renderPasses[renderPassName]._update();
  26433. }
  26434. };
  26435. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26436. this._renderPasses[renderPass._name] = renderPass;
  26437. this._linkParameters();
  26438. };
  26439. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26440. delete this._renderPasses[renderPass._name];
  26441. this._linkParameters();
  26442. };
  26443. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26444. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26445. this._linkParameters();
  26446. };
  26447. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26448. for (var renderPassName in this._renderPasses) {
  26449. if (renderPassName === passName) {
  26450. return this._renderPasses[passName];
  26451. }
  26452. }
  26453. };
  26454. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26455. this._renderPasses = {};
  26456. this._linkParameters();
  26457. };
  26458. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26459. var cameraKey;
  26460. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26461. for (var i = 0; i < _cam.length; i++) {
  26462. var camera = _cam[i];
  26463. var cameraName = camera.name;
  26464. if (this._singleInstance) {
  26465. cameraKey = 0;
  26466. }
  26467. else {
  26468. cameraKey = cameraName;
  26469. }
  26470. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26471. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26472. if (!this._indicesForCamera[cameraName]) {
  26473. this._indicesForCamera[cameraName] = [];
  26474. }
  26475. this._indicesForCamera[cameraName].push(index);
  26476. if (this._cameras.indexOf(camera) === -1) {
  26477. this._cameras[cameraName] = camera;
  26478. }
  26479. for (var passName in this._renderPasses) {
  26480. this._renderPasses[passName]._incRefCount();
  26481. }
  26482. }
  26483. this._linkParameters();
  26484. };
  26485. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26486. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26487. for (var i = 0; i < _cam.length; i++) {
  26488. var camera = _cam[i];
  26489. var cameraName = camera.name;
  26490. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26491. var index = this._cameras.indexOf(cameraName);
  26492. this._indicesForCamera.splice(index, 1);
  26493. this._cameras.splice(index, 1);
  26494. for (var passName in this._renderPasses) {
  26495. this._renderPasses[passName]._decRefCount();
  26496. }
  26497. }
  26498. };
  26499. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26500. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26501. for (var i = 0; i < _cam.length; i++) {
  26502. var camera = _cam[i];
  26503. var cameraName = camera.name;
  26504. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26505. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26506. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26507. }
  26508. }
  26509. for (var passName in this._renderPasses) {
  26510. this._renderPasses[passName]._incRefCount();
  26511. }
  26512. }
  26513. };
  26514. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26515. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26516. for (var i = 0; i < _cam.length; i++) {
  26517. var camera = _cam[i];
  26518. var cameraName = camera.Name;
  26519. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26520. for (var passName in this._renderPasses) {
  26521. this._renderPasses[passName]._decRefCount();
  26522. }
  26523. }
  26524. };
  26525. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26526. if (this._singleInstance) {
  26527. return this._postProcesses[0];
  26528. }
  26529. else {
  26530. return this._postProcesses[camera.name];
  26531. }
  26532. };
  26533. PostProcessRenderEffect.prototype._linkParameters = function () {
  26534. var _this = this;
  26535. for (var index in this._postProcesses) {
  26536. if (this.applyParameters) {
  26537. this.applyParameters(this._postProcesses[index]);
  26538. }
  26539. this._postProcesses[index].onBeforeRender = function (effect) {
  26540. _this._linkTextures(effect);
  26541. };
  26542. }
  26543. };
  26544. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26545. for (var renderPassName in this._renderPasses) {
  26546. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26547. }
  26548. for (var renderEffectName in this._renderEffectAsPasses) {
  26549. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26550. }
  26551. };
  26552. return PostProcessRenderEffect;
  26553. })();
  26554. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26555. })(BABYLON || (BABYLON = {}));
  26556. var BABYLON;
  26557. (function (BABYLON) {
  26558. var PostProcessRenderPipeline = (function () {
  26559. function PostProcessRenderPipeline(engine, name) {
  26560. this._engine = engine;
  26561. this._name = name;
  26562. this._renderEffects = {};
  26563. this._renderEffectsForIsolatedPass = {};
  26564. this._cameras = [];
  26565. }
  26566. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26567. get: function () {
  26568. for (var renderEffectName in this._renderEffects) {
  26569. if (!this._renderEffects[renderEffectName].isSupported) {
  26570. return false;
  26571. }
  26572. }
  26573. return true;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26579. this._renderEffects[renderEffect._name] = renderEffect;
  26580. };
  26581. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26582. var renderEffects = this._renderEffects[renderEffectName];
  26583. if (!renderEffects) {
  26584. return;
  26585. }
  26586. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26587. };
  26588. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26589. var renderEffects = this._renderEffects[renderEffectName];
  26590. if (!renderEffects) {
  26591. return;
  26592. }
  26593. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26594. };
  26595. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26596. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26597. var indicesToDelete = [];
  26598. var i;
  26599. for (i = 0; i < _cam.length; i++) {
  26600. var camera = _cam[i];
  26601. var cameraName = camera.name;
  26602. if (this._cameras.indexOf(camera) === -1) {
  26603. this._cameras[cameraName] = camera;
  26604. }
  26605. else if (unique) {
  26606. indicesToDelete.push(i);
  26607. }
  26608. }
  26609. for (i = 0; i < indicesToDelete.length; i++) {
  26610. cameras.splice(indicesToDelete[i], 1);
  26611. }
  26612. for (var renderEffectName in this._renderEffects) {
  26613. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26614. }
  26615. };
  26616. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26617. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26618. for (var renderEffectName in this._renderEffects) {
  26619. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26620. }
  26621. for (var i = 0; i < _cam.length; i++) {
  26622. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26623. }
  26624. };
  26625. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26626. var _this = this;
  26627. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26628. var pass = null;
  26629. var renderEffectName;
  26630. for (renderEffectName in this._renderEffects) {
  26631. pass = this._renderEffects[renderEffectName].getPass(passName);
  26632. if (pass != null) {
  26633. break;
  26634. }
  26635. }
  26636. if (pass === null) {
  26637. return;
  26638. }
  26639. for (renderEffectName in this._renderEffects) {
  26640. this._renderEffects[renderEffectName]._disable(_cam);
  26641. }
  26642. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26643. for (var i = 0; i < _cam.length; i++) {
  26644. var camera = _cam[i];
  26645. var cameraName = camera.name;
  26646. 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); });
  26647. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26648. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26649. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26650. }
  26651. };
  26652. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26653. var _this = this;
  26654. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26655. for (var i = 0; i < _cam.length; i++) {
  26656. var camera = _cam[i];
  26657. var cameraName = camera.name;
  26658. 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); });
  26659. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26660. }
  26661. for (var renderEffectName in this._renderEffects) {
  26662. this._renderEffects[renderEffectName]._enable(_cam);
  26663. }
  26664. };
  26665. PostProcessRenderPipeline.prototype._update = function () {
  26666. for (var renderEffectName in this._renderEffects) {
  26667. this._renderEffects[renderEffectName]._update();
  26668. }
  26669. for (var i = 0; i < this._cameras.length; i++) {
  26670. var cameraName = this._cameras[i].name;
  26671. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26672. this._renderEffectsForIsolatedPass[cameraName]._update();
  26673. }
  26674. }
  26675. };
  26676. PostProcessRenderPipeline.prototype.dispose = function () {
  26677. // Must be implemented by children
  26678. };
  26679. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26680. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26681. return PostProcessRenderPipeline;
  26682. })();
  26683. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26684. })(BABYLON || (BABYLON = {}));
  26685. var BABYLON;
  26686. (function (BABYLON) {
  26687. var PostProcessRenderPipelineManager = (function () {
  26688. function PostProcessRenderPipelineManager() {
  26689. this._renderPipelines = {};
  26690. }
  26691. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26692. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26693. };
  26694. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26695. var renderPipeline = this._renderPipelines[renderPipelineName];
  26696. if (!renderPipeline) {
  26697. return;
  26698. }
  26699. renderPipeline._attachCameras(cameras, unique);
  26700. };
  26701. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26702. var renderPipeline = this._renderPipelines[renderPipelineName];
  26703. if (!renderPipeline) {
  26704. return;
  26705. }
  26706. renderPipeline._detachCameras(cameras);
  26707. };
  26708. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26709. var renderPipeline = this._renderPipelines[renderPipelineName];
  26710. if (!renderPipeline) {
  26711. return;
  26712. }
  26713. renderPipeline._enableEffect(renderEffectName, cameras);
  26714. };
  26715. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26716. var renderPipeline = this._renderPipelines[renderPipelineName];
  26717. if (!renderPipeline) {
  26718. return;
  26719. }
  26720. renderPipeline._disableEffect(renderEffectName, cameras);
  26721. };
  26722. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26723. var renderPipeline = this._renderPipelines[renderPipelineName];
  26724. if (!renderPipeline) {
  26725. return;
  26726. }
  26727. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26728. };
  26729. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26730. var renderPipeline = this._renderPipelines[renderPipelineName];
  26731. if (!renderPipeline) {
  26732. return;
  26733. }
  26734. renderPipeline._disableDisplayOnlyPass(cameras);
  26735. };
  26736. PostProcessRenderPipelineManager.prototype.update = function () {
  26737. for (var renderPipelineName in this._renderPipelines) {
  26738. var pipeline = this._renderPipelines[renderPipelineName];
  26739. if (!pipeline.isSupported) {
  26740. pipeline.dispose();
  26741. delete this._renderPipelines[renderPipelineName];
  26742. }
  26743. else {
  26744. pipeline._update();
  26745. }
  26746. }
  26747. };
  26748. return PostProcessRenderPipelineManager;
  26749. })();
  26750. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26751. })(BABYLON || (BABYLON = {}));
  26752. var BABYLON;
  26753. (function (BABYLON) {
  26754. var BoundingBoxRenderer = (function () {
  26755. function BoundingBoxRenderer(scene) {
  26756. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26757. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26758. this.showBackLines = true;
  26759. this.renderList = new BABYLON.SmartArray(32);
  26760. this._scene = scene;
  26761. }
  26762. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26763. if (this._colorShader) {
  26764. return;
  26765. }
  26766. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26767. attributes: ["position"],
  26768. uniforms: ["worldViewProjection", "color"]
  26769. });
  26770. var engine = this._scene.getEngine();
  26771. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26772. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26773. 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]);
  26774. };
  26775. BoundingBoxRenderer.prototype.reset = function () {
  26776. this.renderList.reset();
  26777. };
  26778. BoundingBoxRenderer.prototype.render = function () {
  26779. if (this.renderList.length === 0) {
  26780. return;
  26781. }
  26782. this._prepareRessources();
  26783. if (!this._colorShader.isReady()) {
  26784. return;
  26785. }
  26786. var engine = this._scene.getEngine();
  26787. engine.setDepthWrite(false);
  26788. this._colorShader._preBind();
  26789. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26790. var boundingBox = this.renderList.data[boundingBoxIndex];
  26791. var min = boundingBox.minimum;
  26792. var max = boundingBox.maximum;
  26793. var diff = max.subtract(min);
  26794. var median = min.add(diff.scale(0.5));
  26795. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26796. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26797. .multiply(boundingBox.getWorldMatrix());
  26798. // VBOs
  26799. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26800. if (this.showBackLines) {
  26801. // Back
  26802. engine.setDepthFunctionToGreaterOrEqual();
  26803. this._scene.resetCachedMaterial();
  26804. this._colorShader.setColor4("color", this.backColor.toColor4());
  26805. this._colorShader.bind(worldMatrix);
  26806. // Draw order
  26807. engine.draw(false, 0, 24);
  26808. }
  26809. // Front
  26810. engine.setDepthFunctionToLess();
  26811. this._scene.resetCachedMaterial();
  26812. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26813. this._colorShader.bind(worldMatrix);
  26814. // Draw order
  26815. engine.draw(false, 0, 24);
  26816. }
  26817. this._colorShader.unbind();
  26818. engine.setDepthFunctionToLessOrEqual();
  26819. engine.setDepthWrite(true);
  26820. };
  26821. BoundingBoxRenderer.prototype.dispose = function () {
  26822. if (!this._colorShader) {
  26823. return;
  26824. }
  26825. this._colorShader.dispose();
  26826. this._vb.dispose();
  26827. this._scene.getEngine()._releaseBuffer(this._ib);
  26828. };
  26829. return BoundingBoxRenderer;
  26830. })();
  26831. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26832. })(BABYLON || (BABYLON = {}));
  26833. var BABYLON;
  26834. (function (BABYLON) {
  26835. var Condition = (function () {
  26836. function Condition(actionManager) {
  26837. this._actionManager = actionManager;
  26838. }
  26839. Condition.prototype.isValid = function () {
  26840. return true;
  26841. };
  26842. Condition.prototype._getProperty = function (propertyPath) {
  26843. return this._actionManager._getProperty(propertyPath);
  26844. };
  26845. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26846. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26847. };
  26848. return Condition;
  26849. })();
  26850. BABYLON.Condition = Condition;
  26851. var ValueCondition = (function (_super) {
  26852. __extends(ValueCondition, _super);
  26853. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26854. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26855. _super.call(this, actionManager);
  26856. this.propertyPath = propertyPath;
  26857. this.value = value;
  26858. this.operator = operator;
  26859. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26860. this._property = this._getProperty(this.propertyPath);
  26861. }
  26862. Object.defineProperty(ValueCondition, "IsEqual", {
  26863. get: function () {
  26864. return ValueCondition._IsEqual;
  26865. },
  26866. enumerable: true,
  26867. configurable: true
  26868. });
  26869. Object.defineProperty(ValueCondition, "IsDifferent", {
  26870. get: function () {
  26871. return ValueCondition._IsDifferent;
  26872. },
  26873. enumerable: true,
  26874. configurable: true
  26875. });
  26876. Object.defineProperty(ValueCondition, "IsGreater", {
  26877. get: function () {
  26878. return ValueCondition._IsGreater;
  26879. },
  26880. enumerable: true,
  26881. configurable: true
  26882. });
  26883. Object.defineProperty(ValueCondition, "IsLesser", {
  26884. get: function () {
  26885. return ValueCondition._IsLesser;
  26886. },
  26887. enumerable: true,
  26888. configurable: true
  26889. });
  26890. // Methods
  26891. ValueCondition.prototype.isValid = function () {
  26892. switch (this.operator) {
  26893. case ValueCondition.IsGreater:
  26894. return this._target[this._property] > this.value;
  26895. case ValueCondition.IsLesser:
  26896. return this._target[this._property] < this.value;
  26897. case ValueCondition.IsEqual:
  26898. case ValueCondition.IsDifferent:
  26899. var check;
  26900. if (this.value.equals) {
  26901. check = this.value.equals(this._target[this._property]);
  26902. }
  26903. else {
  26904. check = this.value === this._target[this._property];
  26905. }
  26906. return this.operator === ValueCondition.IsEqual ? check : !check;
  26907. }
  26908. return false;
  26909. };
  26910. // Statics
  26911. ValueCondition._IsEqual = 0;
  26912. ValueCondition._IsDifferent = 1;
  26913. ValueCondition._IsGreater = 2;
  26914. ValueCondition._IsLesser = 3;
  26915. return ValueCondition;
  26916. })(Condition);
  26917. BABYLON.ValueCondition = ValueCondition;
  26918. var PredicateCondition = (function (_super) {
  26919. __extends(PredicateCondition, _super);
  26920. function PredicateCondition(actionManager, predicate) {
  26921. _super.call(this, actionManager);
  26922. this.predicate = predicate;
  26923. }
  26924. PredicateCondition.prototype.isValid = function () {
  26925. return this.predicate();
  26926. };
  26927. return PredicateCondition;
  26928. })(Condition);
  26929. BABYLON.PredicateCondition = PredicateCondition;
  26930. var StateCondition = (function (_super) {
  26931. __extends(StateCondition, _super);
  26932. function StateCondition(actionManager, target, value) {
  26933. _super.call(this, actionManager);
  26934. this.value = value;
  26935. this._target = target;
  26936. }
  26937. // Methods
  26938. StateCondition.prototype.isValid = function () {
  26939. return this._target.state === this.value;
  26940. };
  26941. return StateCondition;
  26942. })(Condition);
  26943. BABYLON.StateCondition = StateCondition;
  26944. })(BABYLON || (BABYLON = {}));
  26945. var BABYLON;
  26946. (function (BABYLON) {
  26947. var Action = (function () {
  26948. function Action(triggerOptions, condition) {
  26949. this.triggerOptions = triggerOptions;
  26950. if (triggerOptions.parameter) {
  26951. this.trigger = triggerOptions.trigger;
  26952. this._triggerParameter = triggerOptions.parameter;
  26953. }
  26954. else {
  26955. this.trigger = triggerOptions;
  26956. }
  26957. this._nextActiveAction = this;
  26958. this._condition = condition;
  26959. }
  26960. // Methods
  26961. Action.prototype._prepare = function () {
  26962. };
  26963. Action.prototype.getTriggerParameter = function () {
  26964. return this._triggerParameter;
  26965. };
  26966. Action.prototype._executeCurrent = function (evt) {
  26967. if (this._nextActiveAction._condition) {
  26968. var condition = this._nextActiveAction._condition;
  26969. var currentRenderId = this._actionManager.getScene().getRenderId();
  26970. // We cache the current evaluation for the current frame
  26971. if (condition._evaluationId === currentRenderId) {
  26972. if (!condition._currentResult) {
  26973. return;
  26974. }
  26975. }
  26976. else {
  26977. condition._evaluationId = currentRenderId;
  26978. if (!condition.isValid()) {
  26979. condition._currentResult = false;
  26980. return;
  26981. }
  26982. condition._currentResult = true;
  26983. }
  26984. }
  26985. this._nextActiveAction.execute(evt);
  26986. this.skipToNextActiveAction();
  26987. };
  26988. Action.prototype.execute = function (evt) {
  26989. };
  26990. Action.prototype.skipToNextActiveAction = function () {
  26991. if (this._nextActiveAction._child) {
  26992. if (!this._nextActiveAction._child._actionManager) {
  26993. this._nextActiveAction._child._actionManager = this._actionManager;
  26994. }
  26995. this._nextActiveAction = this._nextActiveAction._child;
  26996. }
  26997. else {
  26998. this._nextActiveAction = this;
  26999. }
  27000. };
  27001. Action.prototype.then = function (action) {
  27002. this._child = action;
  27003. action._actionManager = this._actionManager;
  27004. action._prepare();
  27005. return action;
  27006. };
  27007. Action.prototype._getProperty = function (propertyPath) {
  27008. return this._actionManager._getProperty(propertyPath);
  27009. };
  27010. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27011. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27012. };
  27013. return Action;
  27014. })();
  27015. BABYLON.Action = Action;
  27016. })(BABYLON || (BABYLON = {}));
  27017. var BABYLON;
  27018. (function (BABYLON) {
  27019. /**
  27020. * ActionEvent is the event beint sent when an action is triggered.
  27021. */
  27022. var ActionEvent = (function () {
  27023. /**
  27024. * @constructor
  27025. * @param source The mesh or sprite that triggered the action.
  27026. * @param pointerX The X mouse cursor position at the time of the event
  27027. * @param pointerY The Y mouse cursor position at the time of the event
  27028. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27029. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27030. */
  27031. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27032. this.source = source;
  27033. this.pointerX = pointerX;
  27034. this.pointerY = pointerY;
  27035. this.meshUnderPointer = meshUnderPointer;
  27036. this.sourceEvent = sourceEvent;
  27037. this.additionalData = additionalData;
  27038. }
  27039. /**
  27040. * Helper function to auto-create an ActionEvent from a source mesh.
  27041. * @param source The source mesh that triggered the event
  27042. * @param evt {Event} The original (browser) event
  27043. */
  27044. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27045. var scene = source.getScene();
  27046. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27047. };
  27048. /**
  27049. * Helper function to auto-create an ActionEvent from a source mesh.
  27050. * @param source The source sprite that triggered the event
  27051. * @param scene Scene associated with the sprite
  27052. * @param evt {Event} The original (browser) event
  27053. */
  27054. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27055. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27056. };
  27057. /**
  27058. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27059. * @param scene the scene where the event occurred
  27060. * @param evt {Event} The original (browser) event
  27061. */
  27062. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27063. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27064. };
  27065. return ActionEvent;
  27066. })();
  27067. BABYLON.ActionEvent = ActionEvent;
  27068. /**
  27069. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27070. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27071. */
  27072. var ActionManager = (function () {
  27073. function ActionManager(scene) {
  27074. // Members
  27075. this.actions = new Array();
  27076. this._scene = scene;
  27077. scene._actionManagers.push(this);
  27078. }
  27079. Object.defineProperty(ActionManager, "NothingTrigger", {
  27080. get: function () {
  27081. return ActionManager._NothingTrigger;
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27087. get: function () {
  27088. return ActionManager._OnPickTrigger;
  27089. },
  27090. enumerable: true,
  27091. configurable: true
  27092. });
  27093. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27094. get: function () {
  27095. return ActionManager._OnLeftPickTrigger;
  27096. },
  27097. enumerable: true,
  27098. configurable: true
  27099. });
  27100. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27101. get: function () {
  27102. return ActionManager._OnRightPickTrigger;
  27103. },
  27104. enumerable: true,
  27105. configurable: true
  27106. });
  27107. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27108. get: function () {
  27109. return ActionManager._OnCenterPickTrigger;
  27110. },
  27111. enumerable: true,
  27112. configurable: true
  27113. });
  27114. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27115. get: function () {
  27116. return ActionManager._OnPickDownTrigger;
  27117. },
  27118. enumerable: true,
  27119. configurable: true
  27120. });
  27121. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27122. get: function () {
  27123. return ActionManager._OnPickUpTrigger;
  27124. },
  27125. enumerable: true,
  27126. configurable: true
  27127. });
  27128. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27129. /// This trigger will only be raised if you also declared a OnPickDown
  27130. get: function () {
  27131. return ActionManager._OnPickOutTrigger;
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27137. get: function () {
  27138. return ActionManager._OnLongPressTrigger;
  27139. },
  27140. enumerable: true,
  27141. configurable: true
  27142. });
  27143. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27144. get: function () {
  27145. return ActionManager._OnPointerOverTrigger;
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27151. get: function () {
  27152. return ActionManager._OnPointerOutTrigger;
  27153. },
  27154. enumerable: true,
  27155. configurable: true
  27156. });
  27157. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27158. get: function () {
  27159. return ActionManager._OnEveryFrameTrigger;
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27165. get: function () {
  27166. return ActionManager._OnIntersectionEnterTrigger;
  27167. },
  27168. enumerable: true,
  27169. configurable: true
  27170. });
  27171. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27172. get: function () {
  27173. return ActionManager._OnIntersectionExitTrigger;
  27174. },
  27175. enumerable: true,
  27176. configurable: true
  27177. });
  27178. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27179. get: function () {
  27180. return ActionManager._OnKeyDownTrigger;
  27181. },
  27182. enumerable: true,
  27183. configurable: true
  27184. });
  27185. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27186. get: function () {
  27187. return ActionManager._OnKeyUpTrigger;
  27188. },
  27189. enumerable: true,
  27190. configurable: true
  27191. });
  27192. // Methods
  27193. ActionManager.prototype.dispose = function () {
  27194. var index = this._scene._actionManagers.indexOf(this);
  27195. if (index > -1) {
  27196. this._scene._actionManagers.splice(index, 1);
  27197. }
  27198. };
  27199. ActionManager.prototype.getScene = function () {
  27200. return this._scene;
  27201. };
  27202. /**
  27203. * Does this action manager handles actions of any of the given triggers
  27204. * @param {number[]} triggers - the triggers to be tested
  27205. * @return {boolean} whether one (or more) of the triggers is handeled
  27206. */
  27207. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27208. for (var index = 0; index < this.actions.length; index++) {
  27209. var action = this.actions[index];
  27210. if (triggers.indexOf(action.trigger) > -1) {
  27211. return true;
  27212. }
  27213. }
  27214. return false;
  27215. };
  27216. /**
  27217. * Does this action manager handles actions of a given trigger
  27218. * @param {number} trigger - the trigger to be tested
  27219. * @return {boolean} whether the trigger is handeled
  27220. */
  27221. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27222. for (var index = 0; index < this.actions.length; index++) {
  27223. var action = this.actions[index];
  27224. if (action.trigger === trigger) {
  27225. return true;
  27226. }
  27227. }
  27228. return false;
  27229. };
  27230. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27231. /**
  27232. * Does this action manager has pointer triggers
  27233. * @return {boolean} whether or not it has pointer triggers
  27234. */
  27235. get: function () {
  27236. for (var index = 0; index < this.actions.length; index++) {
  27237. var action = this.actions[index];
  27238. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27239. return true;
  27240. }
  27241. }
  27242. return false;
  27243. },
  27244. enumerable: true,
  27245. configurable: true
  27246. });
  27247. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27248. /**
  27249. * Does this action manager has pick triggers
  27250. * @return {boolean} whether or not it has pick triggers
  27251. */
  27252. get: function () {
  27253. for (var index = 0; index < this.actions.length; index++) {
  27254. var action = this.actions[index];
  27255. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27256. return true;
  27257. }
  27258. }
  27259. return false;
  27260. },
  27261. enumerable: true,
  27262. configurable: true
  27263. });
  27264. /**
  27265. * Registers an action to this action manager
  27266. * @param {BABYLON.Action} action - the action to be registered
  27267. * @return {BABYLON.Action} the action amended (prepared) after registration
  27268. */
  27269. ActionManager.prototype.registerAction = function (action) {
  27270. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27271. if (this.getScene().actionManager !== this) {
  27272. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27273. return null;
  27274. }
  27275. }
  27276. this.actions.push(action);
  27277. action._actionManager = this;
  27278. action._prepare();
  27279. return action;
  27280. };
  27281. /**
  27282. * Process a specific trigger
  27283. * @param {number} trigger - the trigger to process
  27284. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27285. */
  27286. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27287. for (var index = 0; index < this.actions.length; index++) {
  27288. var action = this.actions[index];
  27289. if (action.trigger === trigger) {
  27290. if (trigger === ActionManager.OnKeyUpTrigger
  27291. || trigger === ActionManager.OnKeyDownTrigger) {
  27292. var parameter = action.getTriggerParameter();
  27293. if (parameter) {
  27294. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27295. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27296. if (actualkey !== parameter.toLowerCase()) {
  27297. continue;
  27298. }
  27299. }
  27300. }
  27301. action._executeCurrent(evt);
  27302. }
  27303. }
  27304. };
  27305. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27306. var properties = propertyPath.split(".");
  27307. for (var index = 0; index < properties.length - 1; index++) {
  27308. target = target[properties[index]];
  27309. }
  27310. return target;
  27311. };
  27312. ActionManager.prototype._getProperty = function (propertyPath) {
  27313. var properties = propertyPath.split(".");
  27314. return properties[properties.length - 1];
  27315. };
  27316. ActionManager.Parse = function (parsedActions, object, scene) {
  27317. var actionManager = new BABYLON.ActionManager(scene);
  27318. if (object === null)
  27319. scene.actionManager = actionManager;
  27320. else
  27321. object.actionManager = actionManager;
  27322. // instanciate a new object
  27323. var instanciate = function (name, params) {
  27324. var newInstance = Object.create(BABYLON[name].prototype);
  27325. newInstance.constructor.apply(newInstance, params);
  27326. return newInstance;
  27327. };
  27328. var parseParameter = function (name, value, target, propertyPath) {
  27329. if (propertyPath === null) {
  27330. // String, boolean or float
  27331. var floatValue = parseFloat(value);
  27332. if (value === "true" || value === "false")
  27333. return value === "true";
  27334. else
  27335. return isNaN(floatValue) ? value : floatValue;
  27336. }
  27337. var effectiveTarget = propertyPath.split(".");
  27338. var values = value.split(",");
  27339. // Get effective Target
  27340. for (var i = 0; i < effectiveTarget.length; i++) {
  27341. target = target[effectiveTarget[i]];
  27342. }
  27343. // Return appropriate value with its type
  27344. if (typeof (target) === "boolean")
  27345. return values[0] === "true";
  27346. if (typeof (target) === "string")
  27347. return values[0];
  27348. // Parameters with multiple values such as Vector3 etc.
  27349. var split = new Array();
  27350. for (var i = 0; i < values.length; i++)
  27351. split.push(parseFloat(values[i]));
  27352. if (target instanceof BABYLON.Vector3)
  27353. return BABYLON.Vector3.FromArray(split);
  27354. if (target instanceof BABYLON.Vector4)
  27355. return BABYLON.Vector4.FromArray(split);
  27356. if (target instanceof BABYLON.Color3)
  27357. return BABYLON.Color3.FromArray(split);
  27358. if (target instanceof BABYLON.Color4)
  27359. return BABYLON.Color4.FromArray(split);
  27360. return parseFloat(values[0]);
  27361. };
  27362. // traverse graph per trigger
  27363. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27364. if (combineArray === void 0) { combineArray = null; }
  27365. if (parsedAction.detached)
  27366. return;
  27367. var parameters = new Array();
  27368. var target = null;
  27369. var propertyPath = null;
  27370. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27371. // Parameters
  27372. if (parsedAction.type === 2)
  27373. parameters.push(actionManager);
  27374. else
  27375. parameters.push(trigger);
  27376. if (combine) {
  27377. var actions = new Array();
  27378. for (var j = 0; j < parsedAction.combine.length; j++) {
  27379. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27380. }
  27381. parameters.push(actions);
  27382. }
  27383. else {
  27384. for (var i = 0; i < parsedAction.properties.length; i++) {
  27385. var value = parsedAction.properties[i].value;
  27386. var name = parsedAction.properties[i].name;
  27387. var targetType = parsedAction.properties[i].targetType;
  27388. if (name === "target")
  27389. if (targetType !== null && targetType === "SceneProperties")
  27390. value = target = scene;
  27391. else
  27392. value = target = scene.getNodeByName(value);
  27393. else if (name === "parent")
  27394. value = scene.getNodeByName(value);
  27395. else if (name === "sound")
  27396. value = scene.getSoundByName(value);
  27397. else if (name !== "propertyPath") {
  27398. if (parsedAction.type === 2 && name === "operator")
  27399. value = BABYLON.ValueCondition[value];
  27400. else
  27401. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27402. }
  27403. else {
  27404. propertyPath = value;
  27405. }
  27406. parameters.push(value);
  27407. }
  27408. }
  27409. if (combineArray === null) {
  27410. parameters.push(condition);
  27411. }
  27412. else {
  27413. parameters.push(null);
  27414. }
  27415. // If interpolate value action
  27416. if (parsedAction.name === "InterpolateValueAction") {
  27417. var param = parameters[parameters.length - 2];
  27418. parameters[parameters.length - 1] = param;
  27419. parameters[parameters.length - 2] = condition;
  27420. }
  27421. // Action or condition(s) and not CombineAction
  27422. var newAction = instanciate(parsedAction.name, parameters);
  27423. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27424. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27425. if (action)
  27426. action.then(nothing);
  27427. else
  27428. actionManager.registerAction(nothing);
  27429. action = nothing;
  27430. }
  27431. if (combineArray === null) {
  27432. if (newAction instanceof BABYLON.Condition) {
  27433. condition = newAction;
  27434. newAction = action;
  27435. }
  27436. else {
  27437. condition = null;
  27438. if (action)
  27439. action.then(newAction);
  27440. else
  27441. actionManager.registerAction(newAction);
  27442. }
  27443. }
  27444. else {
  27445. combineArray.push(newAction);
  27446. }
  27447. for (var i = 0; i < parsedAction.children.length; i++)
  27448. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27449. };
  27450. // triggers
  27451. for (var i = 0; i < parsedActions.children.length; i++) {
  27452. var triggerParams;
  27453. var trigger = parsedActions.children[i];
  27454. if (trigger.properties.length > 0) {
  27455. var param = trigger.properties[0].value;
  27456. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27457. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27458. }
  27459. else
  27460. triggerParams = BABYLON.ActionManager[trigger.name];
  27461. for (var j = 0; j < trigger.children.length; j++) {
  27462. if (!trigger.detached)
  27463. traverse(trigger.children[j], triggerParams, null, null);
  27464. }
  27465. }
  27466. };
  27467. // Statics
  27468. ActionManager._NothingTrigger = 0;
  27469. ActionManager._OnPickTrigger = 1;
  27470. ActionManager._OnLeftPickTrigger = 2;
  27471. ActionManager._OnRightPickTrigger = 3;
  27472. ActionManager._OnCenterPickTrigger = 4;
  27473. ActionManager._OnPickDownTrigger = 5;
  27474. ActionManager._OnPickUpTrigger = 6;
  27475. ActionManager._OnLongPressTrigger = 7;
  27476. ActionManager._OnPointerOverTrigger = 8;
  27477. ActionManager._OnPointerOutTrigger = 9;
  27478. ActionManager._OnEveryFrameTrigger = 10;
  27479. ActionManager._OnIntersectionEnterTrigger = 11;
  27480. ActionManager._OnIntersectionExitTrigger = 12;
  27481. ActionManager._OnKeyDownTrigger = 13;
  27482. ActionManager._OnKeyUpTrigger = 14;
  27483. ActionManager._OnPickOutTrigger = 15;
  27484. ActionManager.DragMovementThreshold = 10; // in pixels
  27485. ActionManager.LongPressDelay = 500; // in milliseconds
  27486. return ActionManager;
  27487. })();
  27488. BABYLON.ActionManager = ActionManager;
  27489. })(BABYLON || (BABYLON = {}));
  27490. var BABYLON;
  27491. (function (BABYLON) {
  27492. var InterpolateValueAction = (function (_super) {
  27493. __extends(InterpolateValueAction, _super);
  27494. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27495. if (duration === void 0) { duration = 1000; }
  27496. _super.call(this, triggerOptions, condition);
  27497. this.propertyPath = propertyPath;
  27498. this.value = value;
  27499. this.duration = duration;
  27500. this.stopOtherAnimations = stopOtherAnimations;
  27501. this.onInterpolationDone = onInterpolationDone;
  27502. this._target = target;
  27503. }
  27504. InterpolateValueAction.prototype._prepare = function () {
  27505. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27506. this._property = this._getProperty(this.propertyPath);
  27507. };
  27508. InterpolateValueAction.prototype.execute = function () {
  27509. var scene = this._actionManager.getScene();
  27510. var keys = [
  27511. {
  27512. frame: 0,
  27513. value: this._target[this._property]
  27514. }, {
  27515. frame: 100,
  27516. value: this.value
  27517. }
  27518. ];
  27519. var dataType;
  27520. if (typeof this.value === "number") {
  27521. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27522. }
  27523. else if (this.value instanceof BABYLON.Color3) {
  27524. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27525. }
  27526. else if (this.value instanceof BABYLON.Vector3) {
  27527. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27528. }
  27529. else if (this.value instanceof BABYLON.Matrix) {
  27530. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27531. }
  27532. else if (this.value instanceof BABYLON.Quaternion) {
  27533. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27534. }
  27535. else {
  27536. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27537. return;
  27538. }
  27539. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27540. animation.setKeys(keys);
  27541. if (this.stopOtherAnimations) {
  27542. scene.stopAnimation(this._target);
  27543. }
  27544. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27545. };
  27546. return InterpolateValueAction;
  27547. })(BABYLON.Action);
  27548. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27549. })(BABYLON || (BABYLON = {}));
  27550. var BABYLON;
  27551. (function (BABYLON) {
  27552. var SwitchBooleanAction = (function (_super) {
  27553. __extends(SwitchBooleanAction, _super);
  27554. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27555. _super.call(this, triggerOptions, condition);
  27556. this.propertyPath = propertyPath;
  27557. this._target = target;
  27558. }
  27559. SwitchBooleanAction.prototype._prepare = function () {
  27560. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27561. this._property = this._getProperty(this.propertyPath);
  27562. };
  27563. SwitchBooleanAction.prototype.execute = function () {
  27564. this._target[this._property] = !this._target[this._property];
  27565. };
  27566. return SwitchBooleanAction;
  27567. })(BABYLON.Action);
  27568. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27569. var SetStateAction = (function (_super) {
  27570. __extends(SetStateAction, _super);
  27571. function SetStateAction(triggerOptions, target, value, condition) {
  27572. _super.call(this, triggerOptions, condition);
  27573. this.value = value;
  27574. this._target = target;
  27575. }
  27576. SetStateAction.prototype.execute = function () {
  27577. this._target.state = this.value;
  27578. };
  27579. return SetStateAction;
  27580. })(BABYLON.Action);
  27581. BABYLON.SetStateAction = SetStateAction;
  27582. var SetValueAction = (function (_super) {
  27583. __extends(SetValueAction, _super);
  27584. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27585. _super.call(this, triggerOptions, condition);
  27586. this.propertyPath = propertyPath;
  27587. this.value = value;
  27588. this._target = target;
  27589. }
  27590. SetValueAction.prototype._prepare = function () {
  27591. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27592. this._property = this._getProperty(this.propertyPath);
  27593. };
  27594. SetValueAction.prototype.execute = function () {
  27595. this._target[this._property] = this.value;
  27596. };
  27597. return SetValueAction;
  27598. })(BABYLON.Action);
  27599. BABYLON.SetValueAction = SetValueAction;
  27600. var IncrementValueAction = (function (_super) {
  27601. __extends(IncrementValueAction, _super);
  27602. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27603. _super.call(this, triggerOptions, condition);
  27604. this.propertyPath = propertyPath;
  27605. this.value = value;
  27606. this._target = target;
  27607. }
  27608. IncrementValueAction.prototype._prepare = function () {
  27609. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27610. this._property = this._getProperty(this.propertyPath);
  27611. if (typeof this._target[this._property] !== "number") {
  27612. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27613. }
  27614. };
  27615. IncrementValueAction.prototype.execute = function () {
  27616. this._target[this._property] += this.value;
  27617. };
  27618. return IncrementValueAction;
  27619. })(BABYLON.Action);
  27620. BABYLON.IncrementValueAction = IncrementValueAction;
  27621. var PlayAnimationAction = (function (_super) {
  27622. __extends(PlayAnimationAction, _super);
  27623. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27624. _super.call(this, triggerOptions, condition);
  27625. this.from = from;
  27626. this.to = to;
  27627. this.loop = loop;
  27628. this._target = target;
  27629. }
  27630. PlayAnimationAction.prototype._prepare = function () {
  27631. };
  27632. PlayAnimationAction.prototype.execute = function () {
  27633. var scene = this._actionManager.getScene();
  27634. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27635. };
  27636. return PlayAnimationAction;
  27637. })(BABYLON.Action);
  27638. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27639. var StopAnimationAction = (function (_super) {
  27640. __extends(StopAnimationAction, _super);
  27641. function StopAnimationAction(triggerOptions, target, condition) {
  27642. _super.call(this, triggerOptions, condition);
  27643. this._target = target;
  27644. }
  27645. StopAnimationAction.prototype._prepare = function () {
  27646. };
  27647. StopAnimationAction.prototype.execute = function () {
  27648. var scene = this._actionManager.getScene();
  27649. scene.stopAnimation(this._target);
  27650. };
  27651. return StopAnimationAction;
  27652. })(BABYLON.Action);
  27653. BABYLON.StopAnimationAction = StopAnimationAction;
  27654. var DoNothingAction = (function (_super) {
  27655. __extends(DoNothingAction, _super);
  27656. function DoNothingAction(triggerOptions, condition) {
  27657. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27658. _super.call(this, triggerOptions, condition);
  27659. }
  27660. DoNothingAction.prototype.execute = function () {
  27661. };
  27662. return DoNothingAction;
  27663. })(BABYLON.Action);
  27664. BABYLON.DoNothingAction = DoNothingAction;
  27665. var CombineAction = (function (_super) {
  27666. __extends(CombineAction, _super);
  27667. function CombineAction(triggerOptions, children, condition) {
  27668. _super.call(this, triggerOptions, condition);
  27669. this.children = children;
  27670. }
  27671. CombineAction.prototype._prepare = function () {
  27672. for (var index = 0; index < this.children.length; index++) {
  27673. this.children[index]._actionManager = this._actionManager;
  27674. this.children[index]._prepare();
  27675. }
  27676. };
  27677. CombineAction.prototype.execute = function (evt) {
  27678. for (var index = 0; index < this.children.length; index++) {
  27679. this.children[index].execute(evt);
  27680. }
  27681. };
  27682. return CombineAction;
  27683. })(BABYLON.Action);
  27684. BABYLON.CombineAction = CombineAction;
  27685. var ExecuteCodeAction = (function (_super) {
  27686. __extends(ExecuteCodeAction, _super);
  27687. function ExecuteCodeAction(triggerOptions, func, condition) {
  27688. _super.call(this, triggerOptions, condition);
  27689. this.func = func;
  27690. }
  27691. ExecuteCodeAction.prototype.execute = function (evt) {
  27692. this.func(evt);
  27693. };
  27694. return ExecuteCodeAction;
  27695. })(BABYLON.Action);
  27696. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27697. var SetParentAction = (function (_super) {
  27698. __extends(SetParentAction, _super);
  27699. function SetParentAction(triggerOptions, target, parent, condition) {
  27700. _super.call(this, triggerOptions, condition);
  27701. this._target = target;
  27702. this._parent = parent;
  27703. }
  27704. SetParentAction.prototype._prepare = function () {
  27705. };
  27706. SetParentAction.prototype.execute = function () {
  27707. if (this._target.parent === this._parent) {
  27708. return;
  27709. }
  27710. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27711. invertParentWorldMatrix.invert();
  27712. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27713. this._target.parent = this._parent;
  27714. };
  27715. return SetParentAction;
  27716. })(BABYLON.Action);
  27717. BABYLON.SetParentAction = SetParentAction;
  27718. var PlaySoundAction = (function (_super) {
  27719. __extends(PlaySoundAction, _super);
  27720. function PlaySoundAction(triggerOptions, sound, condition) {
  27721. _super.call(this, triggerOptions, condition);
  27722. this._sound = sound;
  27723. }
  27724. PlaySoundAction.prototype._prepare = function () {
  27725. };
  27726. PlaySoundAction.prototype.execute = function () {
  27727. if (this._sound !== undefined)
  27728. this._sound.play();
  27729. };
  27730. return PlaySoundAction;
  27731. })(BABYLON.Action);
  27732. BABYLON.PlaySoundAction = PlaySoundAction;
  27733. var StopSoundAction = (function (_super) {
  27734. __extends(StopSoundAction, _super);
  27735. function StopSoundAction(triggerOptions, sound, condition) {
  27736. _super.call(this, triggerOptions, condition);
  27737. this._sound = sound;
  27738. }
  27739. StopSoundAction.prototype._prepare = function () {
  27740. };
  27741. StopSoundAction.prototype.execute = function () {
  27742. if (this._sound !== undefined)
  27743. this._sound.stop();
  27744. };
  27745. return StopSoundAction;
  27746. })(BABYLON.Action);
  27747. BABYLON.StopSoundAction = StopSoundAction;
  27748. })(BABYLON || (BABYLON = {}));
  27749. var BABYLON;
  27750. (function (BABYLON) {
  27751. var Geometry = (function () {
  27752. function Geometry(id, scene, vertexData, updatable, mesh) {
  27753. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27754. this._totalVertices = 0;
  27755. this._isDisposed = false;
  27756. this.id = id;
  27757. this._engine = scene.getEngine();
  27758. this._meshes = [];
  27759. this._scene = scene;
  27760. //Init vertex buffer cache
  27761. this._vertexBuffers = {};
  27762. this._indices = [];
  27763. // vertexData
  27764. if (vertexData) {
  27765. this.setAllVerticesData(vertexData, updatable);
  27766. }
  27767. else {
  27768. this._totalVertices = 0;
  27769. this._indices = [];
  27770. }
  27771. // applyToMesh
  27772. if (mesh) {
  27773. this.applyToMesh(mesh);
  27774. mesh.computeWorldMatrix(true);
  27775. }
  27776. }
  27777. Object.defineProperty(Geometry.prototype, "extend", {
  27778. get: function () {
  27779. return this._extend;
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. Geometry.prototype.getScene = function () {
  27785. return this._scene;
  27786. };
  27787. Geometry.prototype.getEngine = function () {
  27788. return this._engine;
  27789. };
  27790. Geometry.prototype.isReady = function () {
  27791. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27792. };
  27793. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27794. vertexData.applyToGeometry(this, updatable);
  27795. this.notifyUpdate();
  27796. };
  27797. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27798. if (this._vertexBuffers[kind]) {
  27799. this._vertexBuffers[kind].dispose();
  27800. }
  27801. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27802. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27803. stride = this._vertexBuffers[kind].getStrideSize();
  27804. this._totalVertices = data.length / stride;
  27805. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27806. var meshes = this._meshes;
  27807. var numOfMeshes = meshes.length;
  27808. for (var index = 0; index < numOfMeshes; index++) {
  27809. var mesh = meshes[index];
  27810. mesh._resetPointsArrayCache();
  27811. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27812. mesh._createGlobalSubMesh();
  27813. mesh.computeWorldMatrix(true);
  27814. }
  27815. }
  27816. this.notifyUpdate(kind);
  27817. };
  27818. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27819. var vertexBuffer = this.getVertexBuffer(kind);
  27820. if (!vertexBuffer) {
  27821. return;
  27822. }
  27823. vertexBuffer.updateDirectly(data, offset);
  27824. this.notifyUpdate(kind);
  27825. };
  27826. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27827. var vertexBuffer = this.getVertexBuffer(kind);
  27828. if (!vertexBuffer) {
  27829. return;
  27830. }
  27831. vertexBuffer.update(data);
  27832. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27833. var stride = vertexBuffer.getStrideSize();
  27834. this._totalVertices = data.length / stride;
  27835. if (updateExtends) {
  27836. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27837. }
  27838. var meshes = this._meshes;
  27839. var numOfMeshes = meshes.length;
  27840. for (var index = 0; index < numOfMeshes; index++) {
  27841. var mesh = meshes[index];
  27842. mesh._resetPointsArrayCache();
  27843. if (updateExtends) {
  27844. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27845. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27846. var subMesh = mesh.subMeshes[subIndex];
  27847. subMesh.refreshBoundingInfo();
  27848. }
  27849. }
  27850. }
  27851. }
  27852. this.notifyUpdate(kind);
  27853. };
  27854. Geometry.prototype.getTotalVertices = function () {
  27855. if (!this.isReady()) {
  27856. return 0;
  27857. }
  27858. return this._totalVertices;
  27859. };
  27860. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27861. var vertexBuffer = this.getVertexBuffer(kind);
  27862. if (!vertexBuffer) {
  27863. return null;
  27864. }
  27865. var orig = vertexBuffer.getData();
  27866. if (!copyWhenShared || this._meshes.length === 1) {
  27867. return orig;
  27868. }
  27869. else {
  27870. var len = orig.length;
  27871. var copy = [];
  27872. for (var i = 0; i < len; i++) {
  27873. copy.push(orig[i]);
  27874. }
  27875. return copy;
  27876. }
  27877. };
  27878. Geometry.prototype.getVertexBuffer = function (kind) {
  27879. if (!this.isReady()) {
  27880. return null;
  27881. }
  27882. return this._vertexBuffers[kind];
  27883. };
  27884. Geometry.prototype.getVertexBuffers = function () {
  27885. if (!this.isReady()) {
  27886. return null;
  27887. }
  27888. return this._vertexBuffers;
  27889. };
  27890. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27891. if (!this._vertexBuffers) {
  27892. if (this._delayInfo) {
  27893. return this._delayInfo.indexOf(kind) !== -1;
  27894. }
  27895. return false;
  27896. }
  27897. return this._vertexBuffers[kind] !== undefined;
  27898. };
  27899. Geometry.prototype.getVerticesDataKinds = function () {
  27900. var result = [];
  27901. var kind;
  27902. if (!this._vertexBuffers && this._delayInfo) {
  27903. for (kind in this._delayInfo) {
  27904. result.push(kind);
  27905. }
  27906. }
  27907. else {
  27908. for (kind in this._vertexBuffers) {
  27909. result.push(kind);
  27910. }
  27911. }
  27912. return result;
  27913. };
  27914. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27915. if (this._indexBuffer) {
  27916. this._engine._releaseBuffer(this._indexBuffer);
  27917. }
  27918. this._indices = indices;
  27919. if (this._meshes.length !== 0 && this._indices) {
  27920. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27921. }
  27922. if (totalVertices !== undefined) {
  27923. this._totalVertices = totalVertices;
  27924. }
  27925. var meshes = this._meshes;
  27926. var numOfMeshes = meshes.length;
  27927. for (var index = 0; index < numOfMeshes; index++) {
  27928. meshes[index]._createGlobalSubMesh();
  27929. }
  27930. this.notifyUpdate();
  27931. };
  27932. Geometry.prototype.getTotalIndices = function () {
  27933. if (!this.isReady()) {
  27934. return 0;
  27935. }
  27936. return this._indices.length;
  27937. };
  27938. Geometry.prototype.getIndices = function (copyWhenShared) {
  27939. if (!this.isReady()) {
  27940. return null;
  27941. }
  27942. var orig = this._indices;
  27943. if (!copyWhenShared || this._meshes.length === 1) {
  27944. return orig;
  27945. }
  27946. else {
  27947. var len = orig.length;
  27948. var copy = [];
  27949. for (var i = 0; i < len; i++) {
  27950. copy.push(orig[i]);
  27951. }
  27952. return copy;
  27953. }
  27954. };
  27955. Geometry.prototype.getIndexBuffer = function () {
  27956. if (!this.isReady()) {
  27957. return null;
  27958. }
  27959. return this._indexBuffer;
  27960. };
  27961. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27962. var meshes = this._meshes;
  27963. var index = meshes.indexOf(mesh);
  27964. if (index === -1) {
  27965. return;
  27966. }
  27967. for (var kind in this._vertexBuffers) {
  27968. this._vertexBuffers[kind].dispose();
  27969. }
  27970. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27971. this._indexBuffer = null;
  27972. }
  27973. meshes.splice(index, 1);
  27974. mesh._geometry = null;
  27975. if (meshes.length === 0 && shouldDispose) {
  27976. this.dispose();
  27977. }
  27978. };
  27979. Geometry.prototype.applyToMesh = function (mesh) {
  27980. if (mesh._geometry === this) {
  27981. return;
  27982. }
  27983. var previousGeometry = mesh._geometry;
  27984. if (previousGeometry) {
  27985. previousGeometry.releaseForMesh(mesh);
  27986. }
  27987. var meshes = this._meshes;
  27988. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27989. mesh._geometry = this;
  27990. this._scene.pushGeometry(this);
  27991. meshes.push(mesh);
  27992. if (this.isReady()) {
  27993. this._applyToMesh(mesh);
  27994. }
  27995. else {
  27996. mesh._boundingInfo = this._boundingInfo;
  27997. }
  27998. };
  27999. Geometry.prototype._applyToMesh = function (mesh) {
  28000. var numOfMeshes = this._meshes.length;
  28001. // vertexBuffers
  28002. for (var kind in this._vertexBuffers) {
  28003. if (numOfMeshes === 1) {
  28004. this._vertexBuffers[kind].create();
  28005. }
  28006. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28007. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28008. mesh._resetPointsArrayCache();
  28009. if (!this._extend) {
  28010. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28011. }
  28012. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28013. mesh._createGlobalSubMesh();
  28014. //bounding info was just created again, world matrix should be applied again.
  28015. mesh._updateBoundingInfo();
  28016. }
  28017. }
  28018. // indexBuffer
  28019. if (numOfMeshes === 1 && this._indices) {
  28020. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28021. }
  28022. if (this._indexBuffer) {
  28023. this._indexBuffer.references = numOfMeshes;
  28024. }
  28025. };
  28026. Geometry.prototype.notifyUpdate = function (kind) {
  28027. if (this.onGeometryUpdated) {
  28028. this.onGeometryUpdated(this, kind);
  28029. }
  28030. };
  28031. Geometry.prototype.load = function (scene, onLoaded) {
  28032. var _this = this;
  28033. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28034. return;
  28035. }
  28036. if (this.isReady()) {
  28037. if (onLoaded) {
  28038. onLoaded();
  28039. }
  28040. return;
  28041. }
  28042. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28043. scene._addPendingData(this);
  28044. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28045. _this._delayLoadingFunction(JSON.parse(data), _this);
  28046. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28047. _this._delayInfo = [];
  28048. scene._removePendingData(_this);
  28049. var meshes = _this._meshes;
  28050. var numOfMeshes = meshes.length;
  28051. for (var index = 0; index < numOfMeshes; index++) {
  28052. _this._applyToMesh(meshes[index]);
  28053. }
  28054. if (onLoaded) {
  28055. onLoaded();
  28056. }
  28057. }, function () { }, scene.database);
  28058. };
  28059. Geometry.prototype.isDisposed = function () {
  28060. return this._isDisposed;
  28061. };
  28062. Geometry.prototype.dispose = function () {
  28063. var meshes = this._meshes;
  28064. var numOfMeshes = meshes.length;
  28065. var index;
  28066. for (index = 0; index < numOfMeshes; index++) {
  28067. this.releaseForMesh(meshes[index]);
  28068. }
  28069. this._meshes = [];
  28070. for (var kind in this._vertexBuffers) {
  28071. this._vertexBuffers[kind].dispose();
  28072. }
  28073. this._vertexBuffers = [];
  28074. this._totalVertices = 0;
  28075. if (this._indexBuffer) {
  28076. this._engine._releaseBuffer(this._indexBuffer);
  28077. }
  28078. this._indexBuffer = null;
  28079. this._indices = [];
  28080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28081. this.delayLoadingFile = null;
  28082. this._delayLoadingFunction = null;
  28083. this._delayInfo = [];
  28084. this._boundingInfo = null;
  28085. this._scene.removeGeometry(this);
  28086. this._isDisposed = true;
  28087. };
  28088. Geometry.prototype.copy = function (id) {
  28089. var vertexData = new BABYLON.VertexData();
  28090. vertexData.indices = [];
  28091. var indices = this.getIndices();
  28092. for (var index = 0; index < indices.length; index++) {
  28093. vertexData.indices.push(indices[index]);
  28094. }
  28095. var updatable = false;
  28096. var stopChecking = false;
  28097. var kind;
  28098. for (kind in this._vertexBuffers) {
  28099. // using slice() to make a copy of the array and not just reference it
  28100. var data = this.getVerticesData(kind);
  28101. if (data instanceof Float32Array) {
  28102. vertexData.set(new Float32Array(data), kind);
  28103. }
  28104. else {
  28105. vertexData.set(data.slice(0), kind);
  28106. }
  28107. if (!stopChecking) {
  28108. updatable = this.getVertexBuffer(kind).isUpdatable();
  28109. stopChecking = !updatable;
  28110. }
  28111. }
  28112. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28113. geometry.delayLoadState = this.delayLoadState;
  28114. geometry.delayLoadingFile = this.delayLoadingFile;
  28115. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28116. for (kind in this._delayInfo) {
  28117. geometry._delayInfo = geometry._delayInfo || [];
  28118. geometry._delayInfo.push(kind);
  28119. }
  28120. // Bounding info
  28121. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28122. return geometry;
  28123. };
  28124. Geometry.prototype.serialize = function () {
  28125. var serializationObject = {};
  28126. serializationObject.id = this.id;
  28127. if (BABYLON.Tags.HasTags(this)) {
  28128. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28129. }
  28130. return serializationObject;
  28131. };
  28132. Geometry.prototype.serializeVerticeData = function () {
  28133. var serializationObject = this.serialize();
  28134. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28135. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28136. }
  28137. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28138. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28139. }
  28140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28141. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28142. }
  28143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28144. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28145. }
  28146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28147. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28148. }
  28149. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28150. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28151. }
  28152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28153. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28154. }
  28155. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28156. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28157. }
  28158. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28159. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28160. }
  28161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28162. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28163. serializationObject.matricesIndices._isExpanded = true;
  28164. }
  28165. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28166. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28167. }
  28168. serializationObject.indices = this.getIndices();
  28169. return serializationObject;
  28170. };
  28171. // Statics
  28172. Geometry.ExtractFromMesh = function (mesh, id) {
  28173. var geometry = mesh._geometry;
  28174. if (!geometry) {
  28175. return null;
  28176. }
  28177. return geometry.copy(id);
  28178. };
  28179. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28180. // be aware Math.random() could cause collisions
  28181. Geometry.RandomId = function () {
  28182. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28183. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28184. return v.toString(16);
  28185. });
  28186. };
  28187. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28188. var scene = mesh.getScene();
  28189. // Geometry
  28190. var geometryId = parsedGeometry.geometryId;
  28191. if (geometryId) {
  28192. var geometry = scene.getGeometryByID(geometryId);
  28193. if (geometry) {
  28194. geometry.applyToMesh(mesh);
  28195. }
  28196. }
  28197. else if (parsedGeometry instanceof ArrayBuffer) {
  28198. var binaryInfo = mesh._binaryInfo;
  28199. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28200. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28201. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28202. }
  28203. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28204. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28205. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28206. }
  28207. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28208. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28209. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28210. }
  28211. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28212. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28213. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28214. }
  28215. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28216. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28217. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28218. }
  28219. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28220. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28221. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28222. }
  28223. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28224. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28225. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28226. }
  28227. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28228. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28229. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28230. }
  28231. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28232. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28233. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28234. }
  28235. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28236. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28237. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28238. }
  28239. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28240. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28241. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28242. }
  28243. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28244. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28245. mesh.setIndices(indicesData);
  28246. }
  28247. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28248. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28249. mesh.subMeshes = [];
  28250. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28251. var materialIndex = subMeshesData[(i * 5) + 0];
  28252. var verticesStart = subMeshesData[(i * 5) + 1];
  28253. var verticesCount = subMeshesData[(i * 5) + 2];
  28254. var indexStart = subMeshesData[(i * 5) + 3];
  28255. var indexCount = subMeshesData[(i * 5) + 4];
  28256. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28257. }
  28258. }
  28259. }
  28260. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28261. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28262. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28263. if (parsedGeometry.uvs) {
  28264. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28265. }
  28266. if (parsedGeometry.uvs2) {
  28267. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28268. }
  28269. if (parsedGeometry.uvs3) {
  28270. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28271. }
  28272. if (parsedGeometry.uvs4) {
  28273. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28274. }
  28275. if (parsedGeometry.uvs5) {
  28276. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28277. }
  28278. if (parsedGeometry.uvs6) {
  28279. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28280. }
  28281. if (parsedGeometry.colors) {
  28282. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28283. }
  28284. if (parsedGeometry.matricesIndices) {
  28285. if (!parsedGeometry.matricesIndices._isExpanded) {
  28286. var floatIndices = [];
  28287. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28288. var matricesIndex = parsedGeometry.matricesIndices[i];
  28289. floatIndices.push(matricesIndex & 0x000000FF);
  28290. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28291. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28292. floatIndices.push(matricesIndex >> 24);
  28293. }
  28294. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28295. }
  28296. else {
  28297. delete parsedGeometry.matricesIndices._isExpanded;
  28298. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28299. }
  28300. }
  28301. if (parsedGeometry.matricesIndicesExtra) {
  28302. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28303. var floatIndices = [];
  28304. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28305. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28306. floatIndices.push(matricesIndex & 0x000000FF);
  28307. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28308. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28309. floatIndices.push(matricesIndex >> 24);
  28310. }
  28311. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28312. }
  28313. else {
  28314. delete parsedGeometry.matricesIndices._isExpanded;
  28315. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28316. }
  28317. }
  28318. if (parsedGeometry.matricesWeights) {
  28319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28320. }
  28321. if (parsedGeometry.matricesWeightsExtra) {
  28322. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28323. }
  28324. mesh.setIndices(parsedGeometry.indices);
  28325. }
  28326. // SubMeshes
  28327. if (parsedGeometry.subMeshes) {
  28328. mesh.subMeshes = [];
  28329. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28330. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28331. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28332. }
  28333. }
  28334. // Flat shading
  28335. if (mesh._shouldGenerateFlatShading) {
  28336. mesh.convertToFlatShadedMesh();
  28337. delete mesh._shouldGenerateFlatShading;
  28338. }
  28339. // Update
  28340. mesh.computeWorldMatrix(true);
  28341. // Octree
  28342. if (scene['_selectionOctree']) {
  28343. scene['_selectionOctree'].addMesh(mesh);
  28344. }
  28345. };
  28346. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28347. if (scene.getGeometryByID(parsedVertexData.id)) {
  28348. return null; // null since geometry could be something else than a box...
  28349. }
  28350. var geometry = new Geometry(parsedVertexData.id, scene);
  28351. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28352. if (parsedVertexData.delayLoadingFile) {
  28353. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28354. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28355. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28356. geometry._delayInfo = [];
  28357. if (parsedVertexData.hasUVs) {
  28358. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28359. }
  28360. if (parsedVertexData.hasUVs2) {
  28361. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28362. }
  28363. if (parsedVertexData.hasUVs3) {
  28364. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28365. }
  28366. if (parsedVertexData.hasUVs4) {
  28367. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28368. }
  28369. if (parsedVertexData.hasUVs5) {
  28370. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28371. }
  28372. if (parsedVertexData.hasUVs6) {
  28373. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28374. }
  28375. if (parsedVertexData.hasColors) {
  28376. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28377. }
  28378. if (parsedVertexData.hasMatricesIndices) {
  28379. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28380. }
  28381. if (parsedVertexData.hasMatricesWeights) {
  28382. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28383. }
  28384. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28385. }
  28386. else {
  28387. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28388. }
  28389. scene.pushGeometry(geometry, true);
  28390. return geometry;
  28391. };
  28392. return Geometry;
  28393. })();
  28394. BABYLON.Geometry = Geometry;
  28395. /////// Primitives //////////////////////////////////////////////
  28396. var Geometry;
  28397. (function (Geometry) {
  28398. var Primitives;
  28399. (function (Primitives) {
  28400. /// Abstract class
  28401. var _Primitive = (function (_super) {
  28402. __extends(_Primitive, _super);
  28403. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28404. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28405. this._canBeRegenerated = _canBeRegenerated;
  28406. this._beingRegenerated = true;
  28407. this.regenerate();
  28408. this._beingRegenerated = false;
  28409. }
  28410. _Primitive.prototype.canBeRegenerated = function () {
  28411. return this._canBeRegenerated;
  28412. };
  28413. _Primitive.prototype.regenerate = function () {
  28414. if (!this._canBeRegenerated) {
  28415. return;
  28416. }
  28417. this._beingRegenerated = true;
  28418. this.setAllVerticesData(this._regenerateVertexData(), false);
  28419. this._beingRegenerated = false;
  28420. };
  28421. _Primitive.prototype.asNewGeometry = function (id) {
  28422. return _super.prototype.copy.call(this, id);
  28423. };
  28424. // overrides
  28425. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28426. if (!this._beingRegenerated) {
  28427. return;
  28428. }
  28429. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28430. };
  28431. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28432. if (!this._beingRegenerated) {
  28433. return;
  28434. }
  28435. _super.prototype.setVerticesData.call(this, kind, data, false);
  28436. };
  28437. // to override
  28438. // protected
  28439. _Primitive.prototype._regenerateVertexData = function () {
  28440. throw new Error("Abstract method");
  28441. };
  28442. _Primitive.prototype.copy = function (id) {
  28443. throw new Error("Must be overriden in sub-classes.");
  28444. };
  28445. _Primitive.prototype.serialize = function () {
  28446. var serializationObject = _super.prototype.serialize.call(this);
  28447. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28448. return serializationObject;
  28449. };
  28450. return _Primitive;
  28451. })(Geometry);
  28452. Primitives._Primitive = _Primitive;
  28453. var Ribbon = (function (_super) {
  28454. __extends(Ribbon, _super);
  28455. // Members
  28456. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28458. _super.call(this, id, scene, canBeRegenerated, mesh);
  28459. this.pathArray = pathArray;
  28460. this.closeArray = closeArray;
  28461. this.closePath = closePath;
  28462. this.offset = offset;
  28463. this.side = side;
  28464. }
  28465. Ribbon.prototype._regenerateVertexData = function () {
  28466. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28467. };
  28468. Ribbon.prototype.copy = function (id) {
  28469. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28470. };
  28471. return Ribbon;
  28472. })(_Primitive);
  28473. Primitives.Ribbon = Ribbon;
  28474. var Box = (function (_super) {
  28475. __extends(Box, _super);
  28476. // Members
  28477. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28478. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28479. _super.call(this, id, scene, canBeRegenerated, mesh);
  28480. this.size = size;
  28481. this.side = side;
  28482. }
  28483. Box.prototype._regenerateVertexData = function () {
  28484. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28485. };
  28486. Box.prototype.copy = function (id) {
  28487. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28488. };
  28489. Box.prototype.serialize = function () {
  28490. var serializationObject = _super.prototype.serialize.call(this);
  28491. serializationObject.size = this.size;
  28492. return serializationObject;
  28493. };
  28494. Box.Parse = function (parsedBox, scene) {
  28495. if (scene.getGeometryByID(parsedBox.id)) {
  28496. return null; // null since geometry could be something else than a box...
  28497. }
  28498. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28499. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28500. scene.pushGeometry(box, true);
  28501. return box;
  28502. };
  28503. return Box;
  28504. })(_Primitive);
  28505. Primitives.Box = Box;
  28506. var Sphere = (function (_super) {
  28507. __extends(Sphere, _super);
  28508. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28509. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28510. _super.call(this, id, scene, canBeRegenerated, mesh);
  28511. this.segments = segments;
  28512. this.diameter = diameter;
  28513. this.side = side;
  28514. }
  28515. Sphere.prototype._regenerateVertexData = function () {
  28516. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28517. };
  28518. Sphere.prototype.copy = function (id) {
  28519. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28520. };
  28521. Sphere.prototype.serialize = function () {
  28522. var serializationObject = _super.prototype.serialize.call(this);
  28523. serializationObject.segments = this.segments;
  28524. serializationObject.diameter = this.diameter;
  28525. return serializationObject;
  28526. };
  28527. Sphere.Parse = function (parsedSphere, scene) {
  28528. if (scene.getGeometryByID(parsedSphere.id)) {
  28529. return null; // null since geometry could be something else than a sphere...
  28530. }
  28531. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28532. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28533. scene.pushGeometry(sphere, true);
  28534. return sphere;
  28535. };
  28536. return Sphere;
  28537. })(_Primitive);
  28538. Primitives.Sphere = Sphere;
  28539. var Disc = (function (_super) {
  28540. __extends(Disc, _super);
  28541. // Members
  28542. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28544. _super.call(this, id, scene, canBeRegenerated, mesh);
  28545. this.radius = radius;
  28546. this.tessellation = tessellation;
  28547. this.side = side;
  28548. }
  28549. Disc.prototype._regenerateVertexData = function () {
  28550. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28551. };
  28552. Disc.prototype.copy = function (id) {
  28553. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28554. };
  28555. return Disc;
  28556. })(_Primitive);
  28557. Primitives.Disc = Disc;
  28558. var Cylinder = (function (_super) {
  28559. __extends(Cylinder, _super);
  28560. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28561. if (subdivisions === void 0) { subdivisions = 1; }
  28562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28563. _super.call(this, id, scene, canBeRegenerated, mesh);
  28564. this.height = height;
  28565. this.diameterTop = diameterTop;
  28566. this.diameterBottom = diameterBottom;
  28567. this.tessellation = tessellation;
  28568. this.subdivisions = subdivisions;
  28569. this.side = side;
  28570. }
  28571. Cylinder.prototype._regenerateVertexData = function () {
  28572. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28573. };
  28574. Cylinder.prototype.copy = function (id) {
  28575. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28576. };
  28577. Cylinder.prototype.serialize = function () {
  28578. var serializationObject = _super.prototype.serialize.call(this);
  28579. serializationObject.height = this.height;
  28580. serializationObject.diameterTop = this.diameterTop;
  28581. serializationObject.diameterBottom = this.diameterBottom;
  28582. serializationObject.tessellation = this.tessellation;
  28583. return serializationObject;
  28584. };
  28585. Cylinder.Parse = function (parsedCylinder, scene) {
  28586. if (scene.getGeometryByID(parsedCylinder.id)) {
  28587. return null; // null since geometry could be something else than a cylinder...
  28588. }
  28589. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28590. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28591. scene.pushGeometry(cylinder, true);
  28592. return cylinder;
  28593. };
  28594. return Cylinder;
  28595. })(_Primitive);
  28596. Primitives.Cylinder = Cylinder;
  28597. var Torus = (function (_super) {
  28598. __extends(Torus, _super);
  28599. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28600. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28601. _super.call(this, id, scene, canBeRegenerated, mesh);
  28602. this.diameter = diameter;
  28603. this.thickness = thickness;
  28604. this.tessellation = tessellation;
  28605. this.side = side;
  28606. }
  28607. Torus.prototype._regenerateVertexData = function () {
  28608. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28609. };
  28610. Torus.prototype.copy = function (id) {
  28611. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28612. };
  28613. Torus.prototype.serialize = function () {
  28614. var serializationObject = _super.prototype.serialize.call(this);
  28615. serializationObject.diameter = this.diameter;
  28616. serializationObject.thickness = this.thickness;
  28617. serializationObject.tessellation = this.tessellation;
  28618. return serializationObject;
  28619. };
  28620. Torus.Parse = function (parsedTorus, scene) {
  28621. if (scene.getGeometryByID(parsedTorus.id)) {
  28622. return null; // null since geometry could be something else than a torus...
  28623. }
  28624. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28625. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28626. scene.pushGeometry(torus, true);
  28627. return torus;
  28628. };
  28629. return Torus;
  28630. })(_Primitive);
  28631. Primitives.Torus = Torus;
  28632. var Ground = (function (_super) {
  28633. __extends(Ground, _super);
  28634. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28635. _super.call(this, id, scene, canBeRegenerated, mesh);
  28636. this.width = width;
  28637. this.height = height;
  28638. this.subdivisions = subdivisions;
  28639. }
  28640. Ground.prototype._regenerateVertexData = function () {
  28641. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28642. };
  28643. Ground.prototype.copy = function (id) {
  28644. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28645. };
  28646. Ground.prototype.serialize = function () {
  28647. var serializationObject = _super.prototype.serialize.call(this);
  28648. serializationObject.width = this.width;
  28649. serializationObject.height = this.height;
  28650. serializationObject.subdivisions = this.subdivisions;
  28651. return serializationObject;
  28652. };
  28653. Ground.Parse = function (parsedGround, scene) {
  28654. if (scene.getGeometryByID(parsedGround.id)) {
  28655. return null; // null since geometry could be something else than a ground...
  28656. }
  28657. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28658. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28659. scene.pushGeometry(ground, true);
  28660. return ground;
  28661. };
  28662. return Ground;
  28663. })(_Primitive);
  28664. Primitives.Ground = Ground;
  28665. var TiledGround = (function (_super) {
  28666. __extends(TiledGround, _super);
  28667. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28668. _super.call(this, id, scene, canBeRegenerated, mesh);
  28669. this.xmin = xmin;
  28670. this.zmin = zmin;
  28671. this.xmax = xmax;
  28672. this.zmax = zmax;
  28673. this.subdivisions = subdivisions;
  28674. this.precision = precision;
  28675. }
  28676. TiledGround.prototype._regenerateVertexData = function () {
  28677. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28678. };
  28679. TiledGround.prototype.copy = function (id) {
  28680. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28681. };
  28682. return TiledGround;
  28683. })(_Primitive);
  28684. Primitives.TiledGround = TiledGround;
  28685. var Plane = (function (_super) {
  28686. __extends(Plane, _super);
  28687. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28688. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28689. _super.call(this, id, scene, canBeRegenerated, mesh);
  28690. this.size = size;
  28691. this.side = side;
  28692. }
  28693. Plane.prototype._regenerateVertexData = function () {
  28694. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28695. };
  28696. Plane.prototype.copy = function (id) {
  28697. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28698. };
  28699. Plane.prototype.serialize = function () {
  28700. var serializationObject = _super.prototype.serialize.call(this);
  28701. serializationObject.size = this.size;
  28702. return serializationObject;
  28703. };
  28704. Plane.Parse = function (parsedPlane, scene) {
  28705. if (scene.getGeometryByID(parsedPlane.id)) {
  28706. return null; // null since geometry could be something else than a ground...
  28707. }
  28708. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28709. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28710. scene.pushGeometry(plane, true);
  28711. return plane;
  28712. };
  28713. return Plane;
  28714. })(_Primitive);
  28715. Primitives.Plane = Plane;
  28716. var TorusKnot = (function (_super) {
  28717. __extends(TorusKnot, _super);
  28718. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28719. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28720. _super.call(this, id, scene, canBeRegenerated, mesh);
  28721. this.radius = radius;
  28722. this.tube = tube;
  28723. this.radialSegments = radialSegments;
  28724. this.tubularSegments = tubularSegments;
  28725. this.p = p;
  28726. this.q = q;
  28727. this.side = side;
  28728. }
  28729. TorusKnot.prototype._regenerateVertexData = function () {
  28730. 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 });
  28731. };
  28732. TorusKnot.prototype.copy = function (id) {
  28733. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28734. };
  28735. TorusKnot.prototype.serialize = function () {
  28736. var serializationObject = _super.prototype.serialize.call(this);
  28737. serializationObject.radius = this.radius;
  28738. serializationObject.tube = this.tube;
  28739. serializationObject.radialSegments = this.radialSegments;
  28740. serializationObject.tubularSegments = this.tubularSegments;
  28741. serializationObject.p = this.p;
  28742. serializationObject.q = this.q;
  28743. return serializationObject;
  28744. };
  28745. ;
  28746. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28747. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28748. return null; // null since geometry could be something else than a ground...
  28749. }
  28750. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28751. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28752. scene.pushGeometry(torusKnot, true);
  28753. return torusKnot;
  28754. };
  28755. return TorusKnot;
  28756. })(_Primitive);
  28757. Primitives.TorusKnot = TorusKnot;
  28758. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28759. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28760. })(BABYLON || (BABYLON = {}));
  28761. var BABYLON;
  28762. (function (BABYLON) {
  28763. var GroundMesh = (function (_super) {
  28764. __extends(GroundMesh, _super);
  28765. function GroundMesh(name, scene) {
  28766. _super.call(this, name, scene);
  28767. this.generateOctree = false;
  28768. this._worldInverse = new BABYLON.Matrix();
  28769. }
  28770. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28771. get: function () {
  28772. return this._subdivisions;
  28773. },
  28774. enumerable: true,
  28775. configurable: true
  28776. });
  28777. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28778. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28779. this._subdivisions = chunksCount;
  28780. this.subdivide(this._subdivisions);
  28781. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28782. };
  28783. /**
  28784. * Returns a height (y) value in the Worl system :
  28785. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28786. * Returns the ground y position if (x, z) are outside the ground surface.
  28787. * Not pertinent if the ground is rotated.
  28788. */
  28789. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28790. // express x and y in the ground local system
  28791. x -= this.position.x;
  28792. z -= this.position.z;
  28793. x /= this.scaling.x;
  28794. z /= this.scaling.z;
  28795. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28796. return this.position.y;
  28797. }
  28798. if (!this._heightQuads || this._heightQuads.length == 0) {
  28799. this._initHeightQuads();
  28800. this._computeHeightQuads();
  28801. }
  28802. var facet = this._getFacetAt(x, z);
  28803. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28804. // return y in the World system
  28805. return y * this.scaling.y + this.position.y;
  28806. };
  28807. /**
  28808. * Returns a normalized vector (Vector3) orthogonal to the ground
  28809. * at the ground coordinates (x, z) expressed in the World system.
  28810. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28811. * Not pertinent if the ground is rotated.
  28812. */
  28813. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28814. var normal = new BABYLON.Vector3(0, 1, 0);
  28815. this.getNormalAtCoordinatesToRef(x, z, normal);
  28816. return normal;
  28817. };
  28818. /**
  28819. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28820. * at the ground coordinates (x, z) expressed in the World system.
  28821. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28822. * Not pertinent if the ground is rotated.
  28823. */
  28824. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28825. // express x and y in the ground local system
  28826. x -= this.position.x;
  28827. z -= this.position.z;
  28828. x /= this.scaling.x;
  28829. z /= this.scaling.z;
  28830. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28831. return;
  28832. }
  28833. if (!this._heightQuads || this._heightQuads.length == 0) {
  28834. this._initHeightQuads();
  28835. this._computeHeightQuads();
  28836. }
  28837. var facet = this._getFacetAt(x, z);
  28838. ref.x = facet.x;
  28839. ref.y = facet.y;
  28840. ref.z = facet.z;
  28841. };
  28842. /**
  28843. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28844. * if the ground has been updated.
  28845. * This can be used in the render loop
  28846. */
  28847. GroundMesh.prototype.updateCoordinateHeights = function () {
  28848. if (!this._heightQuads || this._heightQuads.length == 0) {
  28849. this._initHeightQuads();
  28850. }
  28851. this._computeHeightQuads();
  28852. };
  28853. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28854. GroundMesh.prototype._getFacetAt = function (x, z) {
  28855. // retrieve col and row from x, z coordinates in the ground local system
  28856. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28857. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28858. var quad = this._heightQuads[row * this._subdivisions + col];
  28859. var facet;
  28860. if (z < quad.slope.x * x + quad.slope.y) {
  28861. facet = quad.facet1;
  28862. }
  28863. else {
  28864. facet = quad.facet2;
  28865. }
  28866. return facet;
  28867. };
  28868. // Creates and populates the heightMap array with "facet" elements :
  28869. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28870. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28871. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28872. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28873. GroundMesh.prototype._initHeightQuads = function () {
  28874. this._heightQuads = new Array();
  28875. for (var row = 0; row < this._subdivisions; row++) {
  28876. for (var col = 0; col < this._subdivisions; col++) {
  28877. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  28878. this._heightQuads[row * this._subdivisions + col] = quad;
  28879. }
  28880. }
  28881. };
  28882. // Compute each quad element values and update the the heightMap array :
  28883. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28884. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28885. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28886. GroundMesh.prototype._computeHeightQuads = function () {
  28887. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28888. var v1 = BABYLON.Tmp.Vector3[0];
  28889. var v2 = BABYLON.Tmp.Vector3[1];
  28890. var v3 = BABYLON.Tmp.Vector3[2];
  28891. var v4 = BABYLON.Tmp.Vector3[3];
  28892. var v1v2 = BABYLON.Tmp.Vector3[4];
  28893. var v1v3 = BABYLON.Tmp.Vector3[5];
  28894. var v1v4 = BABYLON.Tmp.Vector3[6];
  28895. var norm1 = BABYLON.Tmp.Vector3[7];
  28896. var norm2 = BABYLON.Tmp.Vector3[8];
  28897. var i = 0;
  28898. var j = 0;
  28899. var k = 0;
  28900. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28901. var h = 0;
  28902. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28903. var d2 = 0;
  28904. for (var row = 0; row < this._subdivisions; row++) {
  28905. for (var col = 0; col < this._subdivisions; col++) {
  28906. i = col * 3;
  28907. j = row * (this._subdivisions + 1) * 3;
  28908. k = (row + 1) * (this._subdivisions + 1) * 3;
  28909. v1.x = positions[j + i];
  28910. v1.y = positions[j + i + 1];
  28911. v1.z = positions[j + i + 2];
  28912. v2.x = positions[j + i + 3];
  28913. v2.y = positions[j + i + 4];
  28914. v2.z = positions[j + i + 5];
  28915. v3.x = positions[k + i];
  28916. v3.y = positions[k + i + 1];
  28917. v3.z = positions[k + i + 2];
  28918. v4.x = positions[k + i + 3];
  28919. v4.y = positions[k + i + 4];
  28920. v4.z = positions[k + i + 5];
  28921. // 2D slope V1V4
  28922. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28923. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28924. // facet equations :
  28925. // we compute each facet normal vector
  28926. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28927. // we compute the value d by applying the equation to v1 which belongs to the plane
  28928. // then we store the facet equation in a Vector4
  28929. v2.subtractToRef(v1, v1v2);
  28930. v3.subtractToRef(v1, v1v3);
  28931. v4.subtractToRef(v1, v1v4);
  28932. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28933. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28934. norm1.normalize();
  28935. norm2.normalize();
  28936. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28937. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28938. var quad = this._heightQuads[row * this._subdivisions + col];
  28939. quad.slope.copyFromFloats(cd, h);
  28940. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  28941. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  28942. }
  28943. }
  28944. };
  28945. return GroundMesh;
  28946. })(BABYLON.Mesh);
  28947. BABYLON.GroundMesh = GroundMesh;
  28948. })(BABYLON || (BABYLON = {}));
  28949. var BABYLON;
  28950. (function (BABYLON) {
  28951. var LinesMesh = (function (_super) {
  28952. __extends(LinesMesh, _super);
  28953. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28954. if (parent === void 0) { parent = null; }
  28955. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28956. this.color = new BABYLON.Color3(1, 1, 1);
  28957. this.alpha = 1;
  28958. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28959. attributes: ["position"],
  28960. uniforms: ["worldViewProjection", "color"],
  28961. needAlphaBlending: true
  28962. });
  28963. }
  28964. Object.defineProperty(LinesMesh.prototype, "material", {
  28965. get: function () {
  28966. return this._colorShader;
  28967. },
  28968. enumerable: true,
  28969. configurable: true
  28970. });
  28971. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28972. get: function () {
  28973. return false;
  28974. },
  28975. enumerable: true,
  28976. configurable: true
  28977. });
  28978. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28979. get: function () {
  28980. return false;
  28981. },
  28982. enumerable: true,
  28983. configurable: true
  28984. });
  28985. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28986. var engine = this.getScene().getEngine();
  28987. var indexToBind = this._geometry.getIndexBuffer();
  28988. // VBOs
  28989. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28990. // Color
  28991. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28992. };
  28993. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28994. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28995. return;
  28996. }
  28997. var engine = this.getScene().getEngine();
  28998. // Draw order
  28999. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29000. };
  29001. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29002. return null;
  29003. };
  29004. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29005. this._colorShader.dispose();
  29006. _super.prototype.dispose.call(this, doNotRecurse);
  29007. };
  29008. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29009. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29010. };
  29011. return LinesMesh;
  29012. })(BABYLON.Mesh);
  29013. BABYLON.LinesMesh = LinesMesh;
  29014. })(BABYLON || (BABYLON = {}));
  29015. var BABYLON;
  29016. (function (BABYLON) {
  29017. var DebugLayer = (function () {
  29018. function DebugLayer(scene) {
  29019. var _this = this;
  29020. this._transformationMatrix = BABYLON.Matrix.Identity();
  29021. this._enabled = false;
  29022. this._labelsEnabled = false;
  29023. this._displayStatistics = true;
  29024. this._displayTree = false;
  29025. this._displayLogs = false;
  29026. this._identityMatrix = BABYLON.Matrix.Identity();
  29027. this.axisRatio = 0.02;
  29028. this.accentColor = "orange";
  29029. this._scene = scene;
  29030. this._syncPositions = function () {
  29031. var engine = _this._scene.getEngine();
  29032. var canvasRect = engine.getRenderingCanvasClientRect();
  29033. if (_this._showUI) {
  29034. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29035. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29036. _this._statsDiv.style.width = "400px";
  29037. _this._statsDiv.style.height = "auto";
  29038. _this._statsSubsetDiv.style.maxHeight = "240px";
  29039. _this._optionsDiv.style.left = "0px";
  29040. _this._optionsDiv.style.top = "10px";
  29041. _this._optionsDiv.style.width = "200px";
  29042. _this._optionsDiv.style.height = "auto";
  29043. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29044. _this._logDiv.style.left = "0px";
  29045. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29046. _this._logDiv.style.width = "600px";
  29047. _this._logDiv.style.height = "160px";
  29048. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29049. _this._treeDiv.style.top = "10px";
  29050. _this._treeDiv.style.width = "300px";
  29051. _this._treeDiv.style.height = "auto";
  29052. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29053. }
  29054. _this._globalDiv.style.left = canvasRect.left + "px";
  29055. _this._globalDiv.style.top = canvasRect.top + "px";
  29056. _this._drawingCanvas.style.left = "0px";
  29057. _this._drawingCanvas.style.top = "0px";
  29058. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29059. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29060. var devicePixelRatio = window.devicePixelRatio || 1;
  29061. var context = _this._drawingContext;
  29062. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29063. context.mozBackingStorePixelRatio ||
  29064. context.msBackingStorePixelRatio ||
  29065. context.oBackingStorePixelRatio ||
  29066. context.backingStorePixelRatio || 1;
  29067. _this._ratio = devicePixelRatio / backingStoreRatio;
  29068. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29069. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29070. };
  29071. this._onCanvasClick = function (evt) {
  29072. _this._clickPosition = {
  29073. x: evt.clientX * _this._ratio,
  29074. y: evt.clientY * _this._ratio
  29075. };
  29076. };
  29077. this._syncUI = function () {
  29078. if (_this._showUI) {
  29079. if (_this._displayStatistics) {
  29080. _this._displayStats();
  29081. _this._statsDiv.style.display = "";
  29082. }
  29083. else {
  29084. _this._statsDiv.style.display = "none";
  29085. }
  29086. if (_this._displayLogs) {
  29087. _this._logDiv.style.display = "";
  29088. }
  29089. else {
  29090. _this._logDiv.style.display = "none";
  29091. }
  29092. if (_this._displayTree) {
  29093. _this._treeDiv.style.display = "";
  29094. if (_this._needToRefreshMeshesTree) {
  29095. _this._needToRefreshMeshesTree = false;
  29096. _this._refreshMeshesTreeContent();
  29097. }
  29098. }
  29099. else {
  29100. _this._treeDiv.style.display = "none";
  29101. }
  29102. }
  29103. };
  29104. this._syncData = function () {
  29105. if (_this._labelsEnabled || !_this._showUI) {
  29106. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29107. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29108. var engine = _this._scene.getEngine();
  29109. var viewport = _this._camera.viewport;
  29110. var globalViewport = viewport.toGlobal(engine);
  29111. // Meshes
  29112. var meshes = _this._camera.getActiveMeshes();
  29113. var index;
  29114. var projectedPosition;
  29115. for (index = 0; index < meshes.length; index++) {
  29116. var mesh = meshes.data[index];
  29117. var position = mesh.getBoundingInfo().boundingSphere.center;
  29118. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29119. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29120. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29121. }
  29122. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29123. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29124. }
  29125. }
  29126. // Cameras
  29127. var cameras = _this._scene.cameras;
  29128. for (index = 0; index < cameras.length; index++) {
  29129. var camera = cameras[index];
  29130. if (camera === _this._camera) {
  29131. continue;
  29132. }
  29133. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29134. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29135. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29136. _this._camera.detachControl(engine.getRenderingCanvas());
  29137. _this._camera = camera;
  29138. _this._camera.attachControl(engine.getRenderingCanvas());
  29139. }, function () { return "purple"; });
  29140. }
  29141. }
  29142. // Lights
  29143. var lights = _this._scene.lights;
  29144. for (index = 0; index < lights.length; index++) {
  29145. var light = lights[index];
  29146. if (light.position) {
  29147. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29148. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29149. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29150. light.setEnabled(!light.isEnabled());
  29151. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29152. }
  29153. }
  29154. }
  29155. }
  29156. _this._clickPosition = undefined;
  29157. };
  29158. }
  29159. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29160. while (this._treeSubsetDiv.hasChildNodes()) {
  29161. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29162. }
  29163. // Add meshes
  29164. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29165. sortedArray.sort(function (a, b) {
  29166. if (a.name === b.name) {
  29167. return 0;
  29168. }
  29169. return (a.name > b.name) ? 1 : -1;
  29170. });
  29171. for (var index = 0; index < sortedArray.length; index++) {
  29172. var mesh = sortedArray[index];
  29173. if (!mesh.isEnabled()) {
  29174. continue;
  29175. }
  29176. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29177. m.isVisible = element.checked;
  29178. }, mesh);
  29179. }
  29180. };
  29181. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29182. this._drawingContext.beginPath();
  29183. this._drawingContext.moveTo(zero.x, zero.y);
  29184. this._drawingContext.lineTo(unit.x, unit.y);
  29185. this._drawingContext.strokeStyle = color;
  29186. this._drawingContext.lineWidth = 4;
  29187. this._drawingContext.stroke();
  29188. this._drawingContext.font = "normal 14px Segoe UI";
  29189. this._drawingContext.fillStyle = color;
  29190. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29191. };
  29192. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29193. var position = mesh.getBoundingInfo().boundingSphere.center;
  29194. var worldMatrix = mesh.getWorldMatrix();
  29195. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29196. var unit = (unprojectedVector.subtract(position)).length();
  29197. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29198. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29199. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29200. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29201. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29202. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29203. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29204. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29205. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29206. };
  29207. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29208. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29209. this._drawingContext.font = "normal 12px Segoe UI";
  29210. var textMetrics = this._drawingContext.measureText(text);
  29211. var centerX = projectedPosition.x - textMetrics.width / 2;
  29212. var centerY = projectedPosition.y;
  29213. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29214. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29215. onClick();
  29216. }
  29217. this._drawingContext.beginPath();
  29218. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29219. this._drawingContext.fillStyle = getFillStyle();
  29220. this._drawingContext.globalAlpha = 0.5;
  29221. this._drawingContext.fill();
  29222. this._drawingContext.globalAlpha = 1.0;
  29223. this._drawingContext.strokeStyle = '#FFFFFF';
  29224. this._drawingContext.lineWidth = 1;
  29225. this._drawingContext.stroke();
  29226. this._drawingContext.fillStyle = "#FFFFFF";
  29227. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29228. this._drawingContext.beginPath();
  29229. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29230. this._drawingContext.fill();
  29231. }
  29232. };
  29233. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29234. if (!this._clickPosition) {
  29235. return false;
  29236. }
  29237. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29238. return false;
  29239. }
  29240. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29241. return false;
  29242. }
  29243. return true;
  29244. };
  29245. DebugLayer.prototype.isVisible = function () {
  29246. return this._enabled;
  29247. };
  29248. DebugLayer.prototype.hide = function () {
  29249. if (!this._enabled) {
  29250. return;
  29251. }
  29252. this._enabled = false;
  29253. var engine = this._scene.getEngine();
  29254. this._scene.unregisterBeforeRender(this._syncData);
  29255. this._scene.unregisterAfterRender(this._syncUI);
  29256. this._rootElement.removeChild(this._globalDiv);
  29257. this._scene.forceShowBoundingBoxes = false;
  29258. this._scene.forceWireframe = false;
  29259. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29260. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29261. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29262. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29263. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29264. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29265. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29266. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29267. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29268. this._scene.shadowsEnabled = true;
  29269. this._scene.particlesEnabled = true;
  29270. this._scene.postProcessesEnabled = true;
  29271. this._scene.collisionsEnabled = true;
  29272. this._scene.lightsEnabled = true;
  29273. this._scene.texturesEnabled = true;
  29274. this._scene.lensFlaresEnabled = true;
  29275. this._scene.proceduralTexturesEnabled = true;
  29276. this._scene.renderTargetsEnabled = true;
  29277. this._scene.probesEnabled = true;
  29278. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29279. };
  29280. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29281. if (showUI === void 0) { showUI = true; }
  29282. if (camera === void 0) { camera = null; }
  29283. if (rootElement === void 0) { rootElement = null; }
  29284. if (this._enabled) {
  29285. return;
  29286. }
  29287. this._enabled = true;
  29288. if (camera) {
  29289. this._camera = camera;
  29290. }
  29291. else {
  29292. this._camera = this._scene.activeCamera;
  29293. }
  29294. this._showUI = showUI;
  29295. var engine = this._scene.getEngine();
  29296. this._globalDiv = document.createElement("div");
  29297. this._rootElement = rootElement || document.body;
  29298. this._rootElement.appendChild(this._globalDiv);
  29299. this._generateDOMelements();
  29300. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29301. this._syncPositions();
  29302. this._scene.registerBeforeRender(this._syncData);
  29303. this._scene.registerAfterRender(this._syncUI);
  29304. };
  29305. DebugLayer.prototype._clearLabels = function () {
  29306. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29307. for (var index = 0; index < this._scene.meshes.length; index++) {
  29308. var mesh = this._scene.meshes[index];
  29309. mesh.renderOverlay = false;
  29310. }
  29311. };
  29312. DebugLayer.prototype._generateheader = function (root, text) {
  29313. var header = document.createElement("div");
  29314. header.innerHTML = text + "&nbsp;";
  29315. header.style.textAlign = "right";
  29316. header.style.width = "100%";
  29317. header.style.color = "white";
  29318. header.style.backgroundColor = "Black";
  29319. header.style.padding = "5px 5px 4px 0px";
  29320. header.style.marginLeft = "-5px";
  29321. header.style.fontWeight = "bold";
  29322. root.appendChild(header);
  29323. };
  29324. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29325. var label = document.createElement("label");
  29326. label.innerHTML = title;
  29327. label.style.color = color;
  29328. root.appendChild(label);
  29329. root.appendChild(document.createElement("br"));
  29330. };
  29331. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29332. if (tag === void 0) { tag = null; }
  29333. var label = document.createElement("label");
  29334. var boundingBoxesCheckbox = document.createElement("input");
  29335. boundingBoxesCheckbox.type = "checkbox";
  29336. boundingBoxesCheckbox.checked = initialState;
  29337. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29338. task(evt.target, tag);
  29339. });
  29340. label.appendChild(boundingBoxesCheckbox);
  29341. var container = document.createElement("span");
  29342. var leftPart = document.createElement("span");
  29343. var rightPart = document.createElement("span");
  29344. rightPart.style.cssFloat = "right";
  29345. leftPart.innerHTML = leftTitle;
  29346. rightPart.innerHTML = rightTitle;
  29347. rightPart.style.fontSize = "12px";
  29348. rightPart.style.maxWidth = "200px";
  29349. container.appendChild(leftPart);
  29350. container.appendChild(rightPart);
  29351. label.appendChild(container);
  29352. root.appendChild(label);
  29353. root.appendChild(document.createElement("br"));
  29354. };
  29355. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29356. if (tag === void 0) { tag = null; }
  29357. var label = document.createElement("label");
  29358. var checkBox = document.createElement("input");
  29359. checkBox.type = "checkbox";
  29360. checkBox.checked = initialState;
  29361. checkBox.addEventListener("change", function (evt) {
  29362. task(evt.target, tag);
  29363. });
  29364. label.appendChild(checkBox);
  29365. label.appendChild(document.createTextNode(title));
  29366. root.appendChild(label);
  29367. root.appendChild(document.createElement("br"));
  29368. };
  29369. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29370. if (tag === void 0) { tag = null; }
  29371. var button = document.createElement("button");
  29372. button.innerHTML = title;
  29373. button.style.height = "24px";
  29374. button.style.width = "150px";
  29375. button.style.marginBottom = "5px";
  29376. button.style.color = "#444444";
  29377. button.style.border = "1px solid white";
  29378. button.className = "debugLayerButton";
  29379. button.addEventListener("click", function (evt) {
  29380. task(evt.target, tag);
  29381. });
  29382. root.appendChild(button);
  29383. root.appendChild(document.createElement("br"));
  29384. };
  29385. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29386. if (tag === void 0) { tag = null; }
  29387. var label = document.createElement("label");
  29388. var boundingBoxesRadio = document.createElement("input");
  29389. boundingBoxesRadio.type = "radio";
  29390. boundingBoxesRadio.name = name;
  29391. boundingBoxesRadio.checked = initialState;
  29392. boundingBoxesRadio.addEventListener("change", function (evt) {
  29393. task(evt.target, tag);
  29394. });
  29395. label.appendChild(boundingBoxesRadio);
  29396. label.appendChild(document.createTextNode(title));
  29397. root.appendChild(label);
  29398. root.appendChild(document.createElement("br"));
  29399. };
  29400. DebugLayer.prototype._generateDOMelements = function () {
  29401. var _this = this;
  29402. this._globalDiv.id = "DebugLayer";
  29403. this._globalDiv.style.position = "absolute";
  29404. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29405. this._globalDiv.style.fontSize = "14px";
  29406. this._globalDiv.style.color = "white";
  29407. // Drawing canvas
  29408. this._drawingCanvas = document.createElement("canvas");
  29409. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29410. this._drawingCanvas.style.position = "absolute";
  29411. this._drawingCanvas.style.pointerEvents = "none";
  29412. this._drawingCanvas.style.backgroundColor = "transparent";
  29413. this._drawingContext = this._drawingCanvas.getContext("2d");
  29414. this._globalDiv.appendChild(this._drawingCanvas);
  29415. if (this._showUI) {
  29416. var background = "rgba(128, 128, 128, 0.4)";
  29417. var border = "rgb(180, 180, 180) solid 1px";
  29418. // Stats
  29419. this._statsDiv = document.createElement("div");
  29420. this._statsDiv.id = "DebugLayerStats";
  29421. this._statsDiv.style.border = border;
  29422. this._statsDiv.style.position = "absolute";
  29423. this._statsDiv.style.background = background;
  29424. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29425. this._generateheader(this._statsDiv, "STATISTICS");
  29426. this._statsSubsetDiv = document.createElement("div");
  29427. this._statsSubsetDiv.style.paddingTop = "5px";
  29428. this._statsSubsetDiv.style.paddingBottom = "5px";
  29429. this._statsSubsetDiv.style.overflowY = "auto";
  29430. this._statsDiv.appendChild(this._statsSubsetDiv);
  29431. // Tree
  29432. this._treeDiv = document.createElement("div");
  29433. this._treeDiv.id = "DebugLayerTree";
  29434. this._treeDiv.style.border = border;
  29435. this._treeDiv.style.position = "absolute";
  29436. this._treeDiv.style.background = background;
  29437. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29438. this._treeDiv.style.display = "none";
  29439. this._generateheader(this._treeDiv, "MESHES TREE");
  29440. this._treeSubsetDiv = document.createElement("div");
  29441. this._treeSubsetDiv.style.paddingTop = "5px";
  29442. this._treeSubsetDiv.style.paddingRight = "5px";
  29443. this._treeSubsetDiv.style.overflowY = "auto";
  29444. this._treeSubsetDiv.style.maxHeight = "300px";
  29445. this._treeDiv.appendChild(this._treeSubsetDiv);
  29446. this._needToRefreshMeshesTree = true;
  29447. // Logs
  29448. this._logDiv = document.createElement("div");
  29449. this._logDiv.style.border = border;
  29450. this._logDiv.id = "DebugLayerLogs";
  29451. this._logDiv.style.position = "absolute";
  29452. this._logDiv.style.background = background;
  29453. this._logDiv.style.padding = "0px 0px 0px 5px";
  29454. this._logDiv.style.display = "none";
  29455. this._generateheader(this._logDiv, "LOGS");
  29456. this._logSubsetDiv = document.createElement("div");
  29457. this._logSubsetDiv.style.height = "127px";
  29458. this._logSubsetDiv.style.paddingTop = "5px";
  29459. this._logSubsetDiv.style.overflowY = "auto";
  29460. this._logSubsetDiv.style.fontSize = "12px";
  29461. this._logSubsetDiv.style.fontFamily = "consolas";
  29462. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29463. this._logDiv.appendChild(this._logSubsetDiv);
  29464. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29465. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29466. };
  29467. // Options
  29468. this._optionsDiv = document.createElement("div");
  29469. this._optionsDiv.id = "DebugLayerOptions";
  29470. this._optionsDiv.style.border = border;
  29471. this._optionsDiv.style.position = "absolute";
  29472. this._optionsDiv.style.background = background;
  29473. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29474. this._optionsDiv.style.overflowY = "auto";
  29475. this._generateheader(this._optionsDiv, "OPTIONS");
  29476. this._optionsSubsetDiv = document.createElement("div");
  29477. this._optionsSubsetDiv.style.paddingTop = "5px";
  29478. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29479. this._optionsSubsetDiv.style.overflowY = "auto";
  29480. this._optionsSubsetDiv.style.maxHeight = "200px";
  29481. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29482. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29483. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29484. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29485. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29486. _this._displayTree = element.checked;
  29487. _this._needToRefreshMeshesTree = true;
  29488. });
  29489. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29490. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29491. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29492. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29493. _this._labelsEnabled = element.checked;
  29494. if (!_this._labelsEnabled) {
  29495. _this._clearLabels();
  29496. }
  29497. });
  29498. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29499. if (element.checked) {
  29500. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29501. }
  29502. else {
  29503. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29504. }
  29505. });
  29506. ;
  29507. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29508. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29509. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29510. if (element.checked) {
  29511. _this._scene.forceWireframe = false;
  29512. _this._scene.forcePointsCloud = false;
  29513. }
  29514. });
  29515. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29516. if (element.checked) {
  29517. _this._scene.forceWireframe = true;
  29518. _this._scene.forcePointsCloud = false;
  29519. }
  29520. });
  29521. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29522. if (element.checked) {
  29523. _this._scene.forceWireframe = false;
  29524. _this._scene.forcePointsCloud = true;
  29525. }
  29526. });
  29527. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29528. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29529. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29530. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29531. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29532. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29533. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29534. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29535. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29536. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29537. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29538. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29539. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29540. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29541. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29542. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29543. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29544. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29545. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29546. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29547. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29548. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29549. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29550. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29551. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29552. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29553. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29554. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29555. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29556. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29557. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29558. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29559. if (element.checked) {
  29560. _this._scene.headphone = true;
  29561. }
  29562. });
  29563. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29564. if (element.checked) {
  29565. _this._scene.headphone = false;
  29566. }
  29567. });
  29568. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29569. _this._scene.audioEnabled = !element.checked;
  29570. });
  29571. }
  29572. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29573. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29574. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29575. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29576. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29577. if (_this._camera) {
  29578. console.log(_this._camera);
  29579. }
  29580. else {
  29581. console.warn("No camera defined, or debug layer created before camera creation!");
  29582. }
  29583. });
  29584. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29585. this._globalDiv.appendChild(this._statsDiv);
  29586. this._globalDiv.appendChild(this._logDiv);
  29587. this._globalDiv.appendChild(this._optionsDiv);
  29588. this._globalDiv.appendChild(this._treeDiv);
  29589. }
  29590. };
  29591. DebugLayer.prototype._displayStats = function () {
  29592. var scene = this._scene;
  29593. var engine = scene.getEngine();
  29594. var glInfo = engine.getGlInfo();
  29595. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29596. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29597. + "<b>Count</b><br>"
  29598. + "Total meshes: " + scene.meshes.length + "<br>"
  29599. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29600. + "Total materials: " + scene.materials.length + "<br>"
  29601. + "Total textures: " + scene.textures.length + "<br>"
  29602. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29603. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29604. + "Active bones: " + scene.getActiveBones() + "<br>"
  29605. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29606. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29607. + "<b>Duration</b><br>"
  29608. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29609. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29610. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29611. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29612. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29613. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29614. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29615. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29616. + "</div>"
  29617. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29618. + "<b>Extensions</b><br>"
  29619. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29620. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29621. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29622. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29623. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29624. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29625. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29626. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29627. + "</div><br>"
  29628. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29629. + "<b>Caps.</b><br>"
  29630. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29631. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29632. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29633. + "<b>Info</b><br>"
  29634. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29635. + glInfo.version + "<br>"
  29636. + "</div><br>"
  29637. + glInfo.renderer + "<br>";
  29638. if (this.customStatsFunction) {
  29639. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29640. }
  29641. };
  29642. return DebugLayer;
  29643. })();
  29644. BABYLON.DebugLayer = DebugLayer;
  29645. })(BABYLON || (BABYLON = {}));
  29646. var BABYLON;
  29647. (function (BABYLON) {
  29648. var DefaultLoadingScreen = (function () {
  29649. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29650. var _this = this;
  29651. if (_loadingText === void 0) { _loadingText = ""; }
  29652. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29653. this._renderingCanvas = _renderingCanvas;
  29654. this._loadingText = _loadingText;
  29655. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29656. // Resize
  29657. this._resizeLoadingUI = function () {
  29658. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29659. _this._loadingDiv.style.position = "absolute";
  29660. _this._loadingDiv.style.left = canvasRect.left + "px";
  29661. _this._loadingDiv.style.top = canvasRect.top + "px";
  29662. _this._loadingDiv.style.width = canvasRect.width + "px";
  29663. _this._loadingDiv.style.height = canvasRect.height + "px";
  29664. };
  29665. }
  29666. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29667. var _this = this;
  29668. if (this._loadingDiv) {
  29669. // Do not add a loading screen if there is already one
  29670. return;
  29671. }
  29672. this._loadingDiv = document.createElement("div");
  29673. this._loadingDiv.id = "babylonjsLoadingDiv";
  29674. this._loadingDiv.style.opacity = "0";
  29675. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29676. // Loading text
  29677. this._loadingTextDiv = document.createElement("div");
  29678. this._loadingTextDiv.style.position = "absolute";
  29679. this._loadingTextDiv.style.left = "0";
  29680. this._loadingTextDiv.style.top = "50%";
  29681. this._loadingTextDiv.style.marginTop = "80px";
  29682. this._loadingTextDiv.style.width = "100%";
  29683. this._loadingTextDiv.style.height = "20px";
  29684. this._loadingTextDiv.style.fontFamily = "Arial";
  29685. this._loadingTextDiv.style.fontSize = "14px";
  29686. this._loadingTextDiv.style.color = "white";
  29687. this._loadingTextDiv.style.textAlign = "center";
  29688. this._loadingTextDiv.innerHTML = "Loading";
  29689. this._loadingDiv.appendChild(this._loadingTextDiv);
  29690. //set the predefined text
  29691. this._loadingTextDiv.innerHTML = this._loadingText;
  29692. // Loading img
  29693. var imgBack = new Image();
  29694. 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==";
  29695. imgBack.style.position = "absolute";
  29696. imgBack.style.left = "50%";
  29697. imgBack.style.top = "50%";
  29698. imgBack.style.marginLeft = "-50px";
  29699. imgBack.style.marginTop = "-50px";
  29700. imgBack.style.transition = "transform 1.0s ease";
  29701. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29702. var deg = 360;
  29703. var onTransitionEnd = function () {
  29704. deg += 360;
  29705. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29706. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29707. };
  29708. imgBack.addEventListener("transitionend", onTransitionEnd);
  29709. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29710. this._loadingDiv.appendChild(imgBack);
  29711. // front image
  29712. var imgFront = new Image();
  29713. 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=";
  29714. imgFront.style.position = "absolute";
  29715. imgFront.style.left = "50%";
  29716. imgFront.style.top = "50%";
  29717. imgFront.style.marginLeft = "-50px";
  29718. imgFront.style.marginTop = "-50px";
  29719. this._loadingDiv.appendChild(imgFront);
  29720. this._resizeLoadingUI();
  29721. window.addEventListener("resize", this._resizeLoadingUI);
  29722. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29723. document.body.appendChild(this._loadingDiv);
  29724. setTimeout(function () {
  29725. _this._loadingDiv.style.opacity = "1";
  29726. imgBack.style.transform = "rotateZ(360deg)";
  29727. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29728. }, 0);
  29729. };
  29730. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29731. var _this = this;
  29732. if (!this._loadingDiv) {
  29733. return;
  29734. }
  29735. var onTransitionEnd = function () {
  29736. if (!_this._loadingDiv) {
  29737. return;
  29738. }
  29739. document.body.removeChild(_this._loadingDiv);
  29740. window.removeEventListener("resize", _this._resizeLoadingUI);
  29741. _this._loadingDiv = null;
  29742. };
  29743. this._loadingDiv.style.opacity = "0";
  29744. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29745. };
  29746. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29747. set: function (text) {
  29748. this._loadingText = text;
  29749. if (this._loadingTextDiv) {
  29750. this._loadingTextDiv.innerHTML = this._loadingText;
  29751. }
  29752. },
  29753. enumerable: true,
  29754. configurable: true
  29755. });
  29756. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29757. get: function () {
  29758. return this._loadingDivBackgroundColor;
  29759. },
  29760. set: function (color) {
  29761. this._loadingDivBackgroundColor = color;
  29762. if (!this._loadingDiv) {
  29763. return;
  29764. }
  29765. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29766. },
  29767. enumerable: true,
  29768. configurable: true
  29769. });
  29770. return DefaultLoadingScreen;
  29771. })();
  29772. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29773. })(BABYLON || (BABYLON = {}));
  29774. var BABYLON;
  29775. (function (BABYLON) {
  29776. var AudioEngine = (function () {
  29777. function AudioEngine() {
  29778. this._audioContext = null;
  29779. this._audioContextInitialized = false;
  29780. this.canUseWebAudio = false;
  29781. this.WarnedWebAudioUnsupported = false;
  29782. this.unlocked = false;
  29783. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29784. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29785. this.canUseWebAudio = true;
  29786. }
  29787. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  29788. this._unlockiOSaudio();
  29789. }
  29790. else {
  29791. this.unlocked = true;
  29792. }
  29793. }
  29794. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29795. get: function () {
  29796. if (!this._audioContextInitialized) {
  29797. this._initializeAudioContext();
  29798. }
  29799. return this._audioContext;
  29800. },
  29801. enumerable: true,
  29802. configurable: true
  29803. });
  29804. AudioEngine.prototype._unlockiOSaudio = function () {
  29805. var _this = this;
  29806. var unlockaudio = function () {
  29807. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  29808. var source = _this.audioContext.createBufferSource();
  29809. source.buffer = buffer;
  29810. source.connect(_this.audioContext.destination);
  29811. source.start(0);
  29812. setTimeout(function () {
  29813. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  29814. _this.unlocked = true;
  29815. window.removeEventListener('touchend', unlockaudio, false);
  29816. if (_this.onAudioUnlocked) {
  29817. _this.onAudioUnlocked();
  29818. }
  29819. }
  29820. }, 0);
  29821. };
  29822. window.addEventListener('touchend', unlockaudio, false);
  29823. };
  29824. AudioEngine.prototype._initializeAudioContext = function () {
  29825. try {
  29826. if (this.canUseWebAudio) {
  29827. this._audioContext = new AudioContext();
  29828. // create a global volume gain node
  29829. this.masterGain = this._audioContext.createGain();
  29830. this.masterGain.gain.value = 1;
  29831. this.masterGain.connect(this._audioContext.destination);
  29832. this._audioContextInitialized = true;
  29833. }
  29834. }
  29835. catch (e) {
  29836. this.canUseWebAudio = false;
  29837. BABYLON.Tools.Error("Web Audio: " + e.message);
  29838. }
  29839. };
  29840. AudioEngine.prototype.dispose = function () {
  29841. if (this.canUseWebAudio && this._audioContextInitialized) {
  29842. if (this._connectedAnalyser) {
  29843. this._connectedAnalyser.stopDebugCanvas();
  29844. this._connectedAnalyser.dispose();
  29845. this.masterGain.disconnect();
  29846. this.masterGain.connect(this._audioContext.destination);
  29847. this._connectedAnalyser = null;
  29848. }
  29849. this.masterGain.gain.value = 1;
  29850. }
  29851. this.WarnedWebAudioUnsupported = false;
  29852. };
  29853. AudioEngine.prototype.getGlobalVolume = function () {
  29854. if (this.canUseWebAudio && this._audioContextInitialized) {
  29855. return this.masterGain.gain.value;
  29856. }
  29857. else {
  29858. return -1;
  29859. }
  29860. };
  29861. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29862. if (this.canUseWebAudio && this._audioContextInitialized) {
  29863. this.masterGain.gain.value = newVolume;
  29864. }
  29865. };
  29866. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29867. if (this._connectedAnalyser) {
  29868. this._connectedAnalyser.stopDebugCanvas();
  29869. }
  29870. if (this.canUseWebAudio && this._audioContextInitialized) {
  29871. this._connectedAnalyser = analyser;
  29872. this.masterGain.disconnect();
  29873. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29874. }
  29875. };
  29876. return AudioEngine;
  29877. })();
  29878. BABYLON.AudioEngine = AudioEngine;
  29879. })(BABYLON || (BABYLON = {}));
  29880. var BABYLON;
  29881. (function (BABYLON) {
  29882. var Sound = (function () {
  29883. /**
  29884. * Create a sound and attach it to a scene
  29885. * @param name Name of your sound
  29886. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29887. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29888. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  29889. */
  29890. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29891. var _this = this;
  29892. this.autoplay = false;
  29893. this.loop = false;
  29894. this.useCustomAttenuation = false;
  29895. this.spatialSound = false;
  29896. this.refDistance = 1;
  29897. this.rolloffFactor = 1;
  29898. this.maxDistance = 100;
  29899. this.distanceModel = "linear";
  29900. this._panningModel = "equalpower";
  29901. this._playbackRate = 1;
  29902. this._streaming = false;
  29903. this._startTime = 0;
  29904. this._startOffset = 0;
  29905. this._position = BABYLON.Vector3.Zero();
  29906. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29907. this._volume = 1;
  29908. this._isLoaded = false;
  29909. this._isReadyToPlay = false;
  29910. this.isPlaying = false;
  29911. this.isPaused = false;
  29912. this._isDirectional = false;
  29913. // Used if you'd like to create a directional sound.
  29914. // If not set, the sound will be omnidirectional
  29915. this._coneInnerAngle = 360;
  29916. this._coneOuterAngle = 360;
  29917. this._coneOuterGain = 0;
  29918. this._isOutputConnected = false;
  29919. this.name = name;
  29920. this._scene = scene;
  29921. this._readyToPlayCallback = readyToPlayCallback;
  29922. // Default custom attenuation function is a linear attenuation
  29923. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29924. if (currentDistance < maxDistance) {
  29925. return currentVolume * (1 - currentDistance / maxDistance);
  29926. }
  29927. else {
  29928. return 0;
  29929. }
  29930. };
  29931. if (options) {
  29932. this.autoplay = options.autoplay || false;
  29933. this.loop = options.loop || false;
  29934. // if volume === 0, we need another way to check this option
  29935. if (options.volume !== undefined) {
  29936. this._volume = options.volume;
  29937. }
  29938. this.spatialSound = options.spatialSound || false;
  29939. this.maxDistance = options.maxDistance || 100;
  29940. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29941. this.rolloffFactor = options.rolloffFactor || 1;
  29942. this.refDistance = options.refDistance || 1;
  29943. this.distanceModel = options.distanceModel || "linear";
  29944. this._playbackRate = options.playbackRate || 1;
  29945. this._streaming = options.streaming || false;
  29946. }
  29947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29948. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29949. this._soundGain.gain.value = this._volume;
  29950. this._inputAudioNode = this._soundGain;
  29951. this._ouputAudioNode = this._soundGain;
  29952. if (this.spatialSound) {
  29953. this._createSpatialParameters();
  29954. }
  29955. this._scene.mainSoundTrack.AddSound(this);
  29956. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29957. if (urlOrArrayBuffer) {
  29958. // If it's an URL
  29959. if (typeof (urlOrArrayBuffer) === "string") {
  29960. // Loading sound using XHR2
  29961. if (!this._streaming) {
  29962. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  29963. }
  29964. else {
  29965. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  29966. this._htmlAudioElement.controls = false;
  29967. this._htmlAudioElement.loop = this.loop;
  29968. this._htmlAudioElement.crossOrigin = "anonymous";
  29969. this._htmlAudioElement.preload = "auto";
  29970. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  29971. _this._isReadyToPlay = true;
  29972. if (_this.autoplay) {
  29973. _this.play();
  29974. }
  29975. if (_this._readyToPlayCallback) {
  29976. _this._readyToPlayCallback();
  29977. }
  29978. });
  29979. document.body.appendChild(this._htmlAudioElement);
  29980. }
  29981. }
  29982. else {
  29983. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29984. if (urlOrArrayBuffer.byteLength > 0) {
  29985. this._soundLoaded(urlOrArrayBuffer);
  29986. }
  29987. }
  29988. else {
  29989. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29990. }
  29991. }
  29992. }
  29993. }
  29994. else {
  29995. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29996. this._scene.mainSoundTrack.AddSound(this);
  29997. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29998. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29999. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30000. }
  30001. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30002. if (this._readyToPlayCallback) {
  30003. window.setTimeout(function () {
  30004. _this._readyToPlayCallback();
  30005. }, 1000);
  30006. }
  30007. }
  30008. }
  30009. Sound.prototype.dispose = function () {
  30010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30011. if (this.isPlaying) {
  30012. this.stop();
  30013. }
  30014. this._isReadyToPlay = false;
  30015. if (this.soundTrackId === -1) {
  30016. this._scene.mainSoundTrack.RemoveSound(this);
  30017. }
  30018. else {
  30019. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30020. }
  30021. if (this._soundGain) {
  30022. this._soundGain.disconnect();
  30023. this._soundGain = null;
  30024. }
  30025. if (this._soundPanner) {
  30026. this._soundPanner.disconnect();
  30027. this._soundPanner = null;
  30028. }
  30029. if (this._soundSource) {
  30030. this._soundSource.disconnect();
  30031. this._soundSource = null;
  30032. }
  30033. this._audioBuffer = null;
  30034. if (this._htmlAudioElement) {
  30035. this._htmlAudioElement.pause();
  30036. this._htmlAudioElement.src = "";
  30037. document.body.removeChild(this._htmlAudioElement);
  30038. }
  30039. if (this._connectedMesh) {
  30040. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30041. this._connectedMesh = null;
  30042. }
  30043. }
  30044. };
  30045. Sound.prototype._soundLoaded = function (audioData) {
  30046. var _this = this;
  30047. this._isLoaded = true;
  30048. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30049. _this._audioBuffer = buffer;
  30050. _this._isReadyToPlay = true;
  30051. if (_this.autoplay) {
  30052. _this.play();
  30053. }
  30054. if (_this._readyToPlayCallback) {
  30055. _this._readyToPlayCallback();
  30056. }
  30057. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30058. };
  30059. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30060. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30061. this._audioBuffer = audioBuffer;
  30062. this._isReadyToPlay = true;
  30063. }
  30064. };
  30065. Sound.prototype.updateOptions = function (options) {
  30066. if (options) {
  30067. this.loop = options.loop || this.loop;
  30068. this.maxDistance = options.maxDistance || this.maxDistance;
  30069. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30070. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30071. this.refDistance = options.refDistance || this.refDistance;
  30072. this.distanceModel = options.distanceModel || this.distanceModel;
  30073. this._playbackRate = options.playbackRate || this._playbackRate;
  30074. this._updateSpatialParameters();
  30075. if (this.isPlaying) {
  30076. if (this._streaming) {
  30077. this._htmlAudioElement.playbackRate = this._playbackRate;
  30078. }
  30079. else {
  30080. this._soundSource.playbackRate.value = this._playbackRate;
  30081. }
  30082. }
  30083. }
  30084. };
  30085. Sound.prototype._createSpatialParameters = function () {
  30086. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30087. if (this._scene.headphone) {
  30088. this._panningModel = "HRTF";
  30089. }
  30090. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30091. this._updateSpatialParameters();
  30092. this._soundPanner.connect(this._ouputAudioNode);
  30093. this._inputAudioNode = this._soundPanner;
  30094. }
  30095. };
  30096. Sound.prototype._updateSpatialParameters = function () {
  30097. if (this.spatialSound) {
  30098. if (this.useCustomAttenuation) {
  30099. // Tricks to disable in a way embedded Web Audio attenuation
  30100. this._soundPanner.distanceModel = "linear";
  30101. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30102. this._soundPanner.refDistance = 1;
  30103. this._soundPanner.rolloffFactor = 1;
  30104. this._soundPanner.panningModel = this._panningModel;
  30105. }
  30106. else {
  30107. this._soundPanner.distanceModel = this.distanceModel;
  30108. this._soundPanner.maxDistance = this.maxDistance;
  30109. this._soundPanner.refDistance = this.refDistance;
  30110. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30111. this._soundPanner.panningModel = this._panningModel;
  30112. }
  30113. }
  30114. };
  30115. Sound.prototype.switchPanningModelToHRTF = function () {
  30116. this._panningModel = "HRTF";
  30117. this._switchPanningModel();
  30118. };
  30119. Sound.prototype.switchPanningModelToEqualPower = function () {
  30120. this._panningModel = "equalpower";
  30121. this._switchPanningModel();
  30122. };
  30123. Sound.prototype._switchPanningModel = function () {
  30124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30125. this._soundPanner.panningModel = this._panningModel;
  30126. }
  30127. };
  30128. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30129. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30130. if (this._isOutputConnected) {
  30131. this._ouputAudioNode.disconnect();
  30132. }
  30133. this._ouputAudioNode.connect(soundTrackAudioNode);
  30134. this._isOutputConnected = true;
  30135. }
  30136. };
  30137. /**
  30138. * Transform this sound into a directional source
  30139. * @param coneInnerAngle Size of the inner cone in degree
  30140. * @param coneOuterAngle Size of the outer cone in degree
  30141. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30142. */
  30143. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30144. if (coneOuterAngle < coneInnerAngle) {
  30145. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30146. return;
  30147. }
  30148. this._coneInnerAngle = coneInnerAngle;
  30149. this._coneOuterAngle = coneOuterAngle;
  30150. this._coneOuterGain = coneOuterGain;
  30151. this._isDirectional = true;
  30152. if (this.isPlaying && this.loop) {
  30153. this.stop();
  30154. this.play();
  30155. }
  30156. };
  30157. Sound.prototype.setPosition = function (newPosition) {
  30158. this._position = newPosition;
  30159. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30160. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30161. }
  30162. };
  30163. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30164. this._localDirection = newLocalDirection;
  30165. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30166. this._updateDirection();
  30167. }
  30168. };
  30169. Sound.prototype._updateDirection = function () {
  30170. var mat = this._connectedMesh.getWorldMatrix();
  30171. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30172. direction.normalize();
  30173. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30174. };
  30175. Sound.prototype.updateDistanceFromListener = function () {
  30176. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30177. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30178. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30179. }
  30180. };
  30181. Sound.prototype.setAttenuationFunction = function (callback) {
  30182. this._customAttenuationFunction = callback;
  30183. };
  30184. /**
  30185. * Play the sound
  30186. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30187. */
  30188. Sound.prototype.play = function (time) {
  30189. var _this = this;
  30190. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30191. try {
  30192. if (this._startOffset < 0) {
  30193. time = -this._startOffset;
  30194. this._startOffset = 0;
  30195. }
  30196. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30197. if (!this._soundSource || !this._streamingSource) {
  30198. if (this.spatialSound) {
  30199. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30200. if (this._isDirectional) {
  30201. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30202. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30203. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30204. if (this._connectedMesh) {
  30205. this._updateDirection();
  30206. }
  30207. else {
  30208. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30209. }
  30210. }
  30211. }
  30212. }
  30213. if (this._streaming) {
  30214. if (!this._streamingSource) {
  30215. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  30216. this._htmlAudioElement.onended = function () { _this._onended(); };
  30217. this._htmlAudioElement.playbackRate = this._playbackRate;
  30218. }
  30219. this._streamingSource.disconnect();
  30220. this._streamingSource.connect(this._inputAudioNode);
  30221. this._htmlAudioElement.play();
  30222. }
  30223. else {
  30224. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30225. this._soundSource.buffer = this._audioBuffer;
  30226. this._soundSource.connect(this._inputAudioNode);
  30227. this._soundSource.loop = this.loop;
  30228. this._soundSource.playbackRate.value = this._playbackRate;
  30229. this._soundSource.onended = function () { _this._onended(); };
  30230. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30231. }
  30232. this._startTime = startTime;
  30233. this.isPlaying = true;
  30234. this.isPaused = false;
  30235. }
  30236. catch (ex) {
  30237. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30238. }
  30239. }
  30240. };
  30241. Sound.prototype._onended = function () {
  30242. this.isPlaying = false;
  30243. if (this.onended) {
  30244. this.onended();
  30245. }
  30246. };
  30247. /**
  30248. * Stop the sound
  30249. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30250. */
  30251. Sound.prototype.stop = function (time) {
  30252. if (this.isPlaying) {
  30253. if (this._streaming) {
  30254. this._htmlAudioElement.pause();
  30255. // Test needed for Firefox or it will generate an Invalid State Error
  30256. if (this._htmlAudioElement.currentTime > 0) {
  30257. this._htmlAudioElement.currentTime = 0;
  30258. }
  30259. }
  30260. else {
  30261. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30262. this._soundSource.stop(stopTime);
  30263. if (!this.isPaused) {
  30264. this._startOffset = 0;
  30265. }
  30266. }
  30267. this.isPlaying = false;
  30268. }
  30269. };
  30270. Sound.prototype.pause = function () {
  30271. if (this.isPlaying) {
  30272. this.isPaused = true;
  30273. if (this._streaming) {
  30274. this._htmlAudioElement.pause();
  30275. }
  30276. else {
  30277. this.stop(0);
  30278. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30279. }
  30280. }
  30281. };
  30282. Sound.prototype.setVolume = function (newVolume, time) {
  30283. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30284. if (time) {
  30285. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  30286. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30287. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  30288. }
  30289. else {
  30290. this._soundGain.gain.value = newVolume;
  30291. }
  30292. }
  30293. this._volume = newVolume;
  30294. };
  30295. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30296. this._playbackRate = newPlaybackRate;
  30297. if (this.isPlaying) {
  30298. if (this._streaming) {
  30299. this._htmlAudioElement.playbackRate = this._playbackRate;
  30300. }
  30301. else {
  30302. this._soundSource.playbackRate.value = this._playbackRate;
  30303. }
  30304. }
  30305. };
  30306. Sound.prototype.getVolume = function () {
  30307. return this._volume;
  30308. };
  30309. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30310. var _this = this;
  30311. if (this._connectedMesh) {
  30312. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30313. this._registerFunc = null;
  30314. }
  30315. this._connectedMesh = meshToConnectTo;
  30316. if (!this.spatialSound) {
  30317. this.spatialSound = true;
  30318. this._createSpatialParameters();
  30319. if (this.isPlaying && this.loop) {
  30320. this.stop();
  30321. this.play();
  30322. }
  30323. }
  30324. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30325. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30326. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30327. };
  30328. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30329. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30330. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30331. this._updateDirection();
  30332. }
  30333. };
  30334. Sound.prototype.clone = function () {
  30335. var _this = this;
  30336. if (!this._streaming) {
  30337. var setBufferAndRun = function () {
  30338. if (_this._isReadyToPlay) {
  30339. clonedSound._audioBuffer = _this.getAudioBuffer();
  30340. clonedSound._isReadyToPlay = true;
  30341. if (clonedSound.autoplay) {
  30342. clonedSound.play();
  30343. }
  30344. }
  30345. else {
  30346. window.setTimeout(setBufferAndRun, 300);
  30347. }
  30348. };
  30349. var currentOptions = {
  30350. autoplay: this.autoplay, loop: this.loop,
  30351. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  30352. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  30353. refDistance: this.refDistance, distanceModel: this.distanceModel
  30354. };
  30355. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  30356. if (this.useCustomAttenuation) {
  30357. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  30358. }
  30359. clonedSound.setPosition(this._position);
  30360. clonedSound.setPlaybackRate(this._playbackRate);
  30361. setBufferAndRun();
  30362. return clonedSound;
  30363. }
  30364. else {
  30365. return null;
  30366. }
  30367. };
  30368. Sound.prototype.getAudioBuffer = function () {
  30369. return this._audioBuffer;
  30370. };
  30371. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  30372. var soundName = parsedSound.name;
  30373. var soundUrl;
  30374. if (parsedSound.url) {
  30375. soundUrl = rootUrl + parsedSound.url;
  30376. }
  30377. else {
  30378. soundUrl = rootUrl + soundName;
  30379. }
  30380. var options = {
  30381. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  30382. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  30383. rolloffFactor: parsedSound.rolloffFactor,
  30384. refDistance: parsedSound.refDistance,
  30385. distanceModel: parsedSound.distanceModel,
  30386. playbackRate: parsedSound.playbackRate
  30387. };
  30388. var newSound;
  30389. if (!sourceSound) {
  30390. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  30391. scene._addPendingData(newSound);
  30392. }
  30393. else {
  30394. var setBufferAndRun = function () {
  30395. if (sourceSound._isReadyToPlay) {
  30396. newSound._audioBuffer = sourceSound.getAudioBuffer();
  30397. newSound._isReadyToPlay = true;
  30398. if (newSound.autoplay) {
  30399. newSound.play();
  30400. }
  30401. }
  30402. else {
  30403. window.setTimeout(setBufferAndRun, 300);
  30404. }
  30405. };
  30406. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  30407. setBufferAndRun();
  30408. }
  30409. if (parsedSound.position) {
  30410. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  30411. newSound.setPosition(soundPosition);
  30412. }
  30413. if (parsedSound.isDirectional) {
  30414. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  30415. if (parsedSound.localDirectionToMesh) {
  30416. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  30417. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  30418. }
  30419. }
  30420. if (parsedSound.connectedMeshId) {
  30421. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  30422. if (connectedMesh) {
  30423. newSound.attachToMesh(connectedMesh);
  30424. }
  30425. }
  30426. return newSound;
  30427. };
  30428. return Sound;
  30429. })();
  30430. BABYLON.Sound = Sound;
  30431. })(BABYLON || (BABYLON = {}));
  30432. var BABYLON;
  30433. (function (BABYLON) {
  30434. var SoundTrack = (function () {
  30435. function SoundTrack(scene, options) {
  30436. this.id = -1;
  30437. this._isMainTrack = false;
  30438. this._isInitialized = false;
  30439. this._scene = scene;
  30440. this.soundCollection = new Array();
  30441. this._options = options;
  30442. if (!this._isMainTrack) {
  30443. this._scene.soundTracks.push(this);
  30444. this.id = this._scene.soundTracks.length - 1;
  30445. }
  30446. }
  30447. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  30448. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30449. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  30450. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  30451. if (this._options) {
  30452. if (this._options.volume) {
  30453. this._outputAudioNode.gain.value = this._options.volume;
  30454. }
  30455. if (this._options.mainTrack) {
  30456. this._isMainTrack = this._options.mainTrack;
  30457. }
  30458. }
  30459. this._isInitialized = true;
  30460. }
  30461. };
  30462. SoundTrack.prototype.dispose = function () {
  30463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30464. if (this._connectedAnalyser) {
  30465. this._connectedAnalyser.stopDebugCanvas();
  30466. }
  30467. while (this.soundCollection.length) {
  30468. this.soundCollection[0].dispose();
  30469. }
  30470. if (this._outputAudioNode) {
  30471. this._outputAudioNode.disconnect();
  30472. }
  30473. this._outputAudioNode = null;
  30474. }
  30475. };
  30476. SoundTrack.prototype.AddSound = function (sound) {
  30477. if (!this._isInitialized) {
  30478. this._initializeSoundTrackAudioGraph();
  30479. }
  30480. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30481. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30482. }
  30483. if (sound.soundTrackId) {
  30484. if (sound.soundTrackId === -1) {
  30485. this._scene.mainSoundTrack.RemoveSound(sound);
  30486. }
  30487. else {
  30488. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30489. }
  30490. }
  30491. this.soundCollection.push(sound);
  30492. sound.soundTrackId = this.id;
  30493. };
  30494. SoundTrack.prototype.RemoveSound = function (sound) {
  30495. var index = this.soundCollection.indexOf(sound);
  30496. if (index !== -1) {
  30497. this.soundCollection.splice(index, 1);
  30498. }
  30499. };
  30500. SoundTrack.prototype.setVolume = function (newVolume) {
  30501. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30502. this._outputAudioNode.gain.value = newVolume;
  30503. }
  30504. };
  30505. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30506. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30507. for (var i = 0; i < this.soundCollection.length; i++) {
  30508. this.soundCollection[i].switchPanningModelToHRTF();
  30509. }
  30510. }
  30511. };
  30512. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30513. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30514. for (var i = 0; i < this.soundCollection.length; i++) {
  30515. this.soundCollection[i].switchPanningModelToEqualPower();
  30516. }
  30517. }
  30518. };
  30519. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30520. if (this._connectedAnalyser) {
  30521. this._connectedAnalyser.stopDebugCanvas();
  30522. }
  30523. this._connectedAnalyser = analyser;
  30524. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30525. this._outputAudioNode.disconnect();
  30526. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  30527. }
  30528. };
  30529. return SoundTrack;
  30530. })();
  30531. BABYLON.SoundTrack = SoundTrack;
  30532. })(BABYLON || (BABYLON = {}));
  30533. var BABYLON;
  30534. (function (BABYLON) {
  30535. var SIMDVector3 = (function () {
  30536. function SIMDVector3() {
  30537. }
  30538. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  30539. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  30540. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30541. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30542. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30543. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30544. 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));
  30545. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30546. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30547. };
  30548. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  30549. var v0 = SIMD.float32x4.splat(x);
  30550. var v1 = SIMD.float32x4.splat(y);
  30551. var v2 = SIMD.float32x4.splat(z);
  30552. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30553. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30554. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30555. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30556. 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));
  30557. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30558. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30559. };
  30560. return SIMDVector3;
  30561. })();
  30562. BABYLON.SIMDVector3 = SIMDVector3;
  30563. var SIMDMatrix = (function () {
  30564. function SIMDMatrix() {
  30565. }
  30566. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  30567. if (offset === void 0) { offset = 0; }
  30568. var tm = this.m;
  30569. var om = other.m;
  30570. var om0 = SIMD.float32x4.load(om, 0);
  30571. var om1 = SIMD.float32x4.load(om, 4);
  30572. var om2 = SIMD.float32x4.load(om, 8);
  30573. var om3 = SIMD.float32x4.load(om, 12);
  30574. var tm0 = SIMD.float32x4.load(tm, 0);
  30575. 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)))));
  30576. var tm1 = SIMD.float32x4.load(tm, 4);
  30577. 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)))));
  30578. var tm2 = SIMD.float32x4.load(tm, 8);
  30579. 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)))));
  30580. var tm3 = SIMD.float32x4.load(tm, 12);
  30581. 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)))));
  30582. };
  30583. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  30584. var src = this.m;
  30585. var dest = other.m;
  30586. var row0, row1, row2, row3;
  30587. var tmp1;
  30588. var minor0, minor1, minor2, minor3;
  30589. var det;
  30590. // Load the 4 rows
  30591. var src0 = SIMD.float32x4.load(src, 0);
  30592. var src1 = SIMD.float32x4.load(src, 4);
  30593. var src2 = SIMD.float32x4.load(src, 8);
  30594. var src3 = SIMD.float32x4.load(src, 12);
  30595. // Transpose the source matrix. Sort of. Not a true transpose operation
  30596. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30597. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30598. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  30599. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  30600. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30601. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30602. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  30603. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  30604. // This is a true transposition, but it will lead to an incorrect result
  30605. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30606. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30607. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30608. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30609. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30610. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30611. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30612. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30613. // ----
  30614. tmp1 = SIMD.float32x4.mul(row2, row3);
  30615. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30616. minor0 = SIMD.float32x4.mul(row1, tmp1);
  30617. minor1 = SIMD.float32x4.mul(row0, tmp1);
  30618. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30619. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  30620. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  30621. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  30622. // ----
  30623. tmp1 = SIMD.float32x4.mul(row1, row2);
  30624. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30625. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  30626. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30627. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30628. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30629. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30630. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30631. // ----
  30632. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30633. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30634. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30635. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30636. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30637. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30638. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30639. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30640. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30641. // ----
  30642. tmp1 = SIMD.float32x4.mul(row0, row1);
  30643. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30644. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30645. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30646. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30647. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30648. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30649. // ----
  30650. tmp1 = SIMD.float32x4.mul(row0, row3);
  30651. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30652. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30653. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30655. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30656. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30657. // ----
  30658. tmp1 = SIMD.float32x4.mul(row0, row2);
  30659. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30660. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30661. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30662. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30663. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30664. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30665. // Compute determinant
  30666. det = SIMD.float32x4.mul(row0, minor0);
  30667. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30668. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30669. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30670. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30671. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30672. // These shuffles aren't necessary if the faulty transposition is done
  30673. // up at the top of this function.
  30674. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30675. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30676. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30677. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30678. // Compute final values by multiplying with 1/det
  30679. minor0 = SIMD.float32x4.mul(det, minor0);
  30680. minor1 = SIMD.float32x4.mul(det, minor1);
  30681. minor2 = SIMD.float32x4.mul(det, minor2);
  30682. minor3 = SIMD.float32x4.mul(det, minor3);
  30683. SIMD.float32x4.store(dest, 0, minor0);
  30684. SIMD.float32x4.store(dest, 4, minor1);
  30685. SIMD.float32x4.store(dest, 8, minor2);
  30686. SIMD.float32x4.store(dest, 12, minor3);
  30687. return this;
  30688. };
  30689. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30690. var out = result.m;
  30691. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30692. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30693. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30694. // cc.kmVec3Subtract(f, pCenter, pEye);
  30695. var f = SIMD.float32x4.sub(center, eye);
  30696. // cc.kmVec3Normalize(f, f);
  30697. var tmp = SIMD.float32x4.mul(f, f);
  30698. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30699. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30700. // cc.kmVec3Assign(up, pUp);
  30701. // cc.kmVec3Normalize(up, up);
  30702. tmp = SIMD.float32x4.mul(up, up);
  30703. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30704. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30705. // cc.kmVec3Cross(s, f, up);
  30706. 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)));
  30707. // cc.kmVec3Normalize(s, s);
  30708. tmp = SIMD.float32x4.mul(s, s);
  30709. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30710. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30711. // cc.kmVec3Cross(u, s, f);
  30712. 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)));
  30713. // cc.kmVec3Normalize(s, s);
  30714. tmp = SIMD.float32x4.mul(s, s);
  30715. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30716. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30717. var zero = SIMD.float32x4.splat(0.0);
  30718. s = SIMD.float32x4.neg(s);
  30719. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30720. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30721. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30722. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30723. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30724. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30725. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30726. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30727. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30728. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30729. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30730. var b3 = SIMD.float32x4.neg(eye);
  30731. b3 = SIMD.float32x4.withW(b3, 1.0);
  30732. 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)))));
  30733. 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)))));
  30734. 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)))));
  30735. 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)))));
  30736. };
  30737. return SIMDMatrix;
  30738. })();
  30739. BABYLON.SIMDMatrix = SIMDMatrix;
  30740. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30741. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30742. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30743. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30744. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30745. var SIMDHelper = (function () {
  30746. function SIMDHelper() {
  30747. }
  30748. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30749. get: function () {
  30750. return SIMDHelper._isEnabled;
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. SIMDHelper.DisableSIMD = function () {
  30756. // Replace functions
  30757. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30758. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30759. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30760. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30762. SIMDHelper._isEnabled = false;
  30763. };
  30764. SIMDHelper.EnableSIMD = function () {
  30765. if (window.SIMD === undefined) {
  30766. return;
  30767. }
  30768. // Replace functions
  30769. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30770. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30771. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30772. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30774. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30775. get: function () { return this._data[0]; },
  30776. set: function (value) {
  30777. if (!this._data) {
  30778. this._data = new Float32Array(3);
  30779. }
  30780. this._data[0] = value;
  30781. }
  30782. });
  30783. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30784. get: function () { return this._data[1]; },
  30785. set: function (value) {
  30786. this._data[1] = value;
  30787. }
  30788. });
  30789. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30790. get: function () { return this._data[2]; },
  30791. set: function (value) {
  30792. this._data[2] = value;
  30793. }
  30794. });
  30795. SIMDHelper._isEnabled = true;
  30796. };
  30797. SIMDHelper._isEnabled = false;
  30798. return SIMDHelper;
  30799. })();
  30800. BABYLON.SIMDHelper = SIMDHelper;
  30801. })(BABYLON || (BABYLON = {}));
  30802. var BABYLON;
  30803. (function (BABYLON) {
  30804. var ShaderMaterial = (function (_super) {
  30805. __extends(ShaderMaterial, _super);
  30806. function ShaderMaterial(name, scene, shaderPath, options) {
  30807. _super.call(this, name, scene);
  30808. this._textures = {};
  30809. this._floats = {};
  30810. this._floatsArrays = {};
  30811. this._colors3 = {};
  30812. this._colors4 = {};
  30813. this._vectors2 = {};
  30814. this._vectors3 = {};
  30815. this._vectors4 = {};
  30816. this._matrices = {};
  30817. this._matrices3x3 = {};
  30818. this._matrices2x2 = {};
  30819. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30820. this._shaderPath = shaderPath;
  30821. options.needAlphaBlending = options.needAlphaBlending || false;
  30822. options.needAlphaTesting = options.needAlphaTesting || false;
  30823. options.attributes = options.attributes || ["position", "normal", "uv"];
  30824. options.uniforms = options.uniforms || ["worldViewProjection"];
  30825. options.samplers = options.samplers || [];
  30826. options.defines = options.defines || [];
  30827. this._options = options;
  30828. }
  30829. ShaderMaterial.prototype.needAlphaBlending = function () {
  30830. return this._options.needAlphaBlending;
  30831. };
  30832. ShaderMaterial.prototype.needAlphaTesting = function () {
  30833. return this._options.needAlphaTesting;
  30834. };
  30835. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30836. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30837. this._options.uniforms.push(uniformName);
  30838. }
  30839. };
  30840. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30841. if (this._options.samplers.indexOf(name) === -1) {
  30842. this._options.samplers.push(name);
  30843. }
  30844. this._textures[name] = texture;
  30845. return this;
  30846. };
  30847. ShaderMaterial.prototype.setFloat = function (name, value) {
  30848. this._checkUniform(name);
  30849. this._floats[name] = value;
  30850. return this;
  30851. };
  30852. ShaderMaterial.prototype.setFloats = function (name, value) {
  30853. this._checkUniform(name);
  30854. this._floatsArrays[name] = value;
  30855. return this;
  30856. };
  30857. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30858. this._checkUniform(name);
  30859. this._colors3[name] = value;
  30860. return this;
  30861. };
  30862. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30863. this._checkUniform(name);
  30864. this._colors4[name] = value;
  30865. return this;
  30866. };
  30867. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30868. this._checkUniform(name);
  30869. this._vectors2[name] = value;
  30870. return this;
  30871. };
  30872. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30873. this._checkUniform(name);
  30874. this._vectors3[name] = value;
  30875. return this;
  30876. };
  30877. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30878. this._checkUniform(name);
  30879. this._vectors4[name] = value;
  30880. return this;
  30881. };
  30882. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30883. this._checkUniform(name);
  30884. this._matrices[name] = value;
  30885. return this;
  30886. };
  30887. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30888. this._checkUniform(name);
  30889. this._matrices3x3[name] = value;
  30890. return this;
  30891. };
  30892. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30893. this._checkUniform(name);
  30894. this._matrices2x2[name] = value;
  30895. return this;
  30896. };
  30897. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30898. var scene = this.getScene();
  30899. var engine = scene.getEngine();
  30900. if (!this.checkReadyOnEveryCall) {
  30901. if (this._renderId === scene.getRenderId()) {
  30902. return true;
  30903. }
  30904. }
  30905. // Instances
  30906. var defines = [];
  30907. var fallbacks = new BABYLON.EffectFallbacks();
  30908. if (useInstances) {
  30909. defines.push("#define INSTANCES");
  30910. }
  30911. for (var index = 0; index < this._options.defines.length; index++) {
  30912. defines.push(this._options.defines[index]);
  30913. }
  30914. // Bones
  30915. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30916. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30917. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30918. fallbacks.addCPUSkinningFallback(0, mesh);
  30919. }
  30920. // Alpha test
  30921. if (engine.getAlphaTesting()) {
  30922. defines.push("#define ALPHATEST");
  30923. }
  30924. var previousEffect = this._effect;
  30925. var join = defines.join("\n");
  30926. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30927. if (!this._effect.isReady()) {
  30928. return false;
  30929. }
  30930. if (previousEffect !== this._effect) {
  30931. scene.resetCachedMaterial();
  30932. }
  30933. this._renderId = scene.getRenderId();
  30934. return true;
  30935. };
  30936. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30937. var scene = this.getScene();
  30938. if (this._options.uniforms.indexOf("world") !== -1) {
  30939. this._effect.setMatrix("world", world);
  30940. }
  30941. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30942. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30943. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30944. }
  30945. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30946. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30947. }
  30948. };
  30949. ShaderMaterial.prototype.bind = function (world, mesh) {
  30950. // Std values
  30951. this.bindOnlyWorldMatrix(world);
  30952. if (this.getScene().getCachedMaterial() !== this) {
  30953. if (this._options.uniforms.indexOf("view") !== -1) {
  30954. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30955. }
  30956. if (this._options.uniforms.indexOf("projection") !== -1) {
  30957. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30958. }
  30959. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30960. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30961. }
  30962. // Bones
  30963. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30964. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30965. }
  30966. // Texture
  30967. for (var name in this._textures) {
  30968. this._effect.setTexture(name, this._textures[name]);
  30969. }
  30970. // Float
  30971. for (name in this._floats) {
  30972. this._effect.setFloat(name, this._floats[name]);
  30973. }
  30974. // Float s
  30975. for (name in this._floatsArrays) {
  30976. this._effect.setArray(name, this._floatsArrays[name]);
  30977. }
  30978. // Color3
  30979. for (name in this._colors3) {
  30980. this._effect.setColor3(name, this._colors3[name]);
  30981. }
  30982. // Color4
  30983. for (name in this._colors4) {
  30984. var color = this._colors4[name];
  30985. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30986. }
  30987. // Vector2
  30988. for (name in this._vectors2) {
  30989. this._effect.setVector2(name, this._vectors2[name]);
  30990. }
  30991. // Vector3
  30992. for (name in this._vectors3) {
  30993. this._effect.setVector3(name, this._vectors3[name]);
  30994. }
  30995. // Vector4
  30996. for (name in this._vectors4) {
  30997. this._effect.setVector4(name, this._vectors4[name]);
  30998. }
  30999. // Matrix
  31000. for (name in this._matrices) {
  31001. this._effect.setMatrix(name, this._matrices[name]);
  31002. }
  31003. // Matrix 3x3
  31004. for (name in this._matrices3x3) {
  31005. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  31006. }
  31007. // Matrix 2x2
  31008. for (name in this._matrices2x2) {
  31009. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  31010. }
  31011. }
  31012. _super.prototype.bind.call(this, world, mesh);
  31013. };
  31014. ShaderMaterial.prototype.clone = function (name) {
  31015. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  31016. return newShaderMaterial;
  31017. };
  31018. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  31019. for (var name in this._textures) {
  31020. this._textures[name].dispose();
  31021. }
  31022. this._textures = {};
  31023. _super.prototype.dispose.call(this, forceDisposeEffect);
  31024. };
  31025. ShaderMaterial.prototype.serialize = function () {
  31026. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31027. serializationObject.customType = "BABYLON.ShaderMaterial";
  31028. serializationObject.options = this._options;
  31029. serializationObject.shaderPath = this._shaderPath;
  31030. // Texture
  31031. serializationObject.textures = {};
  31032. for (var name in this._textures) {
  31033. serializationObject.textures[name] = this._textures[name].serialize();
  31034. }
  31035. // Float
  31036. serializationObject.floats = {};
  31037. for (name in this._floats) {
  31038. serializationObject.floats[name] = this._floats[name];
  31039. }
  31040. // Float s
  31041. serializationObject.floatArrays = {};
  31042. for (name in this._floatsArrays) {
  31043. serializationObject.floatArrays[name] = this._floatsArrays[name];
  31044. }
  31045. // Color3
  31046. serializationObject.colors3 = {};
  31047. for (name in this._colors3) {
  31048. serializationObject.colors3[name] = this._colors3[name].asArray();
  31049. }
  31050. // Color4
  31051. serializationObject.colors4 = {};
  31052. for (name in this._colors4) {
  31053. serializationObject.colors4[name] = this._colors4[name].asArray();
  31054. }
  31055. // Vector2
  31056. serializationObject.vectors2 = {};
  31057. for (name in this._vectors2) {
  31058. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  31059. }
  31060. // Vector3
  31061. serializationObject.vectors3 = {};
  31062. for (name in this._vectors3) {
  31063. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  31064. }
  31065. // Vector4
  31066. serializationObject.vectors4 = {};
  31067. for (name in this._vectors4) {
  31068. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  31069. }
  31070. // Matrix
  31071. serializationObject.matrices = {};
  31072. for (name in this._matrices) {
  31073. serializationObject.matrices[name] = this._matrices[name].asArray();
  31074. }
  31075. // Matrix 3x3
  31076. serializationObject.matrices3x3 = {};
  31077. for (name in this._matrices3x3) {
  31078. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  31079. }
  31080. // Matrix 2x2
  31081. serializationObject.matrices2x2 = {};
  31082. for (name in this._matrices2x2) {
  31083. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  31084. }
  31085. return serializationObject;
  31086. };
  31087. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  31088. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  31089. // Texture
  31090. for (var name in source.textures) {
  31091. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  31092. }
  31093. // Float
  31094. for (name in source.floats) {
  31095. material.setFloat(name, source.floats[name]);
  31096. }
  31097. // Float s
  31098. for (name in source.floatsArrays) {
  31099. material.setFloats(name, source.floatsArrays[name]);
  31100. }
  31101. // Color3
  31102. for (name in source.colors3) {
  31103. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  31104. }
  31105. // Color4
  31106. for (name in source.colors4) {
  31107. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  31108. }
  31109. // Vector2
  31110. for (name in source.vectors2) {
  31111. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  31112. }
  31113. // Vector3
  31114. for (name in source.vectors3) {
  31115. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  31116. }
  31117. // Vector4
  31118. for (name in source.vectors4) {
  31119. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  31120. }
  31121. // Matrix
  31122. for (name in source.matrices) {
  31123. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  31124. }
  31125. // Matrix 3x3
  31126. for (name in source.matrices3x3) {
  31127. material.setMatrix3x3(name, source.matrices3x3[name]);
  31128. }
  31129. // Matrix 2x2
  31130. for (name in source.matrices2x2) {
  31131. material.setMatrix2x2(name, source.matrices2x2[name]);
  31132. }
  31133. return material;
  31134. };
  31135. return ShaderMaterial;
  31136. })(BABYLON.Material);
  31137. BABYLON.ShaderMaterial = ShaderMaterial;
  31138. })(BABYLON || (BABYLON = {}));
  31139. var BABYLON;
  31140. (function (BABYLON) {
  31141. var Internals;
  31142. (function (Internals) {
  31143. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  31144. // All values and structures referenced from:
  31145. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  31146. var DDS_MAGIC = 0x20534444;
  31147. 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;
  31148. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  31149. 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;
  31150. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  31151. function FourCCToInt32(value) {
  31152. return value.charCodeAt(0) +
  31153. (value.charCodeAt(1) << 8) +
  31154. (value.charCodeAt(2) << 16) +
  31155. (value.charCodeAt(3) << 24);
  31156. }
  31157. function Int32ToFourCC(value) {
  31158. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  31159. }
  31160. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  31161. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  31162. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  31163. var headerLengthInt = 31; // The header length in 32 bit ints
  31164. // Offsets into the header array
  31165. var off_magic = 0;
  31166. var off_size = 1;
  31167. var off_flags = 2;
  31168. var off_height = 3;
  31169. var off_width = 4;
  31170. var off_mipmapCount = 7;
  31171. var off_pfFlags = 20;
  31172. var off_pfFourCC = 21;
  31173. var off_RGBbpp = 22;
  31174. var off_RMask = 23;
  31175. var off_GMask = 24;
  31176. var off_BMask = 25;
  31177. var off_AMask = 26;
  31178. var off_caps1 = 27;
  31179. var off_caps2 = 28;
  31180. ;
  31181. var DDSTools = (function () {
  31182. function DDSTools() {
  31183. }
  31184. DDSTools.GetDDSInfo = function (arrayBuffer) {
  31185. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  31186. var mipmapCount = 1;
  31187. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  31188. mipmapCount = Math.max(1, header[off_mipmapCount]);
  31189. }
  31190. return {
  31191. width: header[off_width],
  31192. height: header[off_height],
  31193. mipmapCount: mipmapCount,
  31194. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  31195. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  31196. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  31197. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  31198. };
  31199. };
  31200. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  31201. var byteArray = new Uint8Array(dataLength);
  31202. var srcData = new Uint8Array(arrayBuffer);
  31203. var index = 0;
  31204. for (var y = height - 1; y >= 0; y--) {
  31205. for (var x = 0; x < width; x++) {
  31206. var srcPos = dataOffset + (x + y * width) * 4;
  31207. byteArray[index + 2] = srcData[srcPos];
  31208. byteArray[index + 1] = srcData[srcPos + 1];
  31209. byteArray[index] = srcData[srcPos + 2];
  31210. byteArray[index + 3] = srcData[srcPos + 3];
  31211. index += 4;
  31212. }
  31213. }
  31214. return byteArray;
  31215. };
  31216. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  31217. var byteArray = new Uint8Array(dataLength);
  31218. var srcData = new Uint8Array(arrayBuffer);
  31219. var index = 0;
  31220. for (var y = height - 1; y >= 0; y--) {
  31221. for (var x = 0; x < width; x++) {
  31222. var srcPos = dataOffset + (x + y * width) * 3;
  31223. byteArray[index + 2] = srcData[srcPos];
  31224. byteArray[index + 1] = srcData[srcPos + 1];
  31225. byteArray[index] = srcData[srcPos + 2];
  31226. index += 3;
  31227. }
  31228. }
  31229. return byteArray;
  31230. };
  31231. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  31232. var byteArray = new Uint8Array(dataLength);
  31233. var srcData = new Uint8Array(arrayBuffer);
  31234. var index = 0;
  31235. for (var y = height - 1; y >= 0; y--) {
  31236. for (var x = 0; x < width; x++) {
  31237. var srcPos = dataOffset + (x + y * width);
  31238. byteArray[index] = srcData[srcPos];
  31239. index++;
  31240. }
  31241. }
  31242. return byteArray;
  31243. };
  31244. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  31245. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  31246. if (header[off_magic] != DDS_MAGIC) {
  31247. BABYLON.Tools.Error("Invalid magic number in DDS header");
  31248. return;
  31249. }
  31250. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  31251. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  31252. return;
  31253. }
  31254. if (info.isFourCC) {
  31255. fourCC = header[off_pfFourCC];
  31256. switch (fourCC) {
  31257. case FOURCC_DXT1:
  31258. blockBytes = 8;
  31259. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  31260. break;
  31261. case FOURCC_DXT3:
  31262. blockBytes = 16;
  31263. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  31264. break;
  31265. case FOURCC_DXT5:
  31266. blockBytes = 16;
  31267. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  31268. break;
  31269. default:
  31270. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  31271. return;
  31272. }
  31273. }
  31274. mipmapCount = 1;
  31275. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  31276. mipmapCount = Math.max(1, header[off_mipmapCount]);
  31277. }
  31278. var bpp = header[off_RGBbpp];
  31279. for (var face = 0; face < faces; face++) {
  31280. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  31281. width = header[off_width];
  31282. height = header[off_height];
  31283. dataOffset = header[off_size] + 4;
  31284. for (i = 0; i < mipmapCount; ++i) {
  31285. if (info.isRGB) {
  31286. if (bpp === 24) {
  31287. dataLength = width * height * 3;
  31288. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  31289. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  31290. }
  31291. else {
  31292. dataLength = width * height * 4;
  31293. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  31294. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  31295. }
  31296. }
  31297. else if (info.isLuminance) {
  31298. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  31299. var unpaddedRowSize = width;
  31300. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  31301. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  31302. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  31303. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  31304. }
  31305. else {
  31306. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  31307. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  31308. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  31309. }
  31310. dataOffset += dataLength;
  31311. width *= 0.5;
  31312. height *= 0.5;
  31313. width = Math.max(1.0, width);
  31314. height = Math.max(1.0, height);
  31315. }
  31316. }
  31317. };
  31318. return DDSTools;
  31319. })();
  31320. Internals.DDSTools = DDSTools;
  31321. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31322. })(BABYLON || (BABYLON = {}));
  31323. var BABYLON;
  31324. (function (BABYLON) {
  31325. var CannonJSPlugin = (function () {
  31326. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  31327. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  31328. if (iterations === void 0) { iterations = 10; }
  31329. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  31330. this.name = "CannonJSPlugin";
  31331. this._physicsMaterials = [];
  31332. this._fixedTimeStep = 1 / 60;
  31333. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  31334. this._currentCollisionGroup = 2;
  31335. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  31336. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  31337. this._tmpPosition = BABYLON.Vector3.Zero();
  31338. this._tmpQuaternion = new BABYLON.Quaternion();
  31339. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  31340. this._tmpDeltaRotation = new BABYLON.Quaternion();
  31341. this._tmpUnityRotation = new BABYLON.Quaternion();
  31342. if (!this.isSupported()) {
  31343. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  31344. return;
  31345. }
  31346. this.world = new CANNON.World();
  31347. this.world.broadphase = new CANNON.NaiveBroadphase();
  31348. this.world.solver.iterations = iterations;
  31349. }
  31350. CannonJSPlugin.prototype.setGravity = function (gravity) {
  31351. this.world.gravity.copy(gravity);
  31352. };
  31353. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  31354. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  31355. };
  31356. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31357. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  31358. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  31359. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  31360. };
  31361. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31362. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  31363. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  31364. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  31365. };
  31366. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31367. //parent-child relationship. Does this impostor has a parent impostor?
  31368. if (impostor.parent) {
  31369. if (impostor.physicsBody) {
  31370. this.removePhysicsBody(impostor);
  31371. //TODO is that needed?
  31372. impostor.forceUpdate();
  31373. }
  31374. return;
  31375. }
  31376. //should a new body be created for this impostor?
  31377. if (impostor.isBodyInitRequired()) {
  31378. if (!impostor.mesh.rotationQuaternion) {
  31379. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31380. }
  31381. var shape = this._createShape(impostor);
  31382. //unregister events, if body is being changed
  31383. var oldBody = impostor.physicsBody;
  31384. if (oldBody) {
  31385. this.removePhysicsBody(impostor);
  31386. }
  31387. //create the body and material
  31388. var material = this._addMaterial(impostor.getParam("friction"), impostor.getParam("restitution"));
  31389. var bodyCreationObject = {
  31390. mass: impostor.getParam("mass"),
  31391. material: material
  31392. };
  31393. // A simple extend, in case native options were used.
  31394. var nativeOptions = impostor.getParam("nativeOptions");
  31395. for (var key in nativeOptions) {
  31396. if (nativeOptions.hasOwnProperty(key)) {
  31397. bodyCreationObject[key] = nativeOptions[key];
  31398. }
  31399. }
  31400. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  31401. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  31402. this.world.addEventListener("preStep", impostor.beforeStep);
  31403. this.world.addEventListener("postStep", impostor.afterStep);
  31404. impostor.physicsBody.addShape(shape);
  31405. this.world.add(impostor.physicsBody);
  31406. //try to keep the body moving in the right direction by taking old properties.
  31407. //Should be tested!
  31408. if (oldBody) {
  31409. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  31410. impostor.physicsBody[param].copy(oldBody[param]);
  31411. });
  31412. }
  31413. this._processChildMeshes(impostor);
  31414. }
  31415. //now update the body's transformation
  31416. this._updatePhysicsBodyTransformation(impostor);
  31417. };
  31418. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  31419. var _this = this;
  31420. var meshChildren = mainImpostor.mesh.getChildMeshes(true);
  31421. if (meshChildren.length) {
  31422. var processMesh = function (relativePosition, mesh) {
  31423. var childImpostor = mesh.getPhysicsImpostor();
  31424. if (childImpostor) {
  31425. var parent = childImpostor.parent;
  31426. if (parent !== mainImpostor) {
  31427. var localPosition = mesh.position.add(relativePosition);
  31428. if (childImpostor.physicsBody) {
  31429. _this.removePhysicsBody(childImpostor);
  31430. childImpostor.physicsBody = null;
  31431. }
  31432. childImpostor.parent = mainImpostor;
  31433. childImpostor.resetUpdateFlags();
  31434. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  31435. //Add the mass of the children.
  31436. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  31437. }
  31438. }
  31439. mesh.getChildMeshes(true).forEach(processMesh.bind(_this, mesh.position));
  31440. };
  31441. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  31442. }
  31443. };
  31444. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31445. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  31446. this.world.removeEventListener("preStep", impostor.beforeStep);
  31447. this.world.removeEventListener("postStep", impostor.afterStep);
  31448. this.world.remove(impostor.physicsBody);
  31449. };
  31450. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31451. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31452. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31453. if (!mainBody || !connectedBody) {
  31454. return;
  31455. }
  31456. var constraint;
  31457. var jointData = impostorJoint.joint.jointData;
  31458. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  31459. var constraintData = {
  31460. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  31461. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  31462. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  31463. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  31464. maxForce: jointData.nativeParams.maxForce
  31465. };
  31466. if (!jointData.collision) {
  31467. //add 1st body to a collision group of its own, if it is not in 1
  31468. if (mainBody.collisionFilterGroup === 1) {
  31469. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  31470. this._currentCollisionGroup <<= 1;
  31471. }
  31472. if (connectedBody.collisionFilterGroup === 1) {
  31473. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  31474. this._currentCollisionGroup <<= 1;
  31475. }
  31476. //add their mask to the collisionFilterMask of each other:
  31477. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  31478. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  31479. }
  31480. switch (impostorJoint.joint.type) {
  31481. case BABYLON.PhysicsJoint.HingeJoint:
  31482. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  31483. break;
  31484. case BABYLON.PhysicsJoint.DistanceJoint:
  31485. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  31486. break;
  31487. default:
  31488. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  31489. break;
  31490. }
  31491. impostorJoint.joint.physicsJoint = constraint;
  31492. this.world.addConstraint(constraint);
  31493. };
  31494. CannonJSPlugin.prototype.removeJoint = function (joint) {
  31495. //TODO
  31496. };
  31497. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  31498. var index;
  31499. var mat;
  31500. for (index = 0; index < this._physicsMaterials.length; index++) {
  31501. mat = this._physicsMaterials[index];
  31502. if (mat.friction === friction && mat.restitution === restitution) {
  31503. return mat;
  31504. }
  31505. }
  31506. var currentMat = new CANNON.Material("mat");
  31507. this._physicsMaterials.push(currentMat);
  31508. for (index = 0; index < this._physicsMaterials.length; index++) {
  31509. mat = this._physicsMaterials[index];
  31510. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  31511. this.world.addContactMaterial(contactMaterial);
  31512. }
  31513. return currentMat;
  31514. };
  31515. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  31516. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  31517. };
  31518. CannonJSPlugin.prototype._createShape = function (impostor) {
  31519. var mesh = impostor.mesh;
  31520. //get the correct bounding box
  31521. var oldQuaternion = mesh.rotationQuaternion;
  31522. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31523. mesh.computeWorldMatrix(true);
  31524. var returnValue;
  31525. switch (impostor.type) {
  31526. case BABYLON.PhysicsEngine.SphereImpostor:
  31527. var bbox = mesh.getBoundingInfo().boundingBox;
  31528. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31529. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31530. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31531. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  31532. break;
  31533. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  31534. case BABYLON.PhysicsEngine.CylinderImpostor:
  31535. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  31536. case BABYLON.PhysicsEngine.BoxImpostor:
  31537. bbox = mesh.getBoundingInfo().boundingBox;
  31538. var min = bbox.minimumWorld;
  31539. var max = bbox.maximumWorld;
  31540. var box = max.subtract(min).scale(0.5);
  31541. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  31542. break;
  31543. case BABYLON.PhysicsEngine.PlaneImpostor:
  31544. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  31545. returnValue = new CANNON.Plane();
  31546. break;
  31547. case BABYLON.PhysicsEngine.MeshImpostor:
  31548. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31549. var rawFaces = mesh.getIndices();
  31550. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  31551. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  31552. break;
  31553. case BABYLON.PhysicsEngine.HeightmapImpostor:
  31554. returnValue = this._createHeightmap(mesh);
  31555. break;
  31556. }
  31557. mesh.rotationQuaternion = oldQuaternion;
  31558. return returnValue;
  31559. };
  31560. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  31561. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31562. var matrix = [];
  31563. //For now pointDepth will not be used and will be automatically calculated.
  31564. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  31565. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  31566. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  31567. var elementSize = dim * 2 / arraySize;
  31568. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  31569. for (var i = 0; i < pos.length; i = i + 3) {
  31570. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  31571. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  31572. var y = pos[i + 1] + minY;
  31573. if (!matrix[x]) {
  31574. matrix[x] = [];
  31575. }
  31576. if (!matrix[x][z]) {
  31577. matrix[x][z] = y;
  31578. }
  31579. matrix[x][z] = Math.max(y, matrix[x][z]);
  31580. }
  31581. for (var x = 0; x <= arraySize; ++x) {
  31582. if (!matrix[x]) {
  31583. var loc = 1;
  31584. while (!matrix[(x + loc) % arraySize]) {
  31585. loc++;
  31586. }
  31587. matrix[x] = matrix[(x + loc) % arraySize].slice();
  31588. }
  31589. for (var z = 0; z <= arraySize; ++z) {
  31590. if (!matrix[x][z]) {
  31591. var loc = 1;
  31592. var newValue;
  31593. while (newValue === undefined) {
  31594. newValue = matrix[x][(z + loc++) % arraySize];
  31595. }
  31596. matrix[x][z] = newValue;
  31597. }
  31598. }
  31599. }
  31600. var shape = new CANNON.Heightfield(matrix, {
  31601. elementSize: elementSize
  31602. });
  31603. //For future reference, needed for body transformation
  31604. shape.minY = minY;
  31605. return shape;
  31606. };
  31607. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  31608. var mesh = impostor.mesh;
  31609. //make sure it is updated...
  31610. impostor.mesh.computeWorldMatrix(true);
  31611. // The delta between the mesh position and the mesh bounding box center
  31612. var bbox = mesh.getBoundingInfo().boundingBox;
  31613. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  31614. var quaternion = mesh.rotationQuaternion;
  31615. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  31616. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31617. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31618. //-90 DEG in X, precalculated
  31619. quaternion = quaternion.multiply(this._minus90X);
  31620. //Invert! (Precalculated, 90 deg in X)
  31621. //No need to clone. this will never change.
  31622. impostor.setDeltaRotation(this._plus90X);
  31623. }
  31624. //If it is a heightfield, if should be centered.
  31625. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31626. //calculate the correct body position:
  31627. var rotationQuaternion = mesh.rotationQuaternion;
  31628. mesh.rotationQuaternion = this._tmpUnityRotation;
  31629. mesh.computeWorldMatrix(true);
  31630. //get original center with no rotation
  31631. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31632. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31633. //rotation is back
  31634. mesh.rotationQuaternion = rotationQuaternion;
  31635. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31636. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31637. mesh.setPivotMatrix(p);
  31638. mesh.computeWorldMatrix(true);
  31639. //calculate the translation
  31640. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31641. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31642. //add it inverted to the delta
  31643. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  31644. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31645. mesh.setPivotMatrix(oldPivot);
  31646. mesh.computeWorldMatrix(true);
  31647. }
  31648. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31649. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31650. this._tmpPosition.copyFrom(mesh.position);
  31651. }
  31652. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31653. //Now update the impostor object
  31654. impostor.physicsBody.position.copy(this._tmpPosition);
  31655. impostor.physicsBody.quaternion.copy(quaternion);
  31656. };
  31657. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31658. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31659. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31660. };
  31661. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31662. impostor.physicsBody.position.copy(newPosition);
  31663. impostor.physicsBody.quaternion.copy(newRotation);
  31664. };
  31665. CannonJSPlugin.prototype.isSupported = function () {
  31666. return window.CANNON !== undefined;
  31667. };
  31668. CannonJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31669. impostor.physicsBody.velocity.copy(velocity);
  31670. };
  31671. CannonJSPlugin.prototype.dispose = function () {
  31672. //nothing to do, actually.
  31673. };
  31674. return CannonJSPlugin;
  31675. })();
  31676. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31677. })(BABYLON || (BABYLON = {}));
  31678. var BABYLON;
  31679. (function (BABYLON) {
  31680. var OimoJSPlugin = (function () {
  31681. function OimoJSPlugin(iterations) {
  31682. this.name = "OimoJSPlugin";
  31683. this._tmpImpostorsArray = [];
  31684. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31685. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31686. this.world.clear();
  31687. //making sure no stats are calculated
  31688. this.world.isNoStat = true;
  31689. }
  31690. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31691. this.world.gravity.copy(gravity);
  31692. };
  31693. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31694. var _this = this;
  31695. impostors.forEach(function (impostor) {
  31696. impostor.beforeStep();
  31697. });
  31698. this.world.step();
  31699. impostors.forEach(function (impostor) {
  31700. impostor.afterStep();
  31701. //update the ordered impostors array
  31702. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31703. });
  31704. //check for collisions
  31705. var contact = this.world.contacts;
  31706. while (contact !== null) {
  31707. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31708. contact = contact.next;
  31709. continue;
  31710. }
  31711. //is this body colliding with any other? get the impostor
  31712. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31713. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31714. if (!mainImpostor || !collidingImpostor) {
  31715. contact = contact.next;
  31716. continue;
  31717. }
  31718. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31719. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31720. contact = contact.next;
  31721. }
  31722. };
  31723. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31724. var mass = impostor.physicsBody.massInfo.mass;
  31725. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31726. };
  31727. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31728. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31729. this.applyImpulse(impostor, force, contactPoint);
  31730. };
  31731. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31732. var _this = this;
  31733. //parent-child relationship. Does this impostor has a parent impostor?
  31734. if (impostor.parent) {
  31735. if (impostor.physicsBody) {
  31736. this.removePhysicsBody(impostor);
  31737. //TODO is that needed?
  31738. impostor.forceUpdate();
  31739. }
  31740. return;
  31741. }
  31742. impostor.mesh.computeWorldMatrix(true);
  31743. if (impostor.isBodyInitRequired()) {
  31744. if (!impostor.mesh.rotationQuaternion) {
  31745. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31746. }
  31747. var bodyConfig = {
  31748. name: impostor.mesh.uniqueId,
  31749. //Oimo must have mass, also for static objects.
  31750. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31751. size: [],
  31752. type: [],
  31753. pos: [],
  31754. rot: [],
  31755. move: impostor.getParam("mass") !== 0,
  31756. //Supporting older versions of Oimo
  31757. world: this.world
  31758. };
  31759. var impostors = [impostor];
  31760. function addToArray(parent) {
  31761. parent.getChildMeshes().forEach(function (m) {
  31762. if (m.physicsImpostor) {
  31763. impostors.push(m.physicsImpostor);
  31764. m.physicsImpostor._init();
  31765. }
  31766. });
  31767. }
  31768. addToArray(impostor.mesh);
  31769. function checkWithEpsilon(value) {
  31770. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31771. }
  31772. impostors.forEach(function (i) {
  31773. //get the correct bounding box
  31774. var oldQuaternion = i.mesh.rotationQuaternion;
  31775. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  31776. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31777. i.mesh.computeWorldMatrix(true);
  31778. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31779. if (i === impostor) {
  31780. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31781. //Can also use Array.prototype.push.apply
  31782. bodyConfig.pos.push(bbox.center.x);
  31783. bodyConfig.pos.push(bbox.center.y);
  31784. bodyConfig.pos.push(bbox.center.z);
  31785. //tmp solution
  31786. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31787. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31788. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31789. }
  31790. else {
  31791. bodyConfig.pos.push(i.mesh.position.x);
  31792. bodyConfig.pos.push(i.mesh.position.y);
  31793. bodyConfig.pos.push(i.mesh.position.z);
  31794. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31795. bodyConfig.rot.push(0);
  31796. bodyConfig.rot.push(0);
  31797. bodyConfig.rot.push(0);
  31798. }
  31799. // register mesh
  31800. switch (i.type) {
  31801. case BABYLON.PhysicsEngine.SphereImpostor:
  31802. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31803. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31804. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31805. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31806. bodyConfig.type.push('sphere');
  31807. //due to the way oimo works with compounds, add 3 times
  31808. bodyConfig.size.push(size);
  31809. bodyConfig.size.push(size);
  31810. bodyConfig.size.push(size);
  31811. break;
  31812. case BABYLON.PhysicsEngine.PlaneImpostor:
  31813. //TODO Oimo now supports cylinder!
  31814. case BABYLON.PhysicsEngine.CylinderImpostor:
  31815. case BABYLON.PhysicsEngine.BoxImpostor:
  31816. default:
  31817. var min = bbox.minimumWorld;
  31818. var max = bbox.maximumWorld;
  31819. var box = max.subtract(min);
  31820. var sizeX = checkWithEpsilon(box.x);
  31821. var sizeY = checkWithEpsilon(box.y);
  31822. var sizeZ = checkWithEpsilon(box.z);
  31823. bodyConfig.type.push('box');
  31824. bodyConfig.size.push(sizeX);
  31825. bodyConfig.size.push(sizeY);
  31826. bodyConfig.size.push(sizeZ);
  31827. break;
  31828. }
  31829. //actually not needed, but hey...
  31830. i.mesh.rotationQuaternion = oldQuaternion;
  31831. });
  31832. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31833. }
  31834. else {
  31835. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31836. }
  31837. impostor.setDeltaPosition(this._tmpPositionVector);
  31838. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31839. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31840. };
  31841. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31842. //impostor.physicsBody.dispose();
  31843. //Same as : (older oimo versions)
  31844. this.world.removeRigidBody(impostor.physicsBody);
  31845. };
  31846. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31847. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31848. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31849. if (!mainBody || !connectedBody) {
  31850. return;
  31851. }
  31852. var jointData = impostorJoint.joint.jointData;
  31853. var options = jointData.nativeParams || {};
  31854. var type;
  31855. var nativeJointData = {
  31856. body1: mainBody,
  31857. body2: connectedBody,
  31858. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31859. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31860. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31861. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31862. min: options.min,
  31863. max: options.max,
  31864. collision: options.collision || jointData.collision,
  31865. spring: options.spring,
  31866. //supporting older version of Oimo
  31867. world: this.world
  31868. };
  31869. switch (impostorJoint.joint.type) {
  31870. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31871. type = "jointBall";
  31872. break;
  31873. case BABYLON.PhysicsJoint.DistanceJoint:
  31874. type = "jointDistance";
  31875. nativeJointData.max = jointData.maxDistance;
  31876. break;
  31877. case BABYLON.PhysicsJoint.PrismaticJoint:
  31878. type = "jointPrisme";
  31879. break;
  31880. case BABYLON.PhysicsJoint.SliderJoint:
  31881. type = "jointSlide";
  31882. break;
  31883. case BABYLON.PhysicsJoint.WheelJoint:
  31884. type = "jointWheel";
  31885. break;
  31886. case BABYLON.PhysicsJoint.HingeJoint:
  31887. default:
  31888. type = "jointHinge";
  31889. break;
  31890. }
  31891. nativeJointData.type = type;
  31892. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31893. };
  31894. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31895. joint.joint.physicsJoint.dispose();
  31896. };
  31897. OimoJSPlugin.prototype.isSupported = function () {
  31898. return OIMO !== undefined;
  31899. };
  31900. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31901. if (!impostor.physicsBody.sleeping) {
  31902. //TODO check that
  31903. if (impostor.physicsBody.shapes.next) {
  31904. var parentShape = this._getLastShape(impostor.physicsBody);
  31905. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31906. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31907. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31908. }
  31909. else {
  31910. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31911. }
  31912. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31913. }
  31914. };
  31915. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31916. var body = impostor.physicsBody;
  31917. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31918. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31919. body.syncShapes();
  31920. body.awake();
  31921. };
  31922. OimoJSPlugin.prototype._getLastShape = function (body) {
  31923. var lastShape = body.shapes;
  31924. while (lastShape.next) {
  31925. lastShape = lastShape.next;
  31926. }
  31927. return lastShape;
  31928. };
  31929. OimoJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31930. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31931. };
  31932. OimoJSPlugin.prototype.dispose = function () {
  31933. this.world.clear();
  31934. };
  31935. return OimoJSPlugin;
  31936. })();
  31937. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31938. })(BABYLON || (BABYLON = {}));
  31939. var BABYLON;
  31940. (function (BABYLON) {
  31941. var DisplayPassPostProcess = (function (_super) {
  31942. __extends(DisplayPassPostProcess, _super);
  31943. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31944. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31945. }
  31946. return DisplayPassPostProcess;
  31947. })(BABYLON.PostProcess);
  31948. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31949. })(BABYLON || (BABYLON = {}));
  31950. var BABYLON;
  31951. (function (BABYLON) {
  31952. var SimplificationSettings = (function () {
  31953. function SimplificationSettings(quality, distance, optimizeMesh) {
  31954. this.quality = quality;
  31955. this.distance = distance;
  31956. this.optimizeMesh = optimizeMesh;
  31957. }
  31958. return SimplificationSettings;
  31959. })();
  31960. BABYLON.SimplificationSettings = SimplificationSettings;
  31961. var SimplificationQueue = (function () {
  31962. function SimplificationQueue() {
  31963. this.running = false;
  31964. this._simplificationArray = [];
  31965. }
  31966. SimplificationQueue.prototype.addTask = function (task) {
  31967. this._simplificationArray.push(task);
  31968. };
  31969. SimplificationQueue.prototype.executeNext = function () {
  31970. var task = this._simplificationArray.pop();
  31971. if (task) {
  31972. this.running = true;
  31973. this.runSimplification(task);
  31974. }
  31975. else {
  31976. this.running = false;
  31977. }
  31978. };
  31979. SimplificationQueue.prototype.runSimplification = function (task) {
  31980. var _this = this;
  31981. if (task.parallelProcessing) {
  31982. //parallel simplifier
  31983. task.settings.forEach(function (setting) {
  31984. var simplifier = _this.getSimplifier(task);
  31985. simplifier.simplify(setting, function (newMesh) {
  31986. task.mesh.addLODLevel(setting.distance, newMesh);
  31987. newMesh.isVisible = true;
  31988. //check if it is the last
  31989. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31990. //all done, run the success callback.
  31991. task.successCallback();
  31992. }
  31993. _this.executeNext();
  31994. });
  31995. });
  31996. }
  31997. else {
  31998. //single simplifier.
  31999. var simplifier = this.getSimplifier(task);
  32000. var runDecimation = function (setting, callback) {
  32001. simplifier.simplify(setting, function (newMesh) {
  32002. task.mesh.addLODLevel(setting.distance, newMesh);
  32003. newMesh.isVisible = true;
  32004. //run the next quality level
  32005. callback();
  32006. });
  32007. };
  32008. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  32009. runDecimation(task.settings[loop.index], function () {
  32010. loop.executeNext();
  32011. });
  32012. }, function () {
  32013. //execution ended, run the success callback.
  32014. if (task.successCallback) {
  32015. task.successCallback();
  32016. }
  32017. _this.executeNext();
  32018. });
  32019. }
  32020. };
  32021. SimplificationQueue.prototype.getSimplifier = function (task) {
  32022. switch (task.simplificationType) {
  32023. case SimplificationType.QUADRATIC:
  32024. default:
  32025. return new QuadraticErrorSimplification(task.mesh);
  32026. }
  32027. };
  32028. return SimplificationQueue;
  32029. })();
  32030. BABYLON.SimplificationQueue = SimplificationQueue;
  32031. /**
  32032. * The implemented types of simplification.
  32033. * At the moment only Quadratic Error Decimation is implemented.
  32034. */
  32035. (function (SimplificationType) {
  32036. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  32037. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  32038. var SimplificationType = BABYLON.SimplificationType;
  32039. var DecimationTriangle = (function () {
  32040. function DecimationTriangle(vertices) {
  32041. this.vertices = vertices;
  32042. this.error = new Array(4);
  32043. this.deleted = false;
  32044. this.isDirty = false;
  32045. this.deletePending = false;
  32046. this.borderFactor = 0;
  32047. }
  32048. return DecimationTriangle;
  32049. })();
  32050. BABYLON.DecimationTriangle = DecimationTriangle;
  32051. var DecimationVertex = (function () {
  32052. function DecimationVertex(position, id) {
  32053. this.position = position;
  32054. this.id = id;
  32055. this.isBorder = true;
  32056. this.q = new QuadraticMatrix();
  32057. this.triangleCount = 0;
  32058. this.triangleStart = 0;
  32059. this.originalOffsets = [];
  32060. }
  32061. DecimationVertex.prototype.updatePosition = function (newPosition) {
  32062. this.position.copyFrom(newPosition);
  32063. };
  32064. return DecimationVertex;
  32065. })();
  32066. BABYLON.DecimationVertex = DecimationVertex;
  32067. var QuadraticMatrix = (function () {
  32068. function QuadraticMatrix(data) {
  32069. this.data = new Array(10);
  32070. for (var i = 0; i < 10; ++i) {
  32071. if (data && data[i]) {
  32072. this.data[i] = data[i];
  32073. }
  32074. else {
  32075. this.data[i] = 0;
  32076. }
  32077. }
  32078. }
  32079. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  32080. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  32081. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  32082. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  32083. return det;
  32084. };
  32085. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  32086. for (var i = 0; i < 10; ++i) {
  32087. this.data[i] += matrix.data[i];
  32088. }
  32089. };
  32090. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  32091. for (var i = 0; i < 10; ++i) {
  32092. this.data[i] += data[i];
  32093. }
  32094. };
  32095. QuadraticMatrix.prototype.add = function (matrix) {
  32096. var m = new QuadraticMatrix();
  32097. for (var i = 0; i < 10; ++i) {
  32098. m.data[i] = this.data[i] + matrix.data[i];
  32099. }
  32100. return m;
  32101. };
  32102. QuadraticMatrix.FromData = function (a, b, c, d) {
  32103. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  32104. };
  32105. //returning an array to avoid garbage collection
  32106. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  32107. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  32108. };
  32109. return QuadraticMatrix;
  32110. })();
  32111. BABYLON.QuadraticMatrix = QuadraticMatrix;
  32112. var Reference = (function () {
  32113. function Reference(vertexId, triangleId) {
  32114. this.vertexId = vertexId;
  32115. this.triangleId = triangleId;
  32116. }
  32117. return Reference;
  32118. })();
  32119. BABYLON.Reference = Reference;
  32120. /**
  32121. * An implementation of the Quadratic Error simplification algorithm.
  32122. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  32123. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  32124. * @author RaananW
  32125. */
  32126. var QuadraticErrorSimplification = (function () {
  32127. function QuadraticErrorSimplification(_mesh) {
  32128. this._mesh = _mesh;
  32129. this.initialized = false;
  32130. this.syncIterations = 5000;
  32131. this.aggressiveness = 7;
  32132. this.decimationIterations = 100;
  32133. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  32134. }
  32135. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  32136. var _this = this;
  32137. this.initDecimatedMesh();
  32138. //iterating through the submeshes array, one after the other.
  32139. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  32140. _this.initWithMesh(loop.index, function () {
  32141. _this.runDecimation(settings, loop.index, function () {
  32142. loop.executeNext();
  32143. });
  32144. }, settings.optimizeMesh);
  32145. }, function () {
  32146. setTimeout(function () {
  32147. successCallback(_this._reconstructedMesh);
  32148. }, 0);
  32149. });
  32150. };
  32151. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  32152. var _this = this;
  32153. var gCount = 0;
  32154. triangle.vertices.forEach(function (vertex) {
  32155. var count = 0;
  32156. var vPos = vertex.position;
  32157. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  32158. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  32159. ++count;
  32160. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  32161. ++count;
  32162. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  32163. ++count;
  32164. if (count > 1) {
  32165. ++gCount;
  32166. }
  32167. ;
  32168. });
  32169. if (gCount > 1) {
  32170. console.log(triangle, gCount);
  32171. }
  32172. return gCount > 1;
  32173. };
  32174. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  32175. var _this = this;
  32176. var targetCount = ~~(this.triangles.length * settings.quality);
  32177. var deletedTriangles = 0;
  32178. var triangleCount = this.triangles.length;
  32179. var iterationFunction = function (iteration, callback) {
  32180. setTimeout(function () {
  32181. if (iteration % 5 === 0) {
  32182. _this.updateMesh(iteration === 0);
  32183. }
  32184. for (var i = 0; i < _this.triangles.length; ++i) {
  32185. _this.triangles[i].isDirty = false;
  32186. }
  32187. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  32188. var trianglesIterator = function (i) {
  32189. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  32190. var t = _this.triangles[tIdx];
  32191. if (!t)
  32192. return;
  32193. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  32194. return;
  32195. }
  32196. for (var j = 0; j < 3; ++j) {
  32197. if (t.error[j] < threshold) {
  32198. var deleted0 = [];
  32199. var deleted1 = [];
  32200. var v0 = t.vertices[j];
  32201. var v1 = t.vertices[(j + 1) % 3];
  32202. if (v0.isBorder !== v1.isBorder)
  32203. continue;
  32204. var p = BABYLON.Vector3.Zero();
  32205. var n = BABYLON.Vector3.Zero();
  32206. var uv = BABYLON.Vector2.Zero();
  32207. var color = new BABYLON.Color4(0, 0, 0, 1);
  32208. _this.calculateError(v0, v1, p, n, uv, color);
  32209. var delTr = [];
  32210. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  32211. continue;
  32212. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  32213. continue;
  32214. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  32215. continue;
  32216. var uniqueArray = [];
  32217. delTr.forEach(function (deletedT) {
  32218. if (uniqueArray.indexOf(deletedT) === -1) {
  32219. deletedT.deletePending = true;
  32220. uniqueArray.push(deletedT);
  32221. }
  32222. });
  32223. if (uniqueArray.length % 2 !== 0) {
  32224. continue;
  32225. }
  32226. v0.q = v1.q.add(v0.q);
  32227. v0.updatePosition(p);
  32228. var tStart = _this.references.length;
  32229. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  32230. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  32231. var tCount = _this.references.length - tStart;
  32232. if (tCount <= v0.triangleCount) {
  32233. if (tCount) {
  32234. for (var c = 0; c < tCount; c++) {
  32235. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  32236. }
  32237. }
  32238. }
  32239. else {
  32240. v0.triangleStart = tStart;
  32241. }
  32242. v0.triangleCount = tCount;
  32243. break;
  32244. }
  32245. }
  32246. };
  32247. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  32248. }, 0);
  32249. };
  32250. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  32251. if (triangleCount - deletedTriangles <= targetCount)
  32252. loop.breakLoop();
  32253. else {
  32254. iterationFunction(loop.index, function () {
  32255. loop.executeNext();
  32256. });
  32257. }
  32258. }, function () {
  32259. setTimeout(function () {
  32260. //reconstruct this part of the mesh
  32261. _this.reconstructMesh(submeshIndex);
  32262. successCallback();
  32263. }, 0);
  32264. });
  32265. };
  32266. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  32267. var _this = this;
  32268. this.vertices = [];
  32269. this.triangles = [];
  32270. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32271. var indices = this._mesh.getIndices();
  32272. var submesh = this._mesh.subMeshes[submeshIndex];
  32273. var findInVertices = function (positionToSearch) {
  32274. if (optimizeMesh) {
  32275. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  32276. if (_this.vertices[ii].position.equals(positionToSearch)) {
  32277. return _this.vertices[ii];
  32278. }
  32279. }
  32280. }
  32281. return null;
  32282. };
  32283. var vertexReferences = [];
  32284. var vertexInit = function (i) {
  32285. var offset = i + submesh.verticesStart;
  32286. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  32287. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  32288. vertex.originalOffsets.push(offset);
  32289. if (vertex.id === _this.vertices.length) {
  32290. _this.vertices.push(vertex);
  32291. }
  32292. vertexReferences.push(vertex.id);
  32293. };
  32294. //var totalVertices = mesh.getTotalVertices();
  32295. var totalVertices = submesh.verticesCount;
  32296. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  32297. var indicesInit = function (i) {
  32298. var offset = (submesh.indexStart / 3) + i;
  32299. var pos = (offset * 3);
  32300. var i0 = indices[pos + 0];
  32301. var i1 = indices[pos + 1];
  32302. var i2 = indices[pos + 2];
  32303. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  32304. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  32305. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  32306. var triangle = new DecimationTriangle([v0, v1, v2]);
  32307. triangle.originalOffset = pos;
  32308. _this.triangles.push(triangle);
  32309. };
  32310. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  32311. _this.init(callback);
  32312. });
  32313. });
  32314. };
  32315. QuadraticErrorSimplification.prototype.init = function (callback) {
  32316. var _this = this;
  32317. var triangleInit1 = function (i) {
  32318. var t = _this.triangles[i];
  32319. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  32320. for (var j = 0; j < 3; j++) {
  32321. 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))));
  32322. }
  32323. };
  32324. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  32325. var triangleInit2 = function (i) {
  32326. var t = _this.triangles[i];
  32327. for (var j = 0; j < 3; ++j) {
  32328. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  32329. }
  32330. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32331. };
  32332. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  32333. _this.initialized = true;
  32334. callback();
  32335. });
  32336. });
  32337. };
  32338. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  32339. var newTriangles = [];
  32340. var i;
  32341. for (i = 0; i < this.vertices.length; ++i) {
  32342. this.vertices[i].triangleCount = 0;
  32343. }
  32344. var t;
  32345. var j;
  32346. for (i = 0; i < this.triangles.length; ++i) {
  32347. if (!this.triangles[i].deleted) {
  32348. t = this.triangles[i];
  32349. for (j = 0; j < 3; ++j) {
  32350. t.vertices[j].triangleCount = 1;
  32351. }
  32352. newTriangles.push(t);
  32353. }
  32354. }
  32355. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  32356. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  32357. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  32358. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  32359. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32360. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32361. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32362. var vertexCount = 0;
  32363. for (i = 0; i < this.vertices.length; ++i) {
  32364. var vertex = this.vertices[i];
  32365. vertex.id = vertexCount;
  32366. if (vertex.triangleCount) {
  32367. vertex.originalOffsets.forEach(function (originalOffset) {
  32368. newPositionData.push(vertex.position.x);
  32369. newPositionData.push(vertex.position.y);
  32370. newPositionData.push(vertex.position.z);
  32371. newNormalData.push(normalData[originalOffset * 3]);
  32372. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32373. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32374. if (uvs && uvs.length) {
  32375. newUVsData.push(uvs[(originalOffset * 2)]);
  32376. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32377. }
  32378. else if (colorsData && colorsData.length) {
  32379. newColorsData.push(colorsData[(originalOffset * 4)]);
  32380. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32381. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32382. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32383. }
  32384. ++vertexCount;
  32385. });
  32386. }
  32387. }
  32388. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32389. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32390. var submeshesArray = this._reconstructedMesh.subMeshes;
  32391. this._reconstructedMesh.subMeshes = [];
  32392. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32393. var originalIndices = this._mesh.getIndices();
  32394. for (i = 0; i < newTriangles.length; ++i) {
  32395. t = newTriangles[i]; //now get the new referencing point for each vertex
  32396. [0, 1, 2].forEach(function (idx) {
  32397. var id = originalIndices[t.originalOffset + idx];
  32398. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32399. if (offset < 0)
  32400. offset = 0;
  32401. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32402. });
  32403. }
  32404. //overwriting the old vertex buffers and indices.
  32405. this._reconstructedMesh.setIndices(newIndicesArray);
  32406. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32407. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32408. if (newUVsData.length > 0)
  32409. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32410. if (newColorsData.length > 0)
  32411. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32412. //create submesh
  32413. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32414. if (submeshIndex > 0) {
  32415. this._reconstructedMesh.subMeshes = [];
  32416. submeshesArray.forEach(function (submesh) {
  32417. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32418. });
  32419. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32420. }
  32421. };
  32422. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32423. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32424. this._reconstructedMesh.material = this._mesh.material;
  32425. this._reconstructedMesh.parent = this._mesh.parent;
  32426. this._reconstructedMesh.isVisible = false;
  32427. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  32428. };
  32429. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32430. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32431. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32432. if (t.deleted)
  32433. continue;
  32434. var s = this.references[vertex1.triangleStart + i].vertexId;
  32435. var v1 = t.vertices[(s + 1) % 3];
  32436. var v2 = t.vertices[(s + 2) % 3];
  32437. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32438. deletedArray[i] = true;
  32439. delTr.push(t);
  32440. continue;
  32441. }
  32442. var d1 = v1.position.subtract(point);
  32443. d1 = d1.normalize();
  32444. var d2 = v2.position.subtract(point);
  32445. d2 = d2.normalize();
  32446. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32447. return true;
  32448. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32449. deletedArray[i] = false;
  32450. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32451. return true;
  32452. }
  32453. return false;
  32454. };
  32455. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32456. var newDeleted = deletedTriangles;
  32457. for (var i = 0; i < vertex.triangleCount; ++i) {
  32458. var ref = this.references[vertex.triangleStart + i];
  32459. var t = this.triangles[ref.triangleId];
  32460. if (t.deleted)
  32461. continue;
  32462. if (deletedArray[i] && t.deletePending) {
  32463. t.deleted = true;
  32464. newDeleted++;
  32465. continue;
  32466. }
  32467. t.vertices[ref.vertexId] = origVertex;
  32468. t.isDirty = true;
  32469. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32470. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32471. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32472. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32473. this.references.push(ref);
  32474. }
  32475. return newDeleted;
  32476. };
  32477. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32478. for (var i = 0; i < this.vertices.length; ++i) {
  32479. var vCount = [];
  32480. var vId = [];
  32481. var v = this.vertices[i];
  32482. var j;
  32483. for (j = 0; j < v.triangleCount; ++j) {
  32484. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32485. for (var ii = 0; ii < 3; ii++) {
  32486. var ofs = 0;
  32487. var vv = triangle.vertices[ii];
  32488. while (ofs < vCount.length) {
  32489. if (vId[ofs] === vv.id)
  32490. break;
  32491. ++ofs;
  32492. }
  32493. if (ofs === vCount.length) {
  32494. vCount.push(1);
  32495. vId.push(vv.id);
  32496. }
  32497. else {
  32498. vCount[ofs]++;
  32499. }
  32500. }
  32501. }
  32502. for (j = 0; j < vCount.length; ++j) {
  32503. if (vCount[j] === 1) {
  32504. this.vertices[vId[j]].isBorder = true;
  32505. }
  32506. else {
  32507. this.vertices[vId[j]].isBorder = false;
  32508. }
  32509. }
  32510. }
  32511. };
  32512. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32513. if (identifyBorders === void 0) { identifyBorders = false; }
  32514. var i;
  32515. if (!identifyBorders) {
  32516. var newTrianglesVector = [];
  32517. for (i = 0; i < this.triangles.length; ++i) {
  32518. if (!this.triangles[i].deleted) {
  32519. newTrianglesVector.push(this.triangles[i]);
  32520. }
  32521. }
  32522. this.triangles = newTrianglesVector;
  32523. }
  32524. for (i = 0; i < this.vertices.length; ++i) {
  32525. this.vertices[i].triangleCount = 0;
  32526. this.vertices[i].triangleStart = 0;
  32527. }
  32528. var t;
  32529. var j;
  32530. var v;
  32531. for (i = 0; i < this.triangles.length; ++i) {
  32532. t = this.triangles[i];
  32533. for (j = 0; j < 3; ++j) {
  32534. v = t.vertices[j];
  32535. v.triangleCount++;
  32536. }
  32537. }
  32538. var tStart = 0;
  32539. for (i = 0; i < this.vertices.length; ++i) {
  32540. this.vertices[i].triangleStart = tStart;
  32541. tStart += this.vertices[i].triangleCount;
  32542. this.vertices[i].triangleCount = 0;
  32543. }
  32544. var newReferences = new Array(this.triangles.length * 3);
  32545. for (i = 0; i < this.triangles.length; ++i) {
  32546. t = this.triangles[i];
  32547. for (j = 0; j < 3; ++j) {
  32548. v = t.vertices[j];
  32549. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32550. v.triangleCount++;
  32551. }
  32552. }
  32553. this.references = newReferences;
  32554. if (identifyBorders) {
  32555. this.identifyBorder();
  32556. }
  32557. };
  32558. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32559. var x = point.x;
  32560. var y = point.y;
  32561. var z = point.z;
  32562. 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
  32563. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32564. };
  32565. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32566. var q = vertex1.q.add(vertex2.q);
  32567. var border = vertex1.isBorder && vertex2.isBorder;
  32568. var error = 0;
  32569. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32570. if (qDet !== 0 && !border) {
  32571. if (!pointResult) {
  32572. pointResult = BABYLON.Vector3.Zero();
  32573. }
  32574. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32575. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32576. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32577. error = this.vertexError(q, pointResult);
  32578. }
  32579. else {
  32580. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32581. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32582. var error1 = this.vertexError(q, vertex1.position);
  32583. var error2 = this.vertexError(q, vertex2.position);
  32584. var error3 = this.vertexError(q, p3);
  32585. error = Math.min(error1, error2, error3);
  32586. if (error === error1) {
  32587. if (pointResult) {
  32588. pointResult.copyFrom(vertex1.position);
  32589. }
  32590. }
  32591. else if (error === error2) {
  32592. if (pointResult) {
  32593. pointResult.copyFrom(vertex2.position);
  32594. }
  32595. }
  32596. else {
  32597. if (pointResult) {
  32598. pointResult.copyFrom(p3);
  32599. }
  32600. }
  32601. }
  32602. return error;
  32603. };
  32604. return QuadraticErrorSimplification;
  32605. })();
  32606. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32607. })(BABYLON || (BABYLON = {}));
  32608. var BABYLON;
  32609. (function (BABYLON) {
  32610. var serializedGeometries = [];
  32611. var serializeGeometry = function (geometry, serializationGeometries) {
  32612. if (serializedGeometries[geometry.id]) {
  32613. return;
  32614. }
  32615. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32616. serializationGeometries.boxes.push(geometry.serialize());
  32617. }
  32618. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32619. serializationGeometries.spheres.push(geometry.serialize());
  32620. }
  32621. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32622. serializationGeometries.cylinders.push(geometry.serialize());
  32623. }
  32624. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32625. serializationGeometries.toruses.push(geometry.serialize());
  32626. }
  32627. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32628. serializationGeometries.grounds.push(geometry.serialize());
  32629. }
  32630. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32631. serializationGeometries.planes.push(geometry.serialize());
  32632. }
  32633. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32634. serializationGeometries.torusKnots.push(geometry.serialize());
  32635. }
  32636. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32637. throw new Error("Unknown primitive type");
  32638. }
  32639. else {
  32640. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32641. }
  32642. serializedGeometries[geometry.id] = true;
  32643. };
  32644. var serializeMesh = function (mesh, serializationScene) {
  32645. var serializationObject = {};
  32646. serializationObject.name = mesh.name;
  32647. serializationObject.id = mesh.id;
  32648. if (BABYLON.Tags.HasTags(mesh)) {
  32649. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32650. }
  32651. serializationObject.position = mesh.position.asArray();
  32652. if (mesh.rotationQuaternion) {
  32653. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32654. }
  32655. else if (mesh.rotation) {
  32656. serializationObject.rotation = mesh.rotation.asArray();
  32657. }
  32658. serializationObject.scaling = mesh.scaling.asArray();
  32659. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32660. serializationObject.isEnabled = mesh.isEnabled();
  32661. serializationObject.isVisible = mesh.isVisible;
  32662. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32663. serializationObject.pickable = mesh.isPickable;
  32664. serializationObject.receiveShadows = mesh.receiveShadows;
  32665. serializationObject.billboardMode = mesh.billboardMode;
  32666. serializationObject.visibility = mesh.visibility;
  32667. serializationObject.checkCollisions = mesh.checkCollisions;
  32668. // Parent
  32669. if (mesh.parent) {
  32670. serializationObject.parentId = mesh.parent.id;
  32671. }
  32672. // Geometry
  32673. var geometry = mesh._geometry;
  32674. if (geometry) {
  32675. var geometryId = geometry.id;
  32676. serializationObject.geometryId = geometryId;
  32677. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32678. // 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
  32679. serializeGeometry(geometry, serializationScene.geometries);
  32680. }
  32681. // SubMeshes
  32682. serializationObject.subMeshes = [];
  32683. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32684. var subMesh = mesh.subMeshes[subIndex];
  32685. serializationObject.subMeshes.push({
  32686. materialIndex: subMesh.materialIndex,
  32687. verticesStart: subMesh.verticesStart,
  32688. verticesCount: subMesh.verticesCount,
  32689. indexStart: subMesh.indexStart,
  32690. indexCount: subMesh.indexCount
  32691. });
  32692. }
  32693. }
  32694. // Material
  32695. if (mesh.material) {
  32696. serializationObject.materialId = mesh.material.id;
  32697. }
  32698. else {
  32699. mesh.material = null;
  32700. }
  32701. // Skeleton
  32702. if (mesh.skeleton) {
  32703. serializationObject.skeletonId = mesh.skeleton.id;
  32704. }
  32705. // Physics
  32706. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32707. serializationObject.physicsMass = mesh.getPhysicsMass();
  32708. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32709. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32710. switch (mesh.getPhysicsImpostor().type) {
  32711. case BABYLON.PhysicsEngine.BoxImpostor:
  32712. serializationObject.physicsImpostor = 1;
  32713. break;
  32714. case BABYLON.PhysicsEngine.SphereImpostor:
  32715. serializationObject.physicsImpostor = 2;
  32716. break;
  32717. }
  32718. }
  32719. // Instances
  32720. serializationObject.instances = [];
  32721. for (var index = 0; index < mesh.instances.length; index++) {
  32722. var instance = mesh.instances[index];
  32723. var serializationInstance = {
  32724. name: instance.name,
  32725. position: instance.position.asArray(),
  32726. scaling: instance.scaling.asArray()
  32727. };
  32728. if (instance.rotationQuaternion) {
  32729. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32730. }
  32731. else if (instance.rotation) {
  32732. serializationInstance.rotation = instance.rotation.asArray();
  32733. }
  32734. serializationObject.instances.push(serializationInstance);
  32735. // Animations
  32736. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32737. serializationInstance.ranges = instance.serializeAnimationRanges();
  32738. }
  32739. // Animations
  32740. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32741. serializationObject.ranges = mesh.serializeAnimationRanges();
  32742. // Layer mask
  32743. serializationObject.layerMask = mesh.layerMask;
  32744. return serializationObject;
  32745. };
  32746. var finalizeSingleMesh = function (mesh, serializationObject) {
  32747. //only works if the mesh is already loaded
  32748. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32749. //serialize material
  32750. if (mesh.material) {
  32751. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32752. serializationObject.materials = serializationObject.materials || [];
  32753. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32754. serializationObject.materials.push(mesh.material.serialize());
  32755. }
  32756. }
  32757. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32758. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32759. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32760. serializationObject.multiMaterials.push(mesh.material.serialize());
  32761. }
  32762. }
  32763. }
  32764. //serialize geometry
  32765. var geometry = mesh._geometry;
  32766. if (geometry) {
  32767. if (!serializationObject.geometries) {
  32768. serializationObject.geometries = {};
  32769. serializationObject.geometries.boxes = [];
  32770. serializationObject.geometries.spheres = [];
  32771. serializationObject.geometries.cylinders = [];
  32772. serializationObject.geometries.toruses = [];
  32773. serializationObject.geometries.grounds = [];
  32774. serializationObject.geometries.planes = [];
  32775. serializationObject.geometries.torusKnots = [];
  32776. serializationObject.geometries.vertexData = [];
  32777. }
  32778. serializeGeometry(geometry, serializationObject.geometries);
  32779. }
  32780. // Skeletons
  32781. if (mesh.skeleton) {
  32782. serializationObject.skeletons = serializationObject.skeletons || [];
  32783. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32784. }
  32785. //serialize the actual mesh
  32786. serializationObject.meshes = serializationObject.meshes || [];
  32787. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32788. }
  32789. };
  32790. var SceneSerializer = (function () {
  32791. function SceneSerializer() {
  32792. }
  32793. SceneSerializer.ClearCache = function () {
  32794. serializedGeometries = [];
  32795. };
  32796. SceneSerializer.Serialize = function (scene) {
  32797. var serializationObject = {};
  32798. // Scene
  32799. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32800. serializationObject.autoClear = scene.autoClear;
  32801. serializationObject.clearColor = scene.clearColor.asArray();
  32802. serializationObject.ambientColor = scene.ambientColor.asArray();
  32803. serializationObject.gravity = scene.gravity.asArray();
  32804. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32805. serializationObject.workerCollisions = scene.workerCollisions;
  32806. // Fog
  32807. if (scene.fogMode && scene.fogMode !== 0) {
  32808. serializationObject.fogMode = scene.fogMode;
  32809. serializationObject.fogColor = scene.fogColor.asArray();
  32810. serializationObject.fogStart = scene.fogStart;
  32811. serializationObject.fogEnd = scene.fogEnd;
  32812. serializationObject.fogDensity = scene.fogDensity;
  32813. }
  32814. //Physics
  32815. if (scene.isPhysicsEnabled()) {
  32816. serializationObject.physicsEnabled = true;
  32817. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32818. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32819. }
  32820. // Lights
  32821. serializationObject.lights = [];
  32822. var index;
  32823. var light;
  32824. for (index = 0; index < scene.lights.length; index++) {
  32825. light = scene.lights[index];
  32826. serializationObject.lights.push(light.serialize());
  32827. }
  32828. // Cameras
  32829. serializationObject.cameras = [];
  32830. for (index = 0; index < scene.cameras.length; index++) {
  32831. var camera = scene.cameras[index];
  32832. serializationObject.cameras.push(camera.serialize());
  32833. }
  32834. if (scene.activeCamera) {
  32835. serializationObject.activeCameraID = scene.activeCamera.id;
  32836. }
  32837. // Animations
  32838. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32839. // Materials
  32840. serializationObject.materials = [];
  32841. serializationObject.multiMaterials = [];
  32842. var material;
  32843. for (index = 0; index < scene.materials.length; index++) {
  32844. material = scene.materials[index];
  32845. serializationObject.materials.push(material.serialize());
  32846. }
  32847. // MultiMaterials
  32848. serializationObject.multiMaterials = [];
  32849. for (index = 0; index < scene.multiMaterials.length; index++) {
  32850. var multiMaterial = scene.multiMaterials[index];
  32851. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32852. }
  32853. // Skeletons
  32854. serializationObject.skeletons = [];
  32855. for (index = 0; index < scene.skeletons.length; index++) {
  32856. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32857. }
  32858. // Geometries
  32859. serializationObject.geometries = {};
  32860. serializationObject.geometries.boxes = [];
  32861. serializationObject.geometries.spheres = [];
  32862. serializationObject.geometries.cylinders = [];
  32863. serializationObject.geometries.toruses = [];
  32864. serializationObject.geometries.grounds = [];
  32865. serializationObject.geometries.planes = [];
  32866. serializationObject.geometries.torusKnots = [];
  32867. serializationObject.geometries.vertexData = [];
  32868. serializedGeometries = [];
  32869. var geometries = scene.getGeometries();
  32870. for (index = 0; index < geometries.length; index++) {
  32871. var geometry = geometries[index];
  32872. if (geometry.isReady()) {
  32873. serializeGeometry(geometry, serializationObject.geometries);
  32874. }
  32875. }
  32876. // Meshes
  32877. serializationObject.meshes = [];
  32878. for (index = 0; index < scene.meshes.length; index++) {
  32879. var abstractMesh = scene.meshes[index];
  32880. if (abstractMesh instanceof BABYLON.Mesh) {
  32881. var mesh = abstractMesh;
  32882. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32883. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32884. }
  32885. }
  32886. }
  32887. // Particles Systems
  32888. serializationObject.particleSystems = [];
  32889. for (index = 0; index < scene.particleSystems.length; index++) {
  32890. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32891. }
  32892. // Lens flares
  32893. serializationObject.lensFlareSystems = [];
  32894. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32895. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32896. }
  32897. // Shadows
  32898. serializationObject.shadowGenerators = [];
  32899. for (index = 0; index < scene.lights.length; index++) {
  32900. light = scene.lights[index];
  32901. if (light.getShadowGenerator()) {
  32902. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32903. }
  32904. }
  32905. return serializationObject;
  32906. };
  32907. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32908. if (withParents === void 0) { withParents = false; }
  32909. if (withChildren === void 0) { withChildren = false; }
  32910. var serializationObject = {};
  32911. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32912. if (withParents || withChildren) {
  32913. //deliberate for loop! not for each, appended should be processed as well.
  32914. for (var i = 0; i < toSerialize.length; ++i) {
  32915. if (withChildren) {
  32916. toSerialize[i].getDescendants().forEach(function (node) {
  32917. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32918. toSerialize.push(node);
  32919. }
  32920. });
  32921. }
  32922. //make sure the array doesn't contain the object already
  32923. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32924. toSerialize.push(toSerialize[i].parent);
  32925. }
  32926. }
  32927. }
  32928. toSerialize.forEach(function (mesh) {
  32929. finalizeSingleMesh(mesh, serializationObject);
  32930. });
  32931. return serializationObject;
  32932. };
  32933. return SceneSerializer;
  32934. })();
  32935. BABYLON.SceneSerializer = SceneSerializer;
  32936. })(BABYLON || (BABYLON = {}));
  32937. var BABYLON;
  32938. (function (BABYLON) {
  32939. // Unique ID when we import meshes from Babylon to CSG
  32940. var currentCSGMeshId = 0;
  32941. // # class Vertex
  32942. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32943. // one to provide additional features like texture coordinates and vertex
  32944. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32945. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32946. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32947. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32948. // is not used anywhere else.
  32949. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32950. var Vertex = (function () {
  32951. function Vertex(pos, normal, uv) {
  32952. this.pos = pos;
  32953. this.normal = normal;
  32954. this.uv = uv;
  32955. }
  32956. Vertex.prototype.clone = function () {
  32957. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32958. };
  32959. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32960. // orientation of a polygon is flipped.
  32961. Vertex.prototype.flip = function () {
  32962. this.normal = this.normal.scale(-1);
  32963. };
  32964. // Create a new vertex between this vertex and `other` by linearly
  32965. // interpolating all properties using a parameter of `t`. Subclasses should
  32966. // override this to interpolate additional properties.
  32967. Vertex.prototype.interpolate = function (other, t) {
  32968. 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));
  32969. };
  32970. return Vertex;
  32971. })();
  32972. // # class Plane
  32973. // Represents a plane in 3D space.
  32974. var Plane = (function () {
  32975. function Plane(normal, w) {
  32976. this.normal = normal;
  32977. this.w = w;
  32978. }
  32979. Plane.FromPoints = function (a, b, c) {
  32980. var v0 = c.subtract(a);
  32981. var v1 = b.subtract(a);
  32982. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32983. return null;
  32984. }
  32985. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32986. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32987. };
  32988. Plane.prototype.clone = function () {
  32989. return new Plane(this.normal.clone(), this.w);
  32990. };
  32991. Plane.prototype.flip = function () {
  32992. this.normal.scaleInPlace(-1);
  32993. this.w = -this.w;
  32994. };
  32995. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32996. // fragments in the appropriate lists. Coplanar polygons go into either
  32997. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32998. // respect to this plane. Polygons in front or in back of this plane go into
  32999. // either `front` or `back`.
  33000. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  33001. var COPLANAR = 0;
  33002. var FRONT = 1;
  33003. var BACK = 2;
  33004. var SPANNING = 3;
  33005. // Classify each point as well as the entire polygon into one of the above
  33006. // four classes.
  33007. var polygonType = 0;
  33008. var types = [];
  33009. var i;
  33010. var t;
  33011. for (i = 0; i < polygon.vertices.length; i++) {
  33012. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  33013. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  33014. polygonType |= type;
  33015. types.push(type);
  33016. }
  33017. // Put the polygon in the correct list, splitting it when necessary.
  33018. switch (polygonType) {
  33019. case COPLANAR:
  33020. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  33021. break;
  33022. case FRONT:
  33023. front.push(polygon);
  33024. break;
  33025. case BACK:
  33026. back.push(polygon);
  33027. break;
  33028. case SPANNING:
  33029. var f = [], b = [];
  33030. for (i = 0; i < polygon.vertices.length; i++) {
  33031. var j = (i + 1) % polygon.vertices.length;
  33032. var ti = types[i], tj = types[j];
  33033. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  33034. if (ti !== BACK)
  33035. f.push(vi);
  33036. if (ti !== FRONT)
  33037. b.push(ti !== BACK ? vi.clone() : vi);
  33038. if ((ti | tj) === SPANNING) {
  33039. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  33040. var v = vi.interpolate(vj, t);
  33041. f.push(v);
  33042. b.push(v.clone());
  33043. }
  33044. }
  33045. var poly;
  33046. if (f.length >= 3) {
  33047. poly = new Polygon(f, polygon.shared);
  33048. if (poly.plane)
  33049. front.push(poly);
  33050. }
  33051. if (b.length >= 3) {
  33052. poly = new Polygon(b, polygon.shared);
  33053. if (poly.plane)
  33054. back.push(poly);
  33055. }
  33056. break;
  33057. }
  33058. };
  33059. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  33060. // point is on the plane.
  33061. Plane.EPSILON = 1e-5;
  33062. return Plane;
  33063. })();
  33064. // # class Polygon
  33065. // Represents a convex polygon. The vertices used to initialize a polygon must
  33066. // be coplanar and form a convex loop.
  33067. //
  33068. // Each convex polygon has a `shared` property, which is shared between all
  33069. // polygons that are clones of each other or were split from the same polygon.
  33070. // This can be used to define per-polygon properties (such as surface color).
  33071. var Polygon = (function () {
  33072. function Polygon(vertices, shared) {
  33073. this.vertices = vertices;
  33074. this.shared = shared;
  33075. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  33076. }
  33077. Polygon.prototype.clone = function () {
  33078. var vertices = this.vertices.map(function (v) { return v.clone(); });
  33079. return new Polygon(vertices, this.shared);
  33080. };
  33081. Polygon.prototype.flip = function () {
  33082. this.vertices.reverse().map(function (v) { v.flip(); });
  33083. this.plane.flip();
  33084. };
  33085. return Polygon;
  33086. })();
  33087. // # class Node
  33088. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  33089. // by picking a polygon to split along. That polygon (and all other coplanar
  33090. // polygons) are added directly to that node and the other polygons are added to
  33091. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  33092. // no distinction between internal and leaf nodes.
  33093. var Node = (function () {
  33094. function Node(polygons) {
  33095. this.plane = null;
  33096. this.front = null;
  33097. this.back = null;
  33098. this.polygons = [];
  33099. if (polygons) {
  33100. this.build(polygons);
  33101. }
  33102. }
  33103. Node.prototype.clone = function () {
  33104. var node = new Node();
  33105. node.plane = this.plane && this.plane.clone();
  33106. node.front = this.front && this.front.clone();
  33107. node.back = this.back && this.back.clone();
  33108. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  33109. return node;
  33110. };
  33111. // Convert solid space to empty space and empty space to solid space.
  33112. Node.prototype.invert = function () {
  33113. for (var i = 0; i < this.polygons.length; i++) {
  33114. this.polygons[i].flip();
  33115. }
  33116. if (this.plane) {
  33117. this.plane.flip();
  33118. }
  33119. if (this.front) {
  33120. this.front.invert();
  33121. }
  33122. if (this.back) {
  33123. this.back.invert();
  33124. }
  33125. var temp = this.front;
  33126. this.front = this.back;
  33127. this.back = temp;
  33128. };
  33129. // Recursively remove all polygons in `polygons` that are inside this BSP
  33130. // tree.
  33131. Node.prototype.clipPolygons = function (polygons) {
  33132. if (!this.plane)
  33133. return polygons.slice();
  33134. var front = [], back = [];
  33135. for (var i = 0; i < polygons.length; i++) {
  33136. this.plane.splitPolygon(polygons[i], front, back, front, back);
  33137. }
  33138. if (this.front) {
  33139. front = this.front.clipPolygons(front);
  33140. }
  33141. if (this.back) {
  33142. back = this.back.clipPolygons(back);
  33143. }
  33144. else {
  33145. back = [];
  33146. }
  33147. return front.concat(back);
  33148. };
  33149. // Remove all polygons in this BSP tree that are inside the other BSP tree
  33150. // `bsp`.
  33151. Node.prototype.clipTo = function (bsp) {
  33152. this.polygons = bsp.clipPolygons(this.polygons);
  33153. if (this.front)
  33154. this.front.clipTo(bsp);
  33155. if (this.back)
  33156. this.back.clipTo(bsp);
  33157. };
  33158. // Return a list of all polygons in this BSP tree.
  33159. Node.prototype.allPolygons = function () {
  33160. var polygons = this.polygons.slice();
  33161. if (this.front)
  33162. polygons = polygons.concat(this.front.allPolygons());
  33163. if (this.back)
  33164. polygons = polygons.concat(this.back.allPolygons());
  33165. return polygons;
  33166. };
  33167. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  33168. // new polygons are filtered down to the bottom of the tree and become new
  33169. // nodes there. Each set of polygons is partitioned using the first polygon
  33170. // (no heuristic is used to pick a good split).
  33171. Node.prototype.build = function (polygons) {
  33172. if (!polygons.length)
  33173. return;
  33174. if (!this.plane)
  33175. this.plane = polygons[0].plane.clone();
  33176. var front = [], back = [];
  33177. for (var i = 0; i < polygons.length; i++) {
  33178. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  33179. }
  33180. if (front.length) {
  33181. if (!this.front)
  33182. this.front = new Node();
  33183. this.front.build(front);
  33184. }
  33185. if (back.length) {
  33186. if (!this.back)
  33187. this.back = new Node();
  33188. this.back.build(back);
  33189. }
  33190. };
  33191. return Node;
  33192. })();
  33193. var CSG = (function () {
  33194. function CSG() {
  33195. this.polygons = new Array();
  33196. }
  33197. // Convert BABYLON.Mesh to BABYLON.CSG
  33198. CSG.FromMesh = function (mesh) {
  33199. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  33200. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  33201. if (mesh instanceof BABYLON.Mesh) {
  33202. mesh.computeWorldMatrix(true);
  33203. matrix = mesh.getWorldMatrix();
  33204. meshPosition = mesh.position.clone();
  33205. meshRotation = mesh.rotation.clone();
  33206. if (mesh.rotationQuaternion) {
  33207. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  33208. }
  33209. meshScaling = mesh.scaling.clone();
  33210. }
  33211. else {
  33212. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  33213. }
  33214. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33215. var subMeshes = mesh.subMeshes;
  33216. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  33217. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  33218. vertices = [];
  33219. for (var j = 0; j < 3; j++) {
  33220. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  33221. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  33222. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  33223. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  33224. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  33225. vertex = new Vertex(position, normal, uv);
  33226. vertices.push(vertex);
  33227. }
  33228. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  33229. // To handle the case of degenerated triangle
  33230. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  33231. if (polygon.plane)
  33232. polygons.push(polygon);
  33233. }
  33234. }
  33235. var csg = CSG.FromPolygons(polygons);
  33236. csg.matrix = matrix;
  33237. csg.position = meshPosition;
  33238. csg.rotation = meshRotation;
  33239. csg.scaling = meshScaling;
  33240. csg.rotationQuaternion = meshRotationQuaternion;
  33241. currentCSGMeshId++;
  33242. return csg;
  33243. };
  33244. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  33245. CSG.FromPolygons = function (polygons) {
  33246. var csg = new CSG();
  33247. csg.polygons = polygons;
  33248. return csg;
  33249. };
  33250. CSG.prototype.clone = function () {
  33251. var csg = new CSG();
  33252. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  33253. csg.copyTransformAttributes(this);
  33254. return csg;
  33255. };
  33256. CSG.prototype.toPolygons = function () {
  33257. return this.polygons;
  33258. };
  33259. CSG.prototype.union = function (csg) {
  33260. var a = new Node(this.clone().polygons);
  33261. var b = new Node(csg.clone().polygons);
  33262. a.clipTo(b);
  33263. b.clipTo(a);
  33264. b.invert();
  33265. b.clipTo(a);
  33266. b.invert();
  33267. a.build(b.allPolygons());
  33268. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  33269. };
  33270. CSG.prototype.unionInPlace = function (csg) {
  33271. var a = new Node(this.polygons);
  33272. var b = new Node(csg.polygons);
  33273. a.clipTo(b);
  33274. b.clipTo(a);
  33275. b.invert();
  33276. b.clipTo(a);
  33277. b.invert();
  33278. a.build(b.allPolygons());
  33279. this.polygons = a.allPolygons();
  33280. };
  33281. CSG.prototype.subtract = function (csg) {
  33282. var a = new Node(this.clone().polygons);
  33283. var b = new Node(csg.clone().polygons);
  33284. a.invert();
  33285. a.clipTo(b);
  33286. b.clipTo(a);
  33287. b.invert();
  33288. b.clipTo(a);
  33289. b.invert();
  33290. a.build(b.allPolygons());
  33291. a.invert();
  33292. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  33293. };
  33294. CSG.prototype.subtractInPlace = function (csg) {
  33295. var a = new Node(this.polygons);
  33296. var b = new Node(csg.polygons);
  33297. a.invert();
  33298. a.clipTo(b);
  33299. b.clipTo(a);
  33300. b.invert();
  33301. b.clipTo(a);
  33302. b.invert();
  33303. a.build(b.allPolygons());
  33304. a.invert();
  33305. this.polygons = a.allPolygons();
  33306. };
  33307. CSG.prototype.intersect = function (csg) {
  33308. var a = new Node(this.clone().polygons);
  33309. var b = new Node(csg.clone().polygons);
  33310. a.invert();
  33311. b.clipTo(a);
  33312. b.invert();
  33313. a.clipTo(b);
  33314. b.clipTo(a);
  33315. a.build(b.allPolygons());
  33316. a.invert();
  33317. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  33318. };
  33319. CSG.prototype.intersectInPlace = function (csg) {
  33320. var a = new Node(this.polygons);
  33321. var b = new Node(csg.polygons);
  33322. a.invert();
  33323. b.clipTo(a);
  33324. b.invert();
  33325. a.clipTo(b);
  33326. b.clipTo(a);
  33327. a.build(b.allPolygons());
  33328. a.invert();
  33329. this.polygons = a.allPolygons();
  33330. };
  33331. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  33332. // not modified.
  33333. CSG.prototype.inverse = function () {
  33334. var csg = this.clone();
  33335. csg.inverseInPlace();
  33336. return csg;
  33337. };
  33338. CSG.prototype.inverseInPlace = function () {
  33339. this.polygons.map(function (p) { p.flip(); });
  33340. };
  33341. // This is used to keep meshes transformations so they can be restored
  33342. // when we build back a Babylon Mesh
  33343. // NB : All CSG operations are performed in world coordinates
  33344. CSG.prototype.copyTransformAttributes = function (csg) {
  33345. this.matrix = csg.matrix;
  33346. this.position = csg.position;
  33347. this.rotation = csg.rotation;
  33348. this.scaling = csg.scaling;
  33349. this.rotationQuaternion = csg.rotationQuaternion;
  33350. return this;
  33351. };
  33352. // Build Raw mesh from CSG
  33353. // Coordinates here are in world space
  33354. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  33355. var matrix = this.matrix.clone();
  33356. matrix.invert();
  33357. 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;
  33358. if (keepSubMeshes) {
  33359. // Sort Polygons, since subMeshes are indices range
  33360. polygons.sort(function (a, b) {
  33361. if (a.shared.meshId === b.shared.meshId) {
  33362. return a.shared.subMeshId - b.shared.subMeshId;
  33363. }
  33364. else {
  33365. return a.shared.meshId - b.shared.meshId;
  33366. }
  33367. });
  33368. }
  33369. for (var i = 0, il = polygons.length; i < il; i++) {
  33370. polygon = polygons[i];
  33371. // Building SubMeshes
  33372. if (!subMesh_dict[polygon.shared.meshId]) {
  33373. subMesh_dict[polygon.shared.meshId] = {};
  33374. }
  33375. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  33376. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  33377. indexStart: +Infinity,
  33378. indexEnd: -Infinity,
  33379. materialIndex: polygon.shared.materialIndex
  33380. };
  33381. }
  33382. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  33383. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  33384. polygonIndices[0] = 0;
  33385. polygonIndices[1] = j - 1;
  33386. polygonIndices[2] = j;
  33387. for (var k = 0; k < 3; k++) {
  33388. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  33389. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  33390. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  33391. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  33392. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  33393. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  33394. // Check if 2 points can be merged
  33395. if (!(typeof vertex_idx !== 'undefined' &&
  33396. normals[vertex_idx * 3] === localNormal.x &&
  33397. normals[vertex_idx * 3 + 1] === localNormal.y &&
  33398. normals[vertex_idx * 3 + 2] === localNormal.z &&
  33399. uvs[vertex_idx * 2] === uv.x &&
  33400. uvs[vertex_idx * 2 + 1] === uv.y)) {
  33401. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  33402. uvs.push(uv.x, uv.y);
  33403. normals.push(normal.x, normal.y, normal.z);
  33404. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  33405. }
  33406. indices.push(vertex_idx);
  33407. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  33408. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  33409. currentIndex++;
  33410. }
  33411. }
  33412. }
  33413. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  33414. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33415. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  33416. mesh.setIndices(indices);
  33417. if (keepSubMeshes) {
  33418. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  33419. var materialIndexOffset = 0, materialMaxIndex;
  33420. mesh.subMeshes = new Array();
  33421. for (var m in subMesh_dict) {
  33422. materialMaxIndex = -1;
  33423. for (var sm in subMesh_dict[m]) {
  33424. subMesh_obj = subMesh_dict[m][sm];
  33425. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  33426. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  33427. }
  33428. materialIndexOffset += ++materialMaxIndex;
  33429. }
  33430. }
  33431. return mesh;
  33432. };
  33433. // Build Mesh from CSG taking material and transforms into account
  33434. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  33435. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  33436. mesh.material = material;
  33437. mesh.position.copyFrom(this.position);
  33438. mesh.rotation.copyFrom(this.rotation);
  33439. if (this.rotationQuaternion) {
  33440. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  33441. }
  33442. mesh.scaling.copyFrom(this.scaling);
  33443. mesh.computeWorldMatrix(true);
  33444. return mesh;
  33445. };
  33446. return CSG;
  33447. })();
  33448. BABYLON.CSG = CSG;
  33449. })(BABYLON || (BABYLON = {}));
  33450. var BABYLON;
  33451. (function (BABYLON) {
  33452. var VRDistortionCorrectionPostProcess = (function (_super) {
  33453. __extends(VRDistortionCorrectionPostProcess, _super);
  33454. //ANY
  33455. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  33456. var _this = this;
  33457. _super.call(this, name, "vrDistortionCorrection", [
  33458. 'LensCenter',
  33459. 'Scale',
  33460. 'ScaleIn',
  33461. 'HmdWarpParam'
  33462. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  33463. this._isRightEye = isRightEye;
  33464. this._distortionFactors = vrMetrics.distortionK;
  33465. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  33466. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  33467. this.onSizeChanged = function () {
  33468. _this.aspectRatio = _this.width * .5 / _this.height;
  33469. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  33470. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  33471. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  33472. };
  33473. this.onApply = function (effect) {
  33474. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  33475. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  33476. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  33477. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  33478. };
  33479. }
  33480. return VRDistortionCorrectionPostProcess;
  33481. })(BABYLON.PostProcess);
  33482. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  33483. })(BABYLON || (BABYLON = {}));
  33484. // Mainly based on these 2 articles :
  33485. // 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
  33486. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  33487. var BABYLON;
  33488. (function (BABYLON) {
  33489. (function (JoystickAxis) {
  33490. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  33491. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  33492. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  33493. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  33494. var JoystickAxis = BABYLON.JoystickAxis;
  33495. var VirtualJoystick = (function () {
  33496. function VirtualJoystick(leftJoystick) {
  33497. var _this = this;
  33498. if (leftJoystick) {
  33499. this._leftJoystick = true;
  33500. }
  33501. else {
  33502. this._leftJoystick = false;
  33503. }
  33504. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  33505. VirtualJoystick._globalJoystickIndex++;
  33506. // By default left & right arrow keys are moving the X
  33507. // and up & down keys are moving the Y
  33508. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33509. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33510. this.reverseLeftRight = false;
  33511. this.reverseUpDown = false;
  33512. // collections of pointers
  33513. this._touches = new BABYLON.SmartCollection();
  33514. this.deltaPosition = BABYLON.Vector3.Zero();
  33515. this._joystickSensibility = 25;
  33516. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33517. this._rotationSpeed = 25;
  33518. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  33519. this._rotateOnAxisRelativeToMesh = false;
  33520. this._onResize = function (evt) {
  33521. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33522. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33523. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  33524. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  33525. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  33526. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  33527. };
  33528. // injecting a canvas element on top of the canvas 3D game
  33529. if (!VirtualJoystick.vjCanvas) {
  33530. window.addEventListener("resize", this._onResize, false);
  33531. VirtualJoystick.vjCanvas = document.createElement("canvas");
  33532. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33533. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33534. VirtualJoystick.vjCanvas.width = window.innerWidth;
  33535. VirtualJoystick.vjCanvas.height = window.innerHeight;
  33536. VirtualJoystick.vjCanvas.style.width = "100%";
  33537. VirtualJoystick.vjCanvas.style.height = "100%";
  33538. VirtualJoystick.vjCanvas.style.position = "absolute";
  33539. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  33540. VirtualJoystick.vjCanvas.style.top = "0px";
  33541. VirtualJoystick.vjCanvas.style.left = "0px";
  33542. VirtualJoystick.vjCanvas.style.zIndex = "5";
  33543. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  33544. // Support for jQuery PEP polyfill
  33545. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  33546. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  33547. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  33548. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33549. document.body.appendChild(VirtualJoystick.vjCanvas);
  33550. }
  33551. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  33552. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  33553. this.pressed = false;
  33554. // default joystick color
  33555. this._joystickColor = "cyan";
  33556. this._joystickPointerID = -1;
  33557. // current joystick position
  33558. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  33559. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  33560. // origin joystick position
  33561. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  33562. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  33563. this._onPointerDownHandlerRef = function (evt) {
  33564. _this._onPointerDown(evt);
  33565. };
  33566. this._onPointerMoveHandlerRef = function (evt) {
  33567. _this._onPointerMove(evt);
  33568. };
  33569. this._onPointerOutHandlerRef = function (evt) {
  33570. _this._onPointerUp(evt);
  33571. };
  33572. this._onPointerUpHandlerRef = function (evt) {
  33573. _this._onPointerUp(evt);
  33574. };
  33575. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  33576. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  33577. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  33578. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  33579. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  33580. evt.preventDefault(); // Disables system menu
  33581. }, false);
  33582. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33583. }
  33584. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  33585. this._joystickSensibility = newJoystickSensibility;
  33586. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33587. };
  33588. VirtualJoystick.prototype._onPointerDown = function (e) {
  33589. var positionOnScreenCondition;
  33590. e.preventDefault();
  33591. if (this._leftJoystick === true) {
  33592. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  33593. }
  33594. else {
  33595. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  33596. }
  33597. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33598. // First contact will be dedicated to the virtual joystick
  33599. this._joystickPointerID = e.pointerId;
  33600. this._joystickPointerStartPos.x = e.clientX;
  33601. this._joystickPointerStartPos.y = e.clientY;
  33602. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33603. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33604. this._deltaJoystickVector.x = 0;
  33605. this._deltaJoystickVector.y = 0;
  33606. this.pressed = true;
  33607. this._touches.add(e.pointerId.toString(), e);
  33608. }
  33609. else {
  33610. // You can only trigger the action buttons with a joystick declared
  33611. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33612. this._action();
  33613. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33614. }
  33615. }
  33616. };
  33617. VirtualJoystick.prototype._onPointerMove = function (e) {
  33618. // If the current pointer is the one associated to the joystick (first touch contact)
  33619. if (this._joystickPointerID == e.pointerId) {
  33620. this._joystickPointerPos.x = e.clientX;
  33621. this._joystickPointerPos.y = e.clientY;
  33622. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33623. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33624. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33625. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33626. switch (this._axisTargetedByLeftAndRight) {
  33627. case JoystickAxis.X:
  33628. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33629. break;
  33630. case JoystickAxis.Y:
  33631. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33632. break;
  33633. case JoystickAxis.Z:
  33634. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33635. break;
  33636. }
  33637. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33638. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33639. switch (this._axisTargetedByUpAndDown) {
  33640. case JoystickAxis.X:
  33641. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33642. break;
  33643. case JoystickAxis.Y:
  33644. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33645. break;
  33646. case JoystickAxis.Z:
  33647. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33648. break;
  33649. }
  33650. }
  33651. else {
  33652. if (this._touches.item(e.pointerId.toString())) {
  33653. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33654. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33655. }
  33656. }
  33657. };
  33658. VirtualJoystick.prototype._onPointerUp = function (e) {
  33659. if (this._joystickPointerID == e.pointerId) {
  33660. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33661. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33662. this._joystickPointerID = -1;
  33663. this.pressed = false;
  33664. }
  33665. else {
  33666. var touch = this._touches.item(e.pointerId.toString());
  33667. if (touch) {
  33668. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33669. }
  33670. }
  33671. this._deltaJoystickVector.x = 0;
  33672. this._deltaJoystickVector.y = 0;
  33673. this._touches.remove(e.pointerId.toString());
  33674. };
  33675. /**
  33676. * Change the color of the virtual joystick
  33677. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33678. */
  33679. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33680. this._joystickColor = newColor;
  33681. };
  33682. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33683. this._action = action;
  33684. };
  33685. // Define which axis you'd like to control for left & right
  33686. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33687. switch (axis) {
  33688. case JoystickAxis.X:
  33689. case JoystickAxis.Y:
  33690. case JoystickAxis.Z:
  33691. this._axisTargetedByLeftAndRight = axis;
  33692. break;
  33693. default:
  33694. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33695. break;
  33696. }
  33697. };
  33698. // Define which axis you'd like to control for up & down
  33699. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33700. switch (axis) {
  33701. case JoystickAxis.X:
  33702. case JoystickAxis.Y:
  33703. case JoystickAxis.Z:
  33704. this._axisTargetedByUpAndDown = axis;
  33705. break;
  33706. default:
  33707. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33708. break;
  33709. }
  33710. };
  33711. VirtualJoystick.prototype._clearCanvas = function () {
  33712. if (this._leftJoystick) {
  33713. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33714. }
  33715. else {
  33716. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33717. }
  33718. };
  33719. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33720. var _this = this;
  33721. if (this.pressed) {
  33722. this._touches.forEach(function (touch) {
  33723. if (touch.pointerId === _this._joystickPointerID) {
  33724. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33725. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33726. VirtualJoystick.vjCanvasContext.beginPath();
  33727. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33728. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33729. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33730. VirtualJoystick.vjCanvasContext.stroke();
  33731. VirtualJoystick.vjCanvasContext.closePath();
  33732. VirtualJoystick.vjCanvasContext.beginPath();
  33733. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33734. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33735. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33736. VirtualJoystick.vjCanvasContext.stroke();
  33737. VirtualJoystick.vjCanvasContext.closePath();
  33738. VirtualJoystick.vjCanvasContext.beginPath();
  33739. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33740. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33741. VirtualJoystick.vjCanvasContext.stroke();
  33742. VirtualJoystick.vjCanvasContext.closePath();
  33743. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33744. }
  33745. else {
  33746. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33747. VirtualJoystick.vjCanvasContext.beginPath();
  33748. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33749. VirtualJoystick.vjCanvasContext.beginPath();
  33750. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33751. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33752. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33753. VirtualJoystick.vjCanvasContext.stroke();
  33754. VirtualJoystick.vjCanvasContext.closePath();
  33755. touch.prevX = touch.x;
  33756. touch.prevY = touch.y;
  33757. }
  33758. ;
  33759. });
  33760. }
  33761. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33762. };
  33763. VirtualJoystick.prototype.releaseCanvas = function () {
  33764. if (VirtualJoystick.vjCanvas) {
  33765. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33766. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33767. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33768. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33769. window.removeEventListener("resize", this._onResize);
  33770. document.body.removeChild(VirtualJoystick.vjCanvas);
  33771. VirtualJoystick.vjCanvas = null;
  33772. }
  33773. };
  33774. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33775. VirtualJoystick._globalJoystickIndex = 0;
  33776. return VirtualJoystick;
  33777. })();
  33778. BABYLON.VirtualJoystick = VirtualJoystick;
  33779. })(BABYLON || (BABYLON = {}));
  33780. var BABYLON;
  33781. (function (BABYLON) {
  33782. // We're mainly based on the logic defined into the FreeCamera code
  33783. var VirtualJoysticksCamera = (function (_super) {
  33784. __extends(VirtualJoysticksCamera, _super);
  33785. function VirtualJoysticksCamera(name, position, scene) {
  33786. _super.call(this, name, position, scene);
  33787. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33788. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33789. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33790. this._leftjoystick.setJoystickSensibility(0.15);
  33791. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33792. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33793. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33794. this._rightjoystick.reverseUpDown = true;
  33795. this._rightjoystick.setJoystickSensibility(0.05);
  33796. this._rightjoystick.setJoystickColor("yellow");
  33797. }
  33798. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33799. return this._leftjoystick;
  33800. };
  33801. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33802. return this._rightjoystick;
  33803. };
  33804. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33805. var speed = this._computeLocalCameraSpeed() * 50;
  33806. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33807. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33808. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33809. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33810. if (!this._leftjoystick.pressed) {
  33811. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33812. }
  33813. if (!this._rightjoystick.pressed) {
  33814. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33815. }
  33816. _super.prototype._checkInputs.call(this);
  33817. };
  33818. VirtualJoysticksCamera.prototype.dispose = function () {
  33819. this._leftjoystick.releaseCanvas();
  33820. _super.prototype.dispose.call(this);
  33821. };
  33822. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33823. return "VirtualJoysticksCamera";
  33824. };
  33825. return VirtualJoysticksCamera;
  33826. })(BABYLON.FreeCamera);
  33827. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33828. })(BABYLON || (BABYLON = {}));
  33829. var BABYLON;
  33830. (function (BABYLON) {
  33831. var AnaglyphPostProcess = (function (_super) {
  33832. __extends(AnaglyphPostProcess, _super);
  33833. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33834. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33835. }
  33836. return AnaglyphPostProcess;
  33837. })(BABYLON.PostProcess);
  33838. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33839. })(BABYLON || (BABYLON = {}));
  33840. var BABYLON;
  33841. (function (BABYLON) {
  33842. var OutlineRenderer = (function () {
  33843. function OutlineRenderer(scene) {
  33844. this._scene = scene;
  33845. }
  33846. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33847. var _this = this;
  33848. if (useOverlay === void 0) { useOverlay = false; }
  33849. var scene = this._scene;
  33850. var engine = this._scene.getEngine();
  33851. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33852. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33853. return;
  33854. }
  33855. var mesh = subMesh.getRenderingMesh();
  33856. var material = subMesh.getMaterial();
  33857. engine.enableEffect(this._effect);
  33858. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33859. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33860. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33861. // Bones
  33862. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33863. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33864. }
  33865. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33866. // Alpha test
  33867. if (material && material.needAlphaTesting()) {
  33868. var alphaTexture = material.getAlphaTestTexture();
  33869. this._effect.setTexture("diffuseSampler", alphaTexture);
  33870. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33871. }
  33872. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33873. };
  33874. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33875. var defines = [];
  33876. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33877. var mesh = subMesh.getMesh();
  33878. var material = subMesh.getMaterial();
  33879. // Alpha test
  33880. if (material && material.needAlphaTesting()) {
  33881. defines.push("#define ALPHATEST");
  33882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33883. attribs.push(BABYLON.VertexBuffer.UVKind);
  33884. defines.push("#define UV1");
  33885. }
  33886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33887. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33888. defines.push("#define UV2");
  33889. }
  33890. }
  33891. // Bones
  33892. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33895. if (mesh.numBoneInfluencers > 4) {
  33896. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33897. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33898. }
  33899. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33900. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33901. }
  33902. else {
  33903. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33904. }
  33905. // Instances
  33906. if (useInstances) {
  33907. defines.push("#define INSTANCES");
  33908. attribs.push("world0");
  33909. attribs.push("world1");
  33910. attribs.push("world2");
  33911. attribs.push("world3");
  33912. }
  33913. // Get correct effect
  33914. var join = defines.join("\n");
  33915. if (this._cachedDefines !== join) {
  33916. this._cachedDefines = join;
  33917. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33918. }
  33919. return this._effect.isReady();
  33920. };
  33921. return OutlineRenderer;
  33922. })();
  33923. BABYLON.OutlineRenderer = OutlineRenderer;
  33924. })(BABYLON || (BABYLON = {}));
  33925. var BABYLON;
  33926. (function (BABYLON) {
  33927. var MeshAssetTask = (function () {
  33928. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33929. this.name = name;
  33930. this.meshesNames = meshesNames;
  33931. this.rootUrl = rootUrl;
  33932. this.sceneFilename = sceneFilename;
  33933. this.isCompleted = false;
  33934. }
  33935. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33936. var _this = this;
  33937. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33938. _this.loadedMeshes = meshes;
  33939. _this.loadedParticleSystems = particleSystems;
  33940. _this.loadedSkeletons = skeletons;
  33941. _this.isCompleted = true;
  33942. if (_this.onSuccess) {
  33943. _this.onSuccess(_this);
  33944. }
  33945. onSuccess();
  33946. }, null, function () {
  33947. if (_this.onError) {
  33948. _this.onError(_this);
  33949. }
  33950. onError();
  33951. });
  33952. };
  33953. return MeshAssetTask;
  33954. })();
  33955. BABYLON.MeshAssetTask = MeshAssetTask;
  33956. var TextFileAssetTask = (function () {
  33957. function TextFileAssetTask(name, url) {
  33958. this.name = name;
  33959. this.url = url;
  33960. this.isCompleted = false;
  33961. }
  33962. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33963. var _this = this;
  33964. BABYLON.Tools.LoadFile(this.url, function (data) {
  33965. _this.text = data;
  33966. _this.isCompleted = true;
  33967. if (_this.onSuccess) {
  33968. _this.onSuccess(_this);
  33969. }
  33970. onSuccess();
  33971. }, null, scene.database, false, function () {
  33972. if (_this.onError) {
  33973. _this.onError(_this);
  33974. }
  33975. onError();
  33976. });
  33977. };
  33978. return TextFileAssetTask;
  33979. })();
  33980. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33981. var BinaryFileAssetTask = (function () {
  33982. function BinaryFileAssetTask(name, url) {
  33983. this.name = name;
  33984. this.url = url;
  33985. this.isCompleted = false;
  33986. }
  33987. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33988. var _this = this;
  33989. BABYLON.Tools.LoadFile(this.url, function (data) {
  33990. _this.data = data;
  33991. _this.isCompleted = true;
  33992. if (_this.onSuccess) {
  33993. _this.onSuccess(_this);
  33994. }
  33995. onSuccess();
  33996. }, null, scene.database, true, function () {
  33997. if (_this.onError) {
  33998. _this.onError(_this);
  33999. }
  34000. onError();
  34001. });
  34002. };
  34003. return BinaryFileAssetTask;
  34004. })();
  34005. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  34006. var ImageAssetTask = (function () {
  34007. function ImageAssetTask(name, url) {
  34008. this.name = name;
  34009. this.url = url;
  34010. this.isCompleted = false;
  34011. }
  34012. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  34013. var _this = this;
  34014. var img = new Image();
  34015. img.onload = function () {
  34016. _this.image = img;
  34017. _this.isCompleted = true;
  34018. if (_this.onSuccess) {
  34019. _this.onSuccess(_this);
  34020. }
  34021. onSuccess();
  34022. };
  34023. img.onerror = function () {
  34024. if (_this.onError) {
  34025. _this.onError(_this);
  34026. }
  34027. onError();
  34028. };
  34029. img.src = this.url;
  34030. };
  34031. return ImageAssetTask;
  34032. })();
  34033. BABYLON.ImageAssetTask = ImageAssetTask;
  34034. var TextureAssetTask = (function () {
  34035. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  34036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34037. this.name = name;
  34038. this.url = url;
  34039. this.noMipmap = noMipmap;
  34040. this.invertY = invertY;
  34041. this.samplingMode = samplingMode;
  34042. this.isCompleted = false;
  34043. }
  34044. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  34045. var _this = this;
  34046. var onload = function () {
  34047. _this.isCompleted = true;
  34048. if (_this.onSuccess) {
  34049. _this.onSuccess(_this);
  34050. }
  34051. onSuccess();
  34052. };
  34053. var onerror = function () {
  34054. if (_this.onError) {
  34055. _this.onError(_this);
  34056. }
  34057. onError();
  34058. };
  34059. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  34060. };
  34061. return TextureAssetTask;
  34062. })();
  34063. BABYLON.TextureAssetTask = TextureAssetTask;
  34064. var AssetsManager = (function () {
  34065. function AssetsManager(scene) {
  34066. this._tasks = new Array();
  34067. this._waitingTasksCount = 0;
  34068. this.useDefaultLoadingScreen = true;
  34069. this._scene = scene;
  34070. }
  34071. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  34072. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  34073. this._tasks.push(task);
  34074. return task;
  34075. };
  34076. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  34077. var task = new TextFileAssetTask(taskName, url);
  34078. this._tasks.push(task);
  34079. return task;
  34080. };
  34081. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  34082. var task = new BinaryFileAssetTask(taskName, url);
  34083. this._tasks.push(task);
  34084. return task;
  34085. };
  34086. AssetsManager.prototype.addImageTask = function (taskName, url) {
  34087. var task = new ImageAssetTask(taskName, url);
  34088. this._tasks.push(task);
  34089. return task;
  34090. };
  34091. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  34092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34093. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  34094. this._tasks.push(task);
  34095. return task;
  34096. };
  34097. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  34098. this._waitingTasksCount--;
  34099. if (this._waitingTasksCount === 0) {
  34100. if (this.onFinish) {
  34101. this.onFinish(this._tasks);
  34102. }
  34103. this._scene.getEngine().hideLoadingUI();
  34104. }
  34105. };
  34106. AssetsManager.prototype._runTask = function (task) {
  34107. var _this = this;
  34108. task.run(this._scene, function () {
  34109. if (_this.onTaskSuccess) {
  34110. _this.onTaskSuccess(task);
  34111. }
  34112. _this._decreaseWaitingTasksCount();
  34113. }, function () {
  34114. if (_this.onTaskError) {
  34115. _this.onTaskError(task);
  34116. }
  34117. _this._decreaseWaitingTasksCount();
  34118. });
  34119. };
  34120. AssetsManager.prototype.reset = function () {
  34121. this._tasks = new Array();
  34122. return this;
  34123. };
  34124. AssetsManager.prototype.load = function () {
  34125. this._waitingTasksCount = this._tasks.length;
  34126. if (this._waitingTasksCount === 0) {
  34127. if (this.onFinish) {
  34128. this.onFinish(this._tasks);
  34129. }
  34130. return this;
  34131. }
  34132. if (this.useDefaultLoadingScreen) {
  34133. this._scene.getEngine().displayLoadingUI();
  34134. }
  34135. for (var index = 0; index < this._tasks.length; index++) {
  34136. var task = this._tasks[index];
  34137. this._runTask(task);
  34138. }
  34139. return this;
  34140. };
  34141. return AssetsManager;
  34142. })();
  34143. BABYLON.AssetsManager = AssetsManager;
  34144. })(BABYLON || (BABYLON = {}));
  34145. var BABYLON;
  34146. (function (BABYLON) {
  34147. var VRCameraMetrics = (function () {
  34148. function VRCameraMetrics() {
  34149. this.compensateDistortion = true;
  34150. }
  34151. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  34152. get: function () {
  34153. return this.hResolution / (2 * this.vResolution);
  34154. },
  34155. enumerable: true,
  34156. configurable: true
  34157. });
  34158. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  34159. get: function () {
  34160. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  34161. },
  34162. enumerable: true,
  34163. configurable: true
  34164. });
  34165. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  34166. get: function () {
  34167. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  34168. var h = (4 * meters) / this.hScreenSize;
  34169. return BABYLON.Matrix.Translation(h, 0, 0);
  34170. },
  34171. enumerable: true,
  34172. configurable: true
  34173. });
  34174. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  34175. get: function () {
  34176. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  34177. var h = (4 * meters) / this.hScreenSize;
  34178. return BABYLON.Matrix.Translation(-h, 0, 0);
  34179. },
  34180. enumerable: true,
  34181. configurable: true
  34182. });
  34183. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  34184. get: function () {
  34185. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  34191. get: function () {
  34192. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  34193. },
  34194. enumerable: true,
  34195. configurable: true
  34196. });
  34197. VRCameraMetrics.GetDefault = function () {
  34198. var result = new VRCameraMetrics();
  34199. result.hResolution = 1280;
  34200. result.vResolution = 800;
  34201. result.hScreenSize = 0.149759993;
  34202. result.vScreenSize = 0.0935999975;
  34203. result.vScreenCenter = 0.0467999987,
  34204. result.eyeToScreenDistance = 0.0410000011;
  34205. result.lensSeparationDistance = 0.0635000020;
  34206. result.interpupillaryDistance = 0.0640000030;
  34207. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  34208. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  34209. result.postProcessScaleFactor = 1.714605507808412;
  34210. result.lensCenterOffset = 0.151976421;
  34211. return result;
  34212. };
  34213. return VRCameraMetrics;
  34214. })();
  34215. BABYLON.VRCameraMetrics = VRCameraMetrics;
  34216. })(BABYLON || (BABYLON = {}));
  34217. var BABYLON;
  34218. (function (BABYLON) {
  34219. var VRDeviceOrientationFreeCamera = (function (_super) {
  34220. __extends(VRDeviceOrientationFreeCamera, _super);
  34221. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  34222. if (compensateDistortion === void 0) { compensateDistortion = true; }
  34223. _super.call(this, name, position, scene);
  34224. this._alpha = 0;
  34225. this._beta = 0;
  34226. this._gamma = 0;
  34227. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  34228. metrics.compensateDistortion = compensateDistortion;
  34229. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  34230. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  34231. }
  34232. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  34233. this._alpha = +evt.alpha | 0;
  34234. this._beta = +evt.beta | 0;
  34235. this._gamma = +evt.gamma | 0;
  34236. if (this._gamma < 0) {
  34237. this._gamma = 90 + this._gamma;
  34238. }
  34239. else {
  34240. // Incline it in the correct angle.
  34241. this._gamma = 270 - this._gamma;
  34242. }
  34243. this.rotation.x = this._gamma / 180.0 * Math.PI;
  34244. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  34245. this.rotation.z = this._beta / 180.0 * Math.PI;
  34246. };
  34247. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34248. _super.prototype.attachControl.call(this, element, noPreventDefault);
  34249. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  34250. };
  34251. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  34252. _super.prototype.detachControl.call(this, element);
  34253. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  34254. };
  34255. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  34256. return "VRDeviceOrientationFreeCamera";
  34257. };
  34258. return VRDeviceOrientationFreeCamera;
  34259. })(BABYLON.FreeCamera);
  34260. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  34261. })(BABYLON || (BABYLON = {}));
  34262. var BABYLON;
  34263. (function (BABYLON) {
  34264. var WebVRFreeCamera = (function (_super) {
  34265. __extends(WebVRFreeCamera, _super);
  34266. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  34267. if (compensateDistortion === void 0) { compensateDistortion = true; }
  34268. _super.call(this, name, position, scene);
  34269. this._hmdDevice = null;
  34270. this._sensorDevice = null;
  34271. this._cacheState = null;
  34272. this._cacheQuaternion = new BABYLON.Quaternion();
  34273. this._cacheRotation = BABYLON.Vector3.Zero();
  34274. this._vrEnabled = false;
  34275. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  34276. metrics.compensateDistortion = compensateDistortion;
  34277. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  34278. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  34279. }
  34280. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  34281. var size = devices.length;
  34282. var i = 0;
  34283. // Reset devices.
  34284. this._sensorDevice = null;
  34285. this._hmdDevice = null;
  34286. // Search for a HmdDevice.
  34287. while (i < size && this._hmdDevice === null) {
  34288. if (devices[i] instanceof HMDVRDevice) {
  34289. this._hmdDevice = devices[i];
  34290. }
  34291. i++;
  34292. }
  34293. i = 0;
  34294. while (i < size && this._sensorDevice === null) {
  34295. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  34296. this._sensorDevice = devices[i];
  34297. }
  34298. i++;
  34299. }
  34300. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  34301. };
  34302. WebVRFreeCamera.prototype._checkInputs = function () {
  34303. if (this._vrEnabled) {
  34304. this._cacheState = this._sensorDevice.getState();
  34305. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  34306. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  34307. this.rotation.x = -this._cacheRotation.z;
  34308. this.rotation.y = -this._cacheRotation.y;
  34309. this.rotation.z = this._cacheRotation.x;
  34310. }
  34311. _super.prototype._checkInputs.call(this);
  34312. };
  34313. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34314. _super.prototype.attachControl.call(this, element, noPreventDefault);
  34315. if (navigator.getVRDevices) {
  34316. navigator.getVRDevices().then(this._getWebVRDevices);
  34317. }
  34318. else if (navigator.mozGetVRDevices) {
  34319. navigator.mozGetVRDevices(this._getWebVRDevices);
  34320. }
  34321. };
  34322. WebVRFreeCamera.prototype.detachControl = function (element) {
  34323. _super.prototype.detachControl.call(this, element);
  34324. this._vrEnabled = false;
  34325. };
  34326. WebVRFreeCamera.prototype.getTypeName = function () {
  34327. return "WebVRFreeCamera";
  34328. };
  34329. return WebVRFreeCamera;
  34330. })(BABYLON.FreeCamera);
  34331. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  34332. })(BABYLON || (BABYLON = {}));
  34333. var BABYLON;
  34334. (function (BABYLON) {
  34335. // Standard optimizations
  34336. var SceneOptimization = (function () {
  34337. function SceneOptimization(priority) {
  34338. if (priority === void 0) { priority = 0; }
  34339. this.priority = priority;
  34340. this.apply = function (scene) {
  34341. return true; // Return true if everything that can be done was applied
  34342. };
  34343. }
  34344. return SceneOptimization;
  34345. })();
  34346. BABYLON.SceneOptimization = SceneOptimization;
  34347. var TextureOptimization = (function (_super) {
  34348. __extends(TextureOptimization, _super);
  34349. function TextureOptimization(priority, maximumSize) {
  34350. var _this = this;
  34351. if (priority === void 0) { priority = 0; }
  34352. if (maximumSize === void 0) { maximumSize = 1024; }
  34353. _super.call(this, priority);
  34354. this.priority = priority;
  34355. this.maximumSize = maximumSize;
  34356. this.apply = function (scene) {
  34357. var allDone = true;
  34358. for (var index = 0; index < scene.textures.length; index++) {
  34359. var texture = scene.textures[index];
  34360. if (!texture.canRescale) {
  34361. continue;
  34362. }
  34363. var currentSize = texture.getSize();
  34364. var maxDimension = Math.max(currentSize.width, currentSize.height);
  34365. if (maxDimension > _this.maximumSize) {
  34366. texture.scale(0.5);
  34367. allDone = false;
  34368. }
  34369. }
  34370. return allDone;
  34371. };
  34372. }
  34373. return TextureOptimization;
  34374. })(SceneOptimization);
  34375. BABYLON.TextureOptimization = TextureOptimization;
  34376. var HardwareScalingOptimization = (function (_super) {
  34377. __extends(HardwareScalingOptimization, _super);
  34378. function HardwareScalingOptimization(priority, maximumScale) {
  34379. var _this = this;
  34380. if (priority === void 0) { priority = 0; }
  34381. if (maximumScale === void 0) { maximumScale = 2; }
  34382. _super.call(this, priority);
  34383. this.priority = priority;
  34384. this.maximumScale = maximumScale;
  34385. this._currentScale = 1;
  34386. this.apply = function (scene) {
  34387. _this._currentScale++;
  34388. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  34389. return _this._currentScale >= _this.maximumScale;
  34390. };
  34391. }
  34392. return HardwareScalingOptimization;
  34393. })(SceneOptimization);
  34394. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  34395. var ShadowsOptimization = (function (_super) {
  34396. __extends(ShadowsOptimization, _super);
  34397. function ShadowsOptimization() {
  34398. _super.apply(this, arguments);
  34399. this.apply = function (scene) {
  34400. scene.shadowsEnabled = false;
  34401. return true;
  34402. };
  34403. }
  34404. return ShadowsOptimization;
  34405. })(SceneOptimization);
  34406. BABYLON.ShadowsOptimization = ShadowsOptimization;
  34407. var PostProcessesOptimization = (function (_super) {
  34408. __extends(PostProcessesOptimization, _super);
  34409. function PostProcessesOptimization() {
  34410. _super.apply(this, arguments);
  34411. this.apply = function (scene) {
  34412. scene.postProcessesEnabled = false;
  34413. return true;
  34414. };
  34415. }
  34416. return PostProcessesOptimization;
  34417. })(SceneOptimization);
  34418. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  34419. var LensFlaresOptimization = (function (_super) {
  34420. __extends(LensFlaresOptimization, _super);
  34421. function LensFlaresOptimization() {
  34422. _super.apply(this, arguments);
  34423. this.apply = function (scene) {
  34424. scene.lensFlaresEnabled = false;
  34425. return true;
  34426. };
  34427. }
  34428. return LensFlaresOptimization;
  34429. })(SceneOptimization);
  34430. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  34431. var ParticlesOptimization = (function (_super) {
  34432. __extends(ParticlesOptimization, _super);
  34433. function ParticlesOptimization() {
  34434. _super.apply(this, arguments);
  34435. this.apply = function (scene) {
  34436. scene.particlesEnabled = false;
  34437. return true;
  34438. };
  34439. }
  34440. return ParticlesOptimization;
  34441. })(SceneOptimization);
  34442. BABYLON.ParticlesOptimization = ParticlesOptimization;
  34443. var RenderTargetsOptimization = (function (_super) {
  34444. __extends(RenderTargetsOptimization, _super);
  34445. function RenderTargetsOptimization() {
  34446. _super.apply(this, arguments);
  34447. this.apply = function (scene) {
  34448. scene.renderTargetsEnabled = false;
  34449. return true;
  34450. };
  34451. }
  34452. return RenderTargetsOptimization;
  34453. })(SceneOptimization);
  34454. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  34455. var MergeMeshesOptimization = (function (_super) {
  34456. __extends(MergeMeshesOptimization, _super);
  34457. function MergeMeshesOptimization() {
  34458. var _this = this;
  34459. _super.apply(this, arguments);
  34460. this._canBeMerged = function (abstractMesh) {
  34461. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  34462. return false;
  34463. }
  34464. var mesh = abstractMesh;
  34465. if (!mesh.isVisible || !mesh.isEnabled()) {
  34466. return false;
  34467. }
  34468. if (mesh.instances.length > 0) {
  34469. return false;
  34470. }
  34471. if (mesh.skeleton || mesh.hasLODLevels) {
  34472. return false;
  34473. }
  34474. if (mesh.parent) {
  34475. return false;
  34476. }
  34477. return true;
  34478. };
  34479. this.apply = function (scene, updateSelectionTree) {
  34480. var globalPool = scene.meshes.slice(0);
  34481. var globalLength = globalPool.length;
  34482. for (var index = 0; index < globalLength; index++) {
  34483. var currentPool = new Array();
  34484. var current = globalPool[index];
  34485. // Checks
  34486. if (!_this._canBeMerged(current)) {
  34487. continue;
  34488. }
  34489. currentPool.push(current);
  34490. // Find compatible meshes
  34491. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  34492. var otherMesh = globalPool[subIndex];
  34493. if (!_this._canBeMerged(otherMesh)) {
  34494. continue;
  34495. }
  34496. if (otherMesh.material !== current.material) {
  34497. continue;
  34498. }
  34499. if (otherMesh.checkCollisions !== current.checkCollisions) {
  34500. continue;
  34501. }
  34502. currentPool.push(otherMesh);
  34503. globalLength--;
  34504. globalPool.splice(subIndex, 1);
  34505. subIndex--;
  34506. }
  34507. if (currentPool.length < 2) {
  34508. continue;
  34509. }
  34510. // Merge meshes
  34511. BABYLON.Mesh.MergeMeshes(currentPool);
  34512. }
  34513. if (updateSelectionTree != undefined) {
  34514. if (updateSelectionTree) {
  34515. scene.createOrUpdateSelectionOctree();
  34516. }
  34517. }
  34518. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  34519. scene.createOrUpdateSelectionOctree();
  34520. }
  34521. return true;
  34522. };
  34523. }
  34524. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  34525. get: function () {
  34526. return MergeMeshesOptimization._UpdateSelectionTree;
  34527. },
  34528. set: function (value) {
  34529. MergeMeshesOptimization._UpdateSelectionTree = value;
  34530. },
  34531. enumerable: true,
  34532. configurable: true
  34533. });
  34534. MergeMeshesOptimization._UpdateSelectionTree = false;
  34535. return MergeMeshesOptimization;
  34536. })(SceneOptimization);
  34537. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  34538. // Options
  34539. var SceneOptimizerOptions = (function () {
  34540. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  34541. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  34542. if (trackerDuration === void 0) { trackerDuration = 2000; }
  34543. this.targetFrameRate = targetFrameRate;
  34544. this.trackerDuration = trackerDuration;
  34545. this.optimizations = new Array();
  34546. }
  34547. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  34548. var result = new SceneOptimizerOptions(targetFrameRate);
  34549. var priority = 0;
  34550. result.optimizations.push(new MergeMeshesOptimization(priority));
  34551. result.optimizations.push(new ShadowsOptimization(priority));
  34552. result.optimizations.push(new LensFlaresOptimization(priority));
  34553. // Next priority
  34554. priority++;
  34555. result.optimizations.push(new PostProcessesOptimization(priority));
  34556. result.optimizations.push(new ParticlesOptimization(priority));
  34557. // Next priority
  34558. priority++;
  34559. result.optimizations.push(new TextureOptimization(priority, 1024));
  34560. return result;
  34561. };
  34562. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  34563. var result = new SceneOptimizerOptions(targetFrameRate);
  34564. var priority = 0;
  34565. result.optimizations.push(new MergeMeshesOptimization(priority));
  34566. result.optimizations.push(new ShadowsOptimization(priority));
  34567. result.optimizations.push(new LensFlaresOptimization(priority));
  34568. // Next priority
  34569. priority++;
  34570. result.optimizations.push(new PostProcessesOptimization(priority));
  34571. result.optimizations.push(new ParticlesOptimization(priority));
  34572. // Next priority
  34573. priority++;
  34574. result.optimizations.push(new TextureOptimization(priority, 512));
  34575. // Next priority
  34576. priority++;
  34577. result.optimizations.push(new RenderTargetsOptimization(priority));
  34578. // Next priority
  34579. priority++;
  34580. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  34581. return result;
  34582. };
  34583. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  34584. var result = new SceneOptimizerOptions(targetFrameRate);
  34585. var priority = 0;
  34586. result.optimizations.push(new MergeMeshesOptimization(priority));
  34587. result.optimizations.push(new ShadowsOptimization(priority));
  34588. result.optimizations.push(new LensFlaresOptimization(priority));
  34589. // Next priority
  34590. priority++;
  34591. result.optimizations.push(new PostProcessesOptimization(priority));
  34592. result.optimizations.push(new ParticlesOptimization(priority));
  34593. // Next priority
  34594. priority++;
  34595. result.optimizations.push(new TextureOptimization(priority, 256));
  34596. // Next priority
  34597. priority++;
  34598. result.optimizations.push(new RenderTargetsOptimization(priority));
  34599. // Next priority
  34600. priority++;
  34601. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34602. return result;
  34603. };
  34604. return SceneOptimizerOptions;
  34605. })();
  34606. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34607. // Scene optimizer tool
  34608. var SceneOptimizer = (function () {
  34609. function SceneOptimizer() {
  34610. }
  34611. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34612. // TODO: add an epsilon
  34613. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34614. if (onSuccess) {
  34615. onSuccess();
  34616. }
  34617. return;
  34618. }
  34619. // Apply current level of optimizations
  34620. var allDone = true;
  34621. var noOptimizationApplied = true;
  34622. for (var index = 0; index < options.optimizations.length; index++) {
  34623. var optimization = options.optimizations[index];
  34624. if (optimization.priority === currentPriorityLevel) {
  34625. noOptimizationApplied = false;
  34626. allDone = allDone && optimization.apply(scene);
  34627. }
  34628. }
  34629. // If no optimization was applied, this is a failure :(
  34630. if (noOptimizationApplied) {
  34631. if (onFailure) {
  34632. onFailure();
  34633. }
  34634. return;
  34635. }
  34636. // If all optimizations were done, move to next level
  34637. if (allDone) {
  34638. currentPriorityLevel++;
  34639. }
  34640. // Let's the system running for a specific amount of time before checking FPS
  34641. scene.executeWhenReady(function () {
  34642. setTimeout(function () {
  34643. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34644. }, options.trackerDuration);
  34645. });
  34646. };
  34647. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34648. if (!options) {
  34649. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34650. }
  34651. // Let's the system running for a specific amount of time before checking FPS
  34652. scene.executeWhenReady(function () {
  34653. setTimeout(function () {
  34654. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34655. }, options.trackerDuration);
  34656. });
  34657. };
  34658. return SceneOptimizer;
  34659. })();
  34660. BABYLON.SceneOptimizer = SceneOptimizer;
  34661. })(BABYLON || (BABYLON = {}));
  34662. var BABYLON;
  34663. (function (BABYLON) {
  34664. var Internals;
  34665. (function (Internals) {
  34666. var MeshLODLevel = (function () {
  34667. function MeshLODLevel(distance, mesh) {
  34668. this.distance = distance;
  34669. this.mesh = mesh;
  34670. }
  34671. return MeshLODLevel;
  34672. })();
  34673. Internals.MeshLODLevel = MeshLODLevel;
  34674. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34675. })(BABYLON || (BABYLON = {}));
  34676. var BABYLON;
  34677. (function (BABYLON) {
  34678. var RawTexture = (function (_super) {
  34679. __extends(RawTexture, _super);
  34680. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34682. if (invertY === void 0) { invertY = false; }
  34683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34684. _super.call(this, null, scene, !generateMipMaps, invertY);
  34685. this.format = format;
  34686. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34687. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34688. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34689. }
  34690. RawTexture.prototype.update = function (data) {
  34691. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34692. };
  34693. // Statics
  34694. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34695. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34696. if (invertY === void 0) { invertY = false; }
  34697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34698. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34699. };
  34700. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34701. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34702. if (invertY === void 0) { invertY = false; }
  34703. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34704. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34705. };
  34706. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34707. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34708. if (invertY === void 0) { invertY = false; }
  34709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34710. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34711. };
  34712. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34713. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34714. if (invertY === void 0) { invertY = false; }
  34715. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34716. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34717. };
  34718. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34719. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34720. if (invertY === void 0) { invertY = false; }
  34721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34722. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34723. };
  34724. return RawTexture;
  34725. })(BABYLON.Texture);
  34726. BABYLON.RawTexture = RawTexture;
  34727. })(BABYLON || (BABYLON = {}));
  34728. var BABYLON;
  34729. (function (BABYLON) {
  34730. var IndexedVector2 = (function (_super) {
  34731. __extends(IndexedVector2, _super);
  34732. function IndexedVector2(original, index) {
  34733. _super.call(this, original.x, original.y);
  34734. this.index = index;
  34735. }
  34736. return IndexedVector2;
  34737. })(BABYLON.Vector2);
  34738. var PolygonPoints = (function () {
  34739. function PolygonPoints() {
  34740. this.elements = new Array();
  34741. }
  34742. PolygonPoints.prototype.add = function (originalPoints) {
  34743. var _this = this;
  34744. var result = new Array();
  34745. originalPoints.forEach(function (point) {
  34746. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34747. var newPoint = new IndexedVector2(point, _this.elements.length);
  34748. result.push(newPoint);
  34749. _this.elements.push(newPoint);
  34750. }
  34751. });
  34752. return result;
  34753. };
  34754. PolygonPoints.prototype.computeBounds = function () {
  34755. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34756. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34757. this.elements.forEach(function (point) {
  34758. // x
  34759. if (point.x < lmin.x) {
  34760. lmin.x = point.x;
  34761. }
  34762. else if (point.x > lmax.x) {
  34763. lmax.x = point.x;
  34764. }
  34765. // y
  34766. if (point.y < lmin.y) {
  34767. lmin.y = point.y;
  34768. }
  34769. else if (point.y > lmax.y) {
  34770. lmax.y = point.y;
  34771. }
  34772. });
  34773. return {
  34774. min: lmin,
  34775. max: lmax,
  34776. width: lmax.x - lmin.x,
  34777. height: lmax.y - lmin.y
  34778. };
  34779. };
  34780. return PolygonPoints;
  34781. })();
  34782. var Polygon = (function () {
  34783. function Polygon() {
  34784. }
  34785. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34786. return [
  34787. new BABYLON.Vector2(xmin, ymin),
  34788. new BABYLON.Vector2(xmax, ymin),
  34789. new BABYLON.Vector2(xmax, ymax),
  34790. new BABYLON.Vector2(xmin, ymax)
  34791. ];
  34792. };
  34793. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34794. if (cx === void 0) { cx = 0; }
  34795. if (cy === void 0) { cy = 0; }
  34796. if (numberOfSides === void 0) { numberOfSides = 32; }
  34797. var result = new Array();
  34798. var angle = 0;
  34799. var increment = (Math.PI * 2) / numberOfSides;
  34800. for (var i = 0; i < numberOfSides; i++) {
  34801. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34802. angle -= increment;
  34803. }
  34804. return result;
  34805. };
  34806. Polygon.Parse = function (input) {
  34807. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34808. var i, result = [];
  34809. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34810. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34811. }
  34812. return result;
  34813. };
  34814. Polygon.StartingAt = function (x, y) {
  34815. return BABYLON.Path2.StartingAt(x, y);
  34816. };
  34817. return Polygon;
  34818. })();
  34819. BABYLON.Polygon = Polygon;
  34820. var PolygonMeshBuilder = (function () {
  34821. function PolygonMeshBuilder(name, contours, scene) {
  34822. this._points = new PolygonPoints();
  34823. this._outlinepoints = new PolygonPoints();
  34824. this._holes = [];
  34825. if (!("poly2tri" in window)) {
  34826. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34827. }
  34828. this._name = name;
  34829. this._scene = scene;
  34830. var points;
  34831. if (contours instanceof BABYLON.Path2) {
  34832. points = contours.getPoints();
  34833. }
  34834. else {
  34835. points = contours;
  34836. }
  34837. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34838. this._outlinepoints.add(points);
  34839. }
  34840. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34841. this._swctx.addHole(this._points.add(hole));
  34842. var holepoints = new PolygonPoints();
  34843. holepoints.add(hole);
  34844. this._holes.push(holepoints);
  34845. return this;
  34846. };
  34847. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34848. var _this = this;
  34849. if (updatable === void 0) { updatable = false; }
  34850. var result = new BABYLON.Mesh(this._name, this._scene);
  34851. var normals = [];
  34852. var positions = [];
  34853. var uvs = [];
  34854. var bounds = this._points.computeBounds();
  34855. this._points.elements.forEach(function (p) {
  34856. normals.push(0, 1.0, 0);
  34857. positions.push(p.x, 0, p.y);
  34858. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34859. });
  34860. var indices = [];
  34861. this._swctx.triangulate();
  34862. this._swctx.getTriangles().forEach(function (triangle) {
  34863. triangle.getPoints().forEach(function (point) {
  34864. indices.push(point.index);
  34865. });
  34866. });
  34867. if (depth > 0) {
  34868. var positionscount = (positions.length / 3); //get the current pointcount
  34869. this._points.elements.forEach(function (p) {
  34870. normals.push(0, -1.0, 0);
  34871. positions.push(p.x, -depth, p.y);
  34872. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34873. });
  34874. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34875. var p2;
  34876. var poscounter = 0;
  34877. this._swctx.getTriangles().forEach(function (triangle) {
  34878. triangle.getPoints().forEach(function (point) {
  34879. switch (poscounter) {
  34880. case 0:
  34881. p1 = point;
  34882. break;
  34883. case 1:
  34884. p2 = point;
  34885. break;
  34886. case 2:
  34887. indices.push(point.index + positionscount);
  34888. indices.push(p2.index + positionscount);
  34889. indices.push(p1.index + positionscount);
  34890. poscounter = -1;
  34891. break;
  34892. }
  34893. poscounter++;
  34894. //indices.push((<IndexedVector2>point).index + positionscount);
  34895. });
  34896. });
  34897. //Add the sides
  34898. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34899. this._holes.forEach(function (hole) {
  34900. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34901. });
  34902. }
  34903. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34904. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34905. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34906. result.setIndices(indices);
  34907. return result;
  34908. };
  34909. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34910. var StartIndex = positions.length / 3;
  34911. var ulength = 0;
  34912. for (var i = 0; i < points.elements.length; i++) {
  34913. var p = points.elements[i];
  34914. var p1;
  34915. if ((i + 1) > points.elements.length - 1) {
  34916. p1 = points.elements[0];
  34917. }
  34918. else {
  34919. p1 = points.elements[i + 1];
  34920. }
  34921. positions.push(p.x, 0, p.y);
  34922. positions.push(p.x, -depth, p.y);
  34923. positions.push(p1.x, 0, p1.y);
  34924. positions.push(p1.x, -depth, p1.y);
  34925. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34926. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34927. var v3 = v2.subtract(v1);
  34928. var v4 = new BABYLON.Vector3(0, 1, 0);
  34929. var vn = BABYLON.Vector3.Cross(v3, v4);
  34930. vn = vn.normalize();
  34931. uvs.push(ulength / bounds.width, 0);
  34932. uvs.push(ulength / bounds.width, 1);
  34933. ulength += v3.length();
  34934. uvs.push((ulength / bounds.width), 0);
  34935. uvs.push((ulength / bounds.width), 1);
  34936. if (!flip) {
  34937. normals.push(-vn.x, -vn.y, -vn.z);
  34938. normals.push(-vn.x, -vn.y, -vn.z);
  34939. normals.push(-vn.x, -vn.y, -vn.z);
  34940. normals.push(-vn.x, -vn.y, -vn.z);
  34941. indices.push(StartIndex);
  34942. indices.push(StartIndex + 1);
  34943. indices.push(StartIndex + 2);
  34944. indices.push(StartIndex + 1);
  34945. indices.push(StartIndex + 3);
  34946. indices.push(StartIndex + 2);
  34947. }
  34948. else {
  34949. normals.push(vn.x, vn.y, vn.z);
  34950. normals.push(vn.x, vn.y, vn.z);
  34951. normals.push(vn.x, vn.y, vn.z);
  34952. normals.push(vn.x, vn.y, vn.z);
  34953. indices.push(StartIndex);
  34954. indices.push(StartIndex + 2);
  34955. indices.push(StartIndex + 1);
  34956. indices.push(StartIndex + 1);
  34957. indices.push(StartIndex + 2);
  34958. indices.push(StartIndex + 3);
  34959. }
  34960. StartIndex += 4;
  34961. }
  34962. ;
  34963. };
  34964. return PolygonMeshBuilder;
  34965. })();
  34966. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34967. })(BABYLON || (BABYLON = {}));
  34968. var BABYLON;
  34969. (function (BABYLON) {
  34970. var Octree = (function () {
  34971. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34972. if (maxDepth === void 0) { maxDepth = 2; }
  34973. this.maxDepth = maxDepth;
  34974. this.dynamicContent = new Array();
  34975. this._maxBlockCapacity = maxBlockCapacity || 64;
  34976. this._selectionContent = new BABYLON.SmartArray(1024);
  34977. this._creationFunc = creationFunc;
  34978. }
  34979. // Methods
  34980. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34981. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34982. };
  34983. Octree.prototype.addMesh = function (entry) {
  34984. for (var index = 0; index < this.blocks.length; index++) {
  34985. var block = this.blocks[index];
  34986. block.addEntry(entry);
  34987. }
  34988. };
  34989. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34990. this._selectionContent.reset();
  34991. for (var index = 0; index < this.blocks.length; index++) {
  34992. var block = this.blocks[index];
  34993. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34994. }
  34995. if (allowDuplicate) {
  34996. this._selectionContent.concat(this.dynamicContent);
  34997. }
  34998. else {
  34999. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  35000. }
  35001. return this._selectionContent;
  35002. };
  35003. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  35004. this._selectionContent.reset();
  35005. for (var index = 0; index < this.blocks.length; index++) {
  35006. var block = this.blocks[index];
  35007. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  35008. }
  35009. if (allowDuplicate) {
  35010. this._selectionContent.concat(this.dynamicContent);
  35011. }
  35012. else {
  35013. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  35014. }
  35015. return this._selectionContent;
  35016. };
  35017. Octree.prototype.intersectsRay = function (ray) {
  35018. this._selectionContent.reset();
  35019. for (var index = 0; index < this.blocks.length; index++) {
  35020. var block = this.blocks[index];
  35021. block.intersectsRay(ray, this._selectionContent);
  35022. }
  35023. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  35024. return this._selectionContent;
  35025. };
  35026. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  35027. target.blocks = new Array();
  35028. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  35029. // Segmenting space
  35030. for (var x = 0; x < 2; x++) {
  35031. for (var y = 0; y < 2; y++) {
  35032. for (var z = 0; z < 2; z++) {
  35033. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  35034. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  35035. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  35036. block.addEntries(entries);
  35037. target.blocks.push(block);
  35038. }
  35039. }
  35040. }
  35041. };
  35042. Octree.CreationFuncForMeshes = function (entry, block) {
  35043. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  35044. block.entries.push(entry);
  35045. }
  35046. };
  35047. Octree.CreationFuncForSubMeshes = function (entry, block) {
  35048. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  35049. block.entries.push(entry);
  35050. }
  35051. };
  35052. return Octree;
  35053. })();
  35054. BABYLON.Octree = Octree;
  35055. })(BABYLON || (BABYLON = {}));
  35056. var BABYLON;
  35057. (function (BABYLON) {
  35058. var OctreeBlock = (function () {
  35059. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  35060. this.entries = new Array();
  35061. this._boundingVectors = new Array();
  35062. this._capacity = capacity;
  35063. this._depth = depth;
  35064. this._maxDepth = maxDepth;
  35065. this._creationFunc = creationFunc;
  35066. this._minPoint = minPoint;
  35067. this._maxPoint = maxPoint;
  35068. this._boundingVectors.push(minPoint.clone());
  35069. this._boundingVectors.push(maxPoint.clone());
  35070. this._boundingVectors.push(minPoint.clone());
  35071. this._boundingVectors[2].x = maxPoint.x;
  35072. this._boundingVectors.push(minPoint.clone());
  35073. this._boundingVectors[3].y = maxPoint.y;
  35074. this._boundingVectors.push(minPoint.clone());
  35075. this._boundingVectors[4].z = maxPoint.z;
  35076. this._boundingVectors.push(maxPoint.clone());
  35077. this._boundingVectors[5].z = minPoint.z;
  35078. this._boundingVectors.push(maxPoint.clone());
  35079. this._boundingVectors[6].x = minPoint.x;
  35080. this._boundingVectors.push(maxPoint.clone());
  35081. this._boundingVectors[7].y = minPoint.y;
  35082. }
  35083. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  35084. // Property
  35085. get: function () {
  35086. return this._capacity;
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  35092. get: function () {
  35093. return this._minPoint;
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  35099. get: function () {
  35100. return this._maxPoint;
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. // Methods
  35106. OctreeBlock.prototype.addEntry = function (entry) {
  35107. if (this.blocks) {
  35108. for (var index = 0; index < this.blocks.length; index++) {
  35109. var block = this.blocks[index];
  35110. block.addEntry(entry);
  35111. }
  35112. return;
  35113. }
  35114. this._creationFunc(entry, this);
  35115. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  35116. this.createInnerBlocks();
  35117. }
  35118. };
  35119. OctreeBlock.prototype.addEntries = function (entries) {
  35120. for (var index = 0; index < entries.length; index++) {
  35121. var mesh = entries[index];
  35122. this.addEntry(mesh);
  35123. }
  35124. };
  35125. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  35126. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  35127. if (this.blocks) {
  35128. for (var index = 0; index < this.blocks.length; index++) {
  35129. var block = this.blocks[index];
  35130. block.select(frustumPlanes, selection, allowDuplicate);
  35131. }
  35132. return;
  35133. }
  35134. if (allowDuplicate) {
  35135. selection.concat(this.entries);
  35136. }
  35137. else {
  35138. selection.concatWithNoDuplicate(this.entries);
  35139. }
  35140. }
  35141. };
  35142. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  35143. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  35144. if (this.blocks) {
  35145. for (var index = 0; index < this.blocks.length; index++) {
  35146. var block = this.blocks[index];
  35147. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  35148. }
  35149. return;
  35150. }
  35151. if (allowDuplicate) {
  35152. selection.concat(this.entries);
  35153. }
  35154. else {
  35155. selection.concatWithNoDuplicate(this.entries);
  35156. }
  35157. }
  35158. };
  35159. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  35160. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  35161. if (this.blocks) {
  35162. for (var index = 0; index < this.blocks.length; index++) {
  35163. var block = this.blocks[index];
  35164. block.intersectsRay(ray, selection);
  35165. }
  35166. return;
  35167. }
  35168. selection.concatWithNoDuplicate(this.entries);
  35169. }
  35170. };
  35171. OctreeBlock.prototype.createInnerBlocks = function () {
  35172. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  35173. };
  35174. return OctreeBlock;
  35175. })();
  35176. BABYLON.OctreeBlock = OctreeBlock;
  35177. })(BABYLON || (BABYLON = {}));
  35178. var BABYLON;
  35179. (function (BABYLON) {
  35180. var BlurPostProcess = (function (_super) {
  35181. __extends(BlurPostProcess, _super);
  35182. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  35183. var _this = this;
  35184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35185. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  35186. this.direction = direction;
  35187. this.blurWidth = blurWidth;
  35188. this.onApply = function (effect) {
  35189. effect.setFloat2("screenSize", _this.width, _this.height);
  35190. effect.setVector2("direction", _this.direction);
  35191. effect.setFloat("blurWidth", _this.blurWidth);
  35192. };
  35193. }
  35194. return BlurPostProcess;
  35195. })(BABYLON.PostProcess);
  35196. BABYLON.BlurPostProcess = BlurPostProcess;
  35197. })(BABYLON || (BABYLON = {}));
  35198. var BABYLON;
  35199. (function (BABYLON) {
  35200. var RefractionPostProcess = (function (_super) {
  35201. __extends(RefractionPostProcess, _super);
  35202. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  35203. var _this = this;
  35204. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  35205. this.color = color;
  35206. this.depth = depth;
  35207. this.colorLevel = colorLevel;
  35208. this.onActivate = function (cam) {
  35209. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  35210. };
  35211. this.onApply = function (effect) {
  35212. effect.setColor3("baseColor", _this.color);
  35213. effect.setFloat("depth", _this.depth);
  35214. effect.setFloat("colorLevel", _this.colorLevel);
  35215. effect.setTexture("refractionSampler", _this._refRexture);
  35216. };
  35217. }
  35218. // Methods
  35219. RefractionPostProcess.prototype.dispose = function (camera) {
  35220. if (this._refRexture) {
  35221. this._refRexture.dispose();
  35222. }
  35223. _super.prototype.dispose.call(this, camera);
  35224. };
  35225. return RefractionPostProcess;
  35226. })(BABYLON.PostProcess);
  35227. BABYLON.RefractionPostProcess = RefractionPostProcess;
  35228. })(BABYLON || (BABYLON = {}));
  35229. var BABYLON;
  35230. (function (BABYLON) {
  35231. var BlackAndWhitePostProcess = (function (_super) {
  35232. __extends(BlackAndWhitePostProcess, _super);
  35233. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35234. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  35235. }
  35236. return BlackAndWhitePostProcess;
  35237. })(BABYLON.PostProcess);
  35238. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  35239. })(BABYLON || (BABYLON = {}));
  35240. var BABYLON;
  35241. (function (BABYLON) {
  35242. var ConvolutionPostProcess = (function (_super) {
  35243. __extends(ConvolutionPostProcess, _super);
  35244. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  35245. var _this = this;
  35246. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  35247. this.kernel = kernel;
  35248. this.onApply = function (effect) {
  35249. effect.setFloat2("screenSize", _this.width, _this.height);
  35250. effect.setArray("kernel", _this.kernel);
  35251. };
  35252. }
  35253. // Statics
  35254. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  35255. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  35256. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  35257. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  35258. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  35259. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  35260. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  35261. return ConvolutionPostProcess;
  35262. })(BABYLON.PostProcess);
  35263. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  35264. })(BABYLON || (BABYLON = {}));
  35265. var BABYLON;
  35266. (function (BABYLON) {
  35267. var FilterPostProcess = (function (_super) {
  35268. __extends(FilterPostProcess, _super);
  35269. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  35270. var _this = this;
  35271. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  35272. this.kernelMatrix = kernelMatrix;
  35273. this.onApply = function (effect) {
  35274. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  35275. };
  35276. }
  35277. return FilterPostProcess;
  35278. })(BABYLON.PostProcess);
  35279. BABYLON.FilterPostProcess = FilterPostProcess;
  35280. })(BABYLON || (BABYLON = {}));
  35281. var BABYLON;
  35282. (function (BABYLON) {
  35283. var FxaaPostProcess = (function (_super) {
  35284. __extends(FxaaPostProcess, _super);
  35285. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35286. var _this = this;
  35287. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  35288. this.onSizeChanged = function () {
  35289. _this.texelWidth = 1.0 / _this.width;
  35290. _this.texelHeight = 1.0 / _this.height;
  35291. };
  35292. this.onApply = function (effect) {
  35293. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  35294. };
  35295. }
  35296. return FxaaPostProcess;
  35297. })(BABYLON.PostProcess);
  35298. BABYLON.FxaaPostProcess = FxaaPostProcess;
  35299. })(BABYLON || (BABYLON = {}));
  35300. var BABYLON;
  35301. (function (BABYLON) {
  35302. var StereoscopicInterlacePostProcess = (function (_super) {
  35303. __extends(StereoscopicInterlacePostProcess, _super);
  35304. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  35305. var _this = this;
  35306. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  35307. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  35308. this.onSizeChanged = function () {
  35309. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  35310. };
  35311. this.onApply = function (effect) {
  35312. effect.setTextureFromPostProcess("camASampler", postProcessA);
  35313. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  35314. };
  35315. }
  35316. return StereoscopicInterlacePostProcess;
  35317. })(BABYLON.PostProcess);
  35318. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  35319. })(BABYLON || (BABYLON = {}));
  35320. var BABYLON;
  35321. (function (BABYLON) {
  35322. var LensFlare = (function () {
  35323. function LensFlare(size, position, color, imgUrl, system) {
  35324. this.size = size;
  35325. this.position = position;
  35326. this.dispose = function () {
  35327. if (this.texture) {
  35328. this.texture.dispose();
  35329. }
  35330. // Remove from scene
  35331. var index = this._system.lensFlares.indexOf(this);
  35332. this._system.lensFlares.splice(index, 1);
  35333. };
  35334. this.color = color || new BABYLON.Color3(1, 1, 1);
  35335. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  35336. this._system = system;
  35337. system.lensFlares.push(this);
  35338. }
  35339. return LensFlare;
  35340. })();
  35341. BABYLON.LensFlare = LensFlare;
  35342. })(BABYLON || (BABYLON = {}));
  35343. var BABYLON;
  35344. (function (BABYLON) {
  35345. var LensFlareSystem = (function () {
  35346. function LensFlareSystem(name, emitter, scene) {
  35347. this.name = name;
  35348. this.lensFlares = new Array();
  35349. this.borderLimit = 300;
  35350. this.layerMask = 0x0FFFFFFF;
  35351. this._vertexDeclaration = [2];
  35352. this._vertexStrideSize = 2 * 4;
  35353. this._isEnabled = true;
  35354. this._scene = scene;
  35355. this._emitter = emitter;
  35356. scene.lensFlareSystems.push(this);
  35357. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  35358. // VBO
  35359. var vertices = [];
  35360. vertices.push(1, 1);
  35361. vertices.push(-1, 1);
  35362. vertices.push(-1, -1);
  35363. vertices.push(1, -1);
  35364. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  35365. // Indices
  35366. var indices = [];
  35367. indices.push(0);
  35368. indices.push(1);
  35369. indices.push(2);
  35370. indices.push(0);
  35371. indices.push(2);
  35372. indices.push(3);
  35373. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  35374. // Effects
  35375. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  35376. }
  35377. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  35378. get: function () {
  35379. return this._isEnabled;
  35380. },
  35381. set: function (value) {
  35382. this._isEnabled = value;
  35383. },
  35384. enumerable: true,
  35385. configurable: true
  35386. });
  35387. LensFlareSystem.prototype.getScene = function () {
  35388. return this._scene;
  35389. };
  35390. LensFlareSystem.prototype.getEmitter = function () {
  35391. return this._emitter;
  35392. };
  35393. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  35394. this._emitter = newEmitter;
  35395. };
  35396. LensFlareSystem.prototype.getEmitterPosition = function () {
  35397. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  35398. };
  35399. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  35400. var position = this.getEmitterPosition();
  35401. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  35402. this._positionX = position.x;
  35403. this._positionY = position.y;
  35404. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  35405. if (position.z > 0) {
  35406. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  35407. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  35408. return true;
  35409. }
  35410. }
  35411. return false;
  35412. };
  35413. LensFlareSystem.prototype._isVisible = function () {
  35414. if (!this._isEnabled) {
  35415. return false;
  35416. }
  35417. var emitterPosition = this.getEmitterPosition();
  35418. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  35419. var distance = direction.length();
  35420. direction.normalize();
  35421. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  35422. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  35423. return !pickInfo.hit || pickInfo.distance > distance;
  35424. };
  35425. LensFlareSystem.prototype.render = function () {
  35426. if (!this._effect.isReady())
  35427. return false;
  35428. var engine = this._scene.getEngine();
  35429. var viewport = this._scene.activeCamera.viewport;
  35430. var globalViewport = viewport.toScreenGlobal(engine);
  35431. // Position
  35432. if (!this.computeEffectivePosition(globalViewport)) {
  35433. return false;
  35434. }
  35435. // Visibility
  35436. if (!this._isVisible()) {
  35437. return false;
  35438. }
  35439. // Intensity
  35440. var awayX;
  35441. var awayY;
  35442. if (this._positionX < this.borderLimit + globalViewport.x) {
  35443. awayX = this.borderLimit + globalViewport.x - this._positionX;
  35444. }
  35445. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  35446. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  35447. }
  35448. else {
  35449. awayX = 0;
  35450. }
  35451. if (this._positionY < this.borderLimit + globalViewport.y) {
  35452. awayY = this.borderLimit + globalViewport.y - this._positionY;
  35453. }
  35454. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  35455. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  35456. }
  35457. else {
  35458. awayY = 0;
  35459. }
  35460. var away = (awayX > awayY) ? awayX : awayY;
  35461. if (away > this.borderLimit) {
  35462. away = this.borderLimit;
  35463. }
  35464. var intensity = 1.0 - (away / this.borderLimit);
  35465. if (intensity < 0) {
  35466. return false;
  35467. }
  35468. if (intensity > 1.0) {
  35469. intensity = 1.0;
  35470. }
  35471. // Position
  35472. var centerX = globalViewport.x + globalViewport.width / 2;
  35473. var centerY = globalViewport.y + globalViewport.height / 2;
  35474. var distX = centerX - this._positionX;
  35475. var distY = centerY - this._positionY;
  35476. // Effects
  35477. engine.enableEffect(this._effect);
  35478. engine.setState(false);
  35479. engine.setDepthBuffer(false);
  35480. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35481. // VBOs
  35482. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  35483. // Flares
  35484. for (var index = 0; index < this.lensFlares.length; index++) {
  35485. var flare = this.lensFlares[index];
  35486. var x = centerX - (distX * flare.position);
  35487. var y = centerY - (distY * flare.position);
  35488. var cw = flare.size;
  35489. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  35490. var cx = 2 * (x / globalViewport.width) - 1.0;
  35491. var cy = 1.0 - 2 * (y / globalViewport.height);
  35492. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  35493. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  35494. // Texture
  35495. this._effect.setTexture("textureSampler", flare.texture);
  35496. // Color
  35497. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  35498. // Draw order
  35499. engine.draw(true, 0, 6);
  35500. }
  35501. engine.setDepthBuffer(true);
  35502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35503. return true;
  35504. };
  35505. LensFlareSystem.prototype.dispose = function () {
  35506. if (this._vertexBuffer) {
  35507. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  35508. this._vertexBuffer = null;
  35509. }
  35510. if (this._indexBuffer) {
  35511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35512. this._indexBuffer = null;
  35513. }
  35514. while (this.lensFlares.length) {
  35515. this.lensFlares[0].dispose();
  35516. }
  35517. // Remove from scene
  35518. var index = this._scene.lensFlareSystems.indexOf(this);
  35519. this._scene.lensFlareSystems.splice(index, 1);
  35520. };
  35521. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  35522. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  35523. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  35524. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  35525. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  35526. var parsedFlare = parsedLensFlareSystem.flares[index];
  35527. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  35528. }
  35529. return lensFlareSystem;
  35530. };
  35531. LensFlareSystem.prototype.serialize = function () {
  35532. var serializationObject = {};
  35533. serializationObject.emitterId = this.getEmitter().id;
  35534. serializationObject.borderLimit = this.borderLimit;
  35535. serializationObject.flares = [];
  35536. for (var index = 0; index < this.lensFlares.length; index++) {
  35537. var flare = this.lensFlares[index];
  35538. serializationObject.flares.push({
  35539. size: flare.size,
  35540. position: flare.position,
  35541. color: flare.color.asArray(),
  35542. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  35543. });
  35544. }
  35545. return serializationObject;
  35546. };
  35547. return LensFlareSystem;
  35548. })();
  35549. BABYLON.LensFlareSystem = LensFlareSystem;
  35550. })(BABYLON || (BABYLON = {}));
  35551. var BABYLON;
  35552. (function (BABYLON) {
  35553. // We're mainly based on the logic defined into the FreeCamera code
  35554. var DeviceOrientationCamera = (function (_super) {
  35555. __extends(DeviceOrientationCamera, _super);
  35556. function DeviceOrientationCamera(name, position, scene) {
  35557. var _this = this;
  35558. _super.call(this, name, position, scene);
  35559. this._offsetX = null;
  35560. this._offsetY = null;
  35561. this._orientationGamma = 0;
  35562. this._orientationBeta = 0;
  35563. this._initialOrientationGamma = 0;
  35564. this._initialOrientationBeta = 0;
  35565. this.angularSensibility = 10000.0;
  35566. this.moveSensibility = 50.0;
  35567. window.addEventListener("resize", function () {
  35568. _this._initialOrientationGamma = null;
  35569. }, false);
  35570. }
  35571. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35572. var _this = this;
  35573. if (this._attachedCanvas) {
  35574. return;
  35575. }
  35576. this._attachedCanvas = canvas;
  35577. if (!this._orientationChanged) {
  35578. this._orientationChanged = function (evt) {
  35579. if (!_this._initialOrientationGamma) {
  35580. _this._initialOrientationGamma = evt.gamma;
  35581. _this._initialOrientationBeta = evt.beta;
  35582. }
  35583. _this._orientationGamma = evt.gamma;
  35584. _this._orientationBeta = evt.beta;
  35585. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  35586. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  35587. };
  35588. }
  35589. window.addEventListener("deviceorientation", this._orientationChanged);
  35590. };
  35591. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  35592. if (this._attachedCanvas !== canvas) {
  35593. return;
  35594. }
  35595. window.removeEventListener("deviceorientation", this._orientationChanged);
  35596. this._attachedCanvas = null;
  35597. this._orientationGamma = 0;
  35598. this._orientationBeta = 0;
  35599. this._initialOrientationGamma = 0;
  35600. this._initialOrientationBeta = 0;
  35601. };
  35602. DeviceOrientationCamera.prototype._checkInputs = function () {
  35603. if (!this._offsetX) {
  35604. return;
  35605. }
  35606. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35607. var speed = this._computeLocalCameraSpeed();
  35608. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35609. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35610. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35611. _super.prototype._checkInputs.call(this);
  35612. };
  35613. DeviceOrientationCamera.prototype.getTypeName = function () {
  35614. return "DeviceOrientationCamera";
  35615. };
  35616. __decorate([
  35617. BABYLON.serialize()
  35618. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35622. return DeviceOrientationCamera;
  35623. })(BABYLON.FreeCamera);
  35624. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35625. })(BABYLON || (BABYLON = {}));
  35626. var BABYLON;
  35627. (function (BABYLON) {
  35628. // We're mainly based on the logic defined into the FreeCamera code
  35629. var UniversalCamera = (function (_super) {
  35630. __extends(UniversalCamera, _super);
  35631. function UniversalCamera(name, position, scene) {
  35632. var _this = this;
  35633. _super.call(this, name, position, scene);
  35634. this.gamepadAngularSensibility = 200;
  35635. this.gamepadMoveSensibility = 40;
  35636. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  35637. }
  35638. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  35639. // Only the first gamepad can control the camera
  35640. if (gamepad.index === 0) {
  35641. this.gamepad = gamepad;
  35642. }
  35643. };
  35644. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35645. _super.prototype.attachControl.call(this, canvas, false);
  35646. };
  35647. UniversalCamera.prototype.detachControl = function (canvas) {
  35648. _super.prototype.detachControl.call(this, canvas);
  35649. };
  35650. UniversalCamera.prototype._checkInputs = function () {
  35651. if (this.gamepad) {
  35652. var LSValues = this.gamepad.leftStick;
  35653. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  35654. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  35655. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  35656. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  35657. var RSValues = this.gamepad.rightStick;
  35658. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  35659. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  35660. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  35661. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  35662. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  35663. var speed = this._computeLocalCameraSpeed() * 50.0;
  35664. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  35665. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  35666. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  35667. }
  35668. _super.prototype._checkInputs.call(this);
  35669. };
  35670. UniversalCamera.prototype.dispose = function () {
  35671. this._gamepads.dispose();
  35672. _super.prototype.dispose.call(this);
  35673. };
  35674. UniversalCamera.prototype.getTypeName = function () {
  35675. return "UniversalCamera";
  35676. };
  35677. __decorate([
  35678. BABYLON.serialize()
  35679. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  35680. __decorate([
  35681. BABYLON.serialize()
  35682. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  35683. return UniversalCamera;
  35684. })(BABYLON.TouchCamera);
  35685. BABYLON.UniversalCamera = UniversalCamera;
  35686. })(BABYLON || (BABYLON = {}));
  35687. var BABYLON;
  35688. (function (BABYLON) {
  35689. var Gamepads = (function () {
  35690. function Gamepads(ongamedpadconnected) {
  35691. var _this = this;
  35692. this.babylonGamepads = [];
  35693. this.oneGamepadConnected = false;
  35694. this.isMonitoring = false;
  35695. this.gamepadEventSupported = 'GamepadEvent' in window;
  35696. this.gamepadSupportAvailable = (navigator.getGamepads ||
  35697. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  35698. this._callbackGamepadConnected = ongamedpadconnected;
  35699. if (this.gamepadSupportAvailable) {
  35700. // Checking if the gamepad connected event is supported (like in Firefox)
  35701. if (this.gamepadEventSupported) {
  35702. window.addEventListener('gamepadconnected', function (evt) {
  35703. _this._onGamepadConnected(evt);
  35704. }, false);
  35705. window.addEventListener('gamepaddisconnected', function (evt) {
  35706. _this._onGamepadDisconnected(evt);
  35707. }, false);
  35708. }
  35709. else {
  35710. this._startMonitoringGamepads();
  35711. }
  35712. }
  35713. }
  35714. Gamepads.prototype.dispose = function () {
  35715. if (Gamepads.gamepadDOMInfo) {
  35716. document.body.removeChild(Gamepads.gamepadDOMInfo);
  35717. }
  35718. };
  35719. Gamepads.prototype._onGamepadConnected = function (evt) {
  35720. var newGamepad = this._addNewGamepad(evt.gamepad);
  35721. if (this._callbackGamepadConnected)
  35722. this._callbackGamepadConnected(newGamepad);
  35723. this._startMonitoringGamepads();
  35724. };
  35725. Gamepads.prototype._addNewGamepad = function (gamepad) {
  35726. if (!this.oneGamepadConnected) {
  35727. this.oneGamepadConnected = true;
  35728. if (Gamepads.gamepadDOMInfo) {
  35729. document.body.removeChild(Gamepads.gamepadDOMInfo);
  35730. Gamepads.gamepadDOMInfo = null;
  35731. }
  35732. }
  35733. var newGamepad;
  35734. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  35735. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  35736. }
  35737. else {
  35738. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  35739. }
  35740. this.babylonGamepads.push(newGamepad);
  35741. return newGamepad;
  35742. };
  35743. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  35744. // Remove the gamepad from the list of gamepads to monitor.
  35745. for (var i in this.babylonGamepads) {
  35746. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  35747. this.babylonGamepads.splice(+i, 1);
  35748. break;
  35749. }
  35750. }
  35751. // If no gamepads are left, stop the polling loop.
  35752. if (this.babylonGamepads.length == 0) {
  35753. this._stopMonitoringGamepads();
  35754. }
  35755. };
  35756. Gamepads.prototype._startMonitoringGamepads = function () {
  35757. if (!this.isMonitoring) {
  35758. this.isMonitoring = true;
  35759. this._checkGamepadsStatus();
  35760. }
  35761. };
  35762. Gamepads.prototype._stopMonitoringGamepads = function () {
  35763. this.isMonitoring = false;
  35764. };
  35765. Gamepads.prototype._checkGamepadsStatus = function () {
  35766. var _this = this;
  35767. // updating gamepad objects
  35768. this._updateGamepadObjects();
  35769. for (var i in this.babylonGamepads) {
  35770. this.babylonGamepads[i].update();
  35771. }
  35772. if (this.isMonitoring) {
  35773. if (window.requestAnimationFrame) {
  35774. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35775. }
  35776. else if (window.mozRequestAnimationFrame) {
  35777. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35778. }
  35779. else if (window.webkitRequestAnimationFrame) {
  35780. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  35781. }
  35782. }
  35783. };
  35784. // This function is called only on Chrome, which does not yet support
  35785. // connection/disconnection events, but requires you to monitor
  35786. // an array for changes.
  35787. Gamepads.prototype._updateGamepadObjects = function () {
  35788. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  35789. for (var i = 0; i < gamepads.length; i++) {
  35790. if (gamepads[i]) {
  35791. if (!(gamepads[i].index in this.babylonGamepads)) {
  35792. var newGamepad = this._addNewGamepad(gamepads[i]);
  35793. if (this._callbackGamepadConnected) {
  35794. this._callbackGamepadConnected(newGamepad);
  35795. }
  35796. }
  35797. else {
  35798. this.babylonGamepads[i].browserGamepad = gamepads[i];
  35799. }
  35800. }
  35801. }
  35802. };
  35803. return Gamepads;
  35804. })();
  35805. BABYLON.Gamepads = Gamepads;
  35806. var StickValues = (function () {
  35807. function StickValues(x, y) {
  35808. this.x = x;
  35809. this.y = y;
  35810. }
  35811. return StickValues;
  35812. })();
  35813. BABYLON.StickValues = StickValues;
  35814. var Gamepad = (function () {
  35815. function Gamepad(id, index, browserGamepad) {
  35816. this.id = id;
  35817. this.index = index;
  35818. this.browserGamepad = browserGamepad;
  35819. if (this.browserGamepad.axes.length >= 2) {
  35820. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  35821. }
  35822. if (this.browserGamepad.axes.length >= 4) {
  35823. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  35824. }
  35825. }
  35826. Gamepad.prototype.onleftstickchanged = function (callback) {
  35827. this._onleftstickchanged = callback;
  35828. };
  35829. Gamepad.prototype.onrightstickchanged = function (callback) {
  35830. this._onrightstickchanged = callback;
  35831. };
  35832. Object.defineProperty(Gamepad.prototype, "leftStick", {
  35833. get: function () {
  35834. return this._leftStick;
  35835. },
  35836. set: function (newValues) {
  35837. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  35838. this._onleftstickchanged(newValues);
  35839. }
  35840. this._leftStick = newValues;
  35841. },
  35842. enumerable: true,
  35843. configurable: true
  35844. });
  35845. Object.defineProperty(Gamepad.prototype, "rightStick", {
  35846. get: function () {
  35847. return this._rightStick;
  35848. },
  35849. set: function (newValues) {
  35850. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  35851. this._onrightstickchanged(newValues);
  35852. }
  35853. this._rightStick = newValues;
  35854. },
  35855. enumerable: true,
  35856. configurable: true
  35857. });
  35858. Gamepad.prototype.update = function () {
  35859. if (this._leftStick) {
  35860. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  35861. }
  35862. if (this._rightStick) {
  35863. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  35864. }
  35865. };
  35866. return Gamepad;
  35867. })();
  35868. BABYLON.Gamepad = Gamepad;
  35869. var GenericPad = (function (_super) {
  35870. __extends(GenericPad, _super);
  35871. function GenericPad(id, index, gamepad) {
  35872. _super.call(this, id, index, gamepad);
  35873. this.id = id;
  35874. this.index = index;
  35875. this.gamepad = gamepad;
  35876. this._buttons = new Array(gamepad.buttons.length);
  35877. }
  35878. GenericPad.prototype.onbuttondown = function (callback) {
  35879. this._onbuttondown = callback;
  35880. };
  35881. GenericPad.prototype.onbuttonup = function (callback) {
  35882. this._onbuttonup = callback;
  35883. };
  35884. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  35885. if (newValue !== currentValue) {
  35886. if (this._onbuttondown && newValue === 1) {
  35887. this._onbuttondown(buttonIndex);
  35888. }
  35889. if (this._onbuttonup && newValue === 0) {
  35890. this._onbuttonup(buttonIndex);
  35891. }
  35892. }
  35893. return newValue;
  35894. };
  35895. GenericPad.prototype.update = function () {
  35896. _super.prototype.update.call(this);
  35897. for (var index = 0; index < this._buttons.length; index++) {
  35898. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  35899. }
  35900. };
  35901. return GenericPad;
  35902. })(Gamepad);
  35903. BABYLON.GenericPad = GenericPad;
  35904. (function (Xbox360Button) {
  35905. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  35906. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  35907. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  35908. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  35909. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  35910. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  35911. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  35912. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  35913. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  35914. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  35915. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  35916. var Xbox360Button = BABYLON.Xbox360Button;
  35917. (function (Xbox360Dpad) {
  35918. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  35919. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  35920. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  35921. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  35922. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  35923. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  35924. var Xbox360Pad = (function (_super) {
  35925. __extends(Xbox360Pad, _super);
  35926. function Xbox360Pad() {
  35927. _super.apply(this, arguments);
  35928. this._leftTrigger = 0;
  35929. this._rightTrigger = 0;
  35930. this._buttonA = 0;
  35931. this._buttonB = 0;
  35932. this._buttonX = 0;
  35933. this._buttonY = 0;
  35934. this._buttonBack = 0;
  35935. this._buttonStart = 0;
  35936. this._buttonLB = 0;
  35937. this._buttonRB = 0;
  35938. this._buttonLeftStick = 0;
  35939. this._buttonRightStick = 0;
  35940. this._dPadUp = 0;
  35941. this._dPadDown = 0;
  35942. this._dPadLeft = 0;
  35943. this._dPadRight = 0;
  35944. }
  35945. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  35946. this._onlefttriggerchanged = callback;
  35947. };
  35948. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  35949. this._onrighttriggerchanged = callback;
  35950. };
  35951. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  35952. get: function () {
  35953. return this._leftTrigger;
  35954. },
  35955. set: function (newValue) {
  35956. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  35957. this._onlefttriggerchanged(newValue);
  35958. }
  35959. this._leftTrigger = newValue;
  35960. },
  35961. enumerable: true,
  35962. configurable: true
  35963. });
  35964. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  35965. get: function () {
  35966. return this._rightTrigger;
  35967. },
  35968. set: function (newValue) {
  35969. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  35970. this._onrighttriggerchanged(newValue);
  35971. }
  35972. this._rightTrigger = newValue;
  35973. },
  35974. enumerable: true,
  35975. configurable: true
  35976. });
  35977. Xbox360Pad.prototype.onbuttondown = function (callback) {
  35978. this._onbuttondown = callback;
  35979. };
  35980. Xbox360Pad.prototype.onbuttonup = function (callback) {
  35981. this._onbuttonup = callback;
  35982. };
  35983. Xbox360Pad.prototype.ondpaddown = function (callback) {
  35984. this._ondpaddown = callback;
  35985. };
  35986. Xbox360Pad.prototype.ondpadup = function (callback) {
  35987. this._ondpadup = callback;
  35988. };
  35989. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  35990. if (newValue !== currentValue) {
  35991. if (this._onbuttondown && newValue === 1) {
  35992. this._onbuttondown(buttonType);
  35993. }
  35994. if (this._onbuttonup && newValue === 0) {
  35995. this._onbuttonup(buttonType);
  35996. }
  35997. }
  35998. return newValue;
  35999. };
  36000. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  36001. if (newValue !== currentValue) {
  36002. if (this._ondpaddown && newValue === 1) {
  36003. this._ondpaddown(buttonType);
  36004. }
  36005. if (this._ondpadup && newValue === 0) {
  36006. this._ondpadup(buttonType);
  36007. }
  36008. }
  36009. return newValue;
  36010. };
  36011. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  36012. get: function () {
  36013. return this._buttonA;
  36014. },
  36015. set: function (value) {
  36016. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  36017. },
  36018. enumerable: true,
  36019. configurable: true
  36020. });
  36021. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  36022. get: function () {
  36023. return this._buttonB;
  36024. },
  36025. set: function (value) {
  36026. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  36027. },
  36028. enumerable: true,
  36029. configurable: true
  36030. });
  36031. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  36032. get: function () {
  36033. return this._buttonX;
  36034. },
  36035. set: function (value) {
  36036. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  36037. },
  36038. enumerable: true,
  36039. configurable: true
  36040. });
  36041. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  36042. get: function () {
  36043. return this._buttonY;
  36044. },
  36045. set: function (value) {
  36046. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  36047. },
  36048. enumerable: true,
  36049. configurable: true
  36050. });
  36051. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  36052. get: function () {
  36053. return this._buttonStart;
  36054. },
  36055. set: function (value) {
  36056. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  36057. },
  36058. enumerable: true,
  36059. configurable: true
  36060. });
  36061. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  36062. get: function () {
  36063. return this._buttonBack;
  36064. },
  36065. set: function (value) {
  36066. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  36067. },
  36068. enumerable: true,
  36069. configurable: true
  36070. });
  36071. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  36072. get: function () {
  36073. return this._buttonLB;
  36074. },
  36075. set: function (value) {
  36076. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  36077. },
  36078. enumerable: true,
  36079. configurable: true
  36080. });
  36081. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  36082. get: function () {
  36083. return this._buttonRB;
  36084. },
  36085. set: function (value) {
  36086. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  36087. },
  36088. enumerable: true,
  36089. configurable: true
  36090. });
  36091. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  36092. get: function () {
  36093. return this._buttonLeftStick;
  36094. },
  36095. set: function (value) {
  36096. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  36097. },
  36098. enumerable: true,
  36099. configurable: true
  36100. });
  36101. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  36102. get: function () {
  36103. return this._buttonRightStick;
  36104. },
  36105. set: function (value) {
  36106. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  36107. },
  36108. enumerable: true,
  36109. configurable: true
  36110. });
  36111. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  36112. get: function () {
  36113. return this._dPadUp;
  36114. },
  36115. set: function (value) {
  36116. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  36117. },
  36118. enumerable: true,
  36119. configurable: true
  36120. });
  36121. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  36122. get: function () {
  36123. return this._dPadDown;
  36124. },
  36125. set: function (value) {
  36126. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  36127. },
  36128. enumerable: true,
  36129. configurable: true
  36130. });
  36131. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  36132. get: function () {
  36133. return this._dPadLeft;
  36134. },
  36135. set: function (value) {
  36136. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  36137. },
  36138. enumerable: true,
  36139. configurable: true
  36140. });
  36141. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  36142. get: function () {
  36143. return this._dPadRight;
  36144. },
  36145. set: function (value) {
  36146. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Xbox360Pad.prototype.update = function () {
  36152. _super.prototype.update.call(this);
  36153. this.buttonA = this.browserGamepad.buttons[0].value;
  36154. this.buttonB = this.browserGamepad.buttons[1].value;
  36155. this.buttonX = this.browserGamepad.buttons[2].value;
  36156. this.buttonY = this.browserGamepad.buttons[3].value;
  36157. this.buttonLB = this.browserGamepad.buttons[4].value;
  36158. this.buttonRB = this.browserGamepad.buttons[5].value;
  36159. this.leftTrigger = this.browserGamepad.buttons[6].value;
  36160. this.rightTrigger = this.browserGamepad.buttons[7].value;
  36161. this.buttonBack = this.browserGamepad.buttons[8].value;
  36162. this.buttonStart = this.browserGamepad.buttons[9].value;
  36163. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  36164. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  36165. this.dPadUp = this.browserGamepad.buttons[12].value;
  36166. this.dPadDown = this.browserGamepad.buttons[13].value;
  36167. this.dPadLeft = this.browserGamepad.buttons[14].value;
  36168. this.dPadRight = this.browserGamepad.buttons[15].value;
  36169. };
  36170. return Xbox360Pad;
  36171. })(Gamepad);
  36172. BABYLON.Xbox360Pad = Xbox360Pad;
  36173. })(BABYLON || (BABYLON = {}));
  36174. var BABYLON;
  36175. (function (BABYLON) {
  36176. // We're mainly based on the logic defined into the FreeCamera code
  36177. var GamepadCamera = (function (_super) {
  36178. __extends(GamepadCamera, _super);
  36179. function GamepadCamera(name, position, scene) {
  36180. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  36181. _super.call(this, name, position, scene);
  36182. }
  36183. GamepadCamera.prototype.getTypeName = function () {
  36184. return "GamepadCamera";
  36185. };
  36186. return GamepadCamera;
  36187. })(BABYLON.UniversalCamera);
  36188. BABYLON.GamepadCamera = GamepadCamera;
  36189. })(BABYLON || (BABYLON = {}));
  36190. var BABYLON;
  36191. (function (BABYLON) {
  36192. var Analyser = (function () {
  36193. function Analyser(scene) {
  36194. this.SMOOTHING = 0.75;
  36195. this.FFT_SIZE = 512;
  36196. this.BARGRAPHAMPLITUDE = 256;
  36197. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  36198. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  36199. this._scene = scene;
  36200. this._audioEngine = BABYLON.Engine.audioEngine;
  36201. if (this._audioEngine.canUseWebAudio) {
  36202. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  36203. this._webAudioAnalyser.minDecibels = -140;
  36204. this._webAudioAnalyser.maxDecibels = 0;
  36205. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  36206. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  36207. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  36208. }
  36209. }
  36210. Analyser.prototype.getFrequencyBinCount = function () {
  36211. if (this._audioEngine.canUseWebAudio) {
  36212. return this._webAudioAnalyser.frequencyBinCount;
  36213. }
  36214. else {
  36215. return 0;
  36216. }
  36217. };
  36218. Analyser.prototype.getByteFrequencyData = function () {
  36219. if (this._audioEngine.canUseWebAudio) {
  36220. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  36221. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  36222. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  36223. }
  36224. return this._byteFreqs;
  36225. };
  36226. Analyser.prototype.getByteTimeDomainData = function () {
  36227. if (this._audioEngine.canUseWebAudio) {
  36228. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  36229. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  36230. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  36231. }
  36232. return this._byteTime;
  36233. };
  36234. Analyser.prototype.getFloatFrequencyData = function () {
  36235. if (this._audioEngine.canUseWebAudio) {
  36236. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  36237. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  36238. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  36239. }
  36240. return this._floatFreqs;
  36241. };
  36242. Analyser.prototype.drawDebugCanvas = function () {
  36243. var _this = this;
  36244. if (this._audioEngine.canUseWebAudio) {
  36245. if (!this._debugCanvas) {
  36246. this._debugCanvas = document.createElement("canvas");
  36247. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  36248. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  36249. this._debugCanvas.style.position = "absolute";
  36250. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  36251. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  36252. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  36253. document.body.appendChild(this._debugCanvas);
  36254. this._registerFunc = function () {
  36255. _this.drawDebugCanvas();
  36256. };
  36257. this._scene.registerBeforeRender(this._registerFunc);
  36258. }
  36259. if (this._registerFunc) {
  36260. var workingArray = this.getByteFrequencyData();
  36261. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  36262. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  36263. // Draw the frequency domain chart.
  36264. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  36265. var value = workingArray[i];
  36266. var percent = value / this.BARGRAPHAMPLITUDE;
  36267. var height = this.DEBUGCANVASSIZE.height * percent;
  36268. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  36269. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  36270. var hue = i / this.getFrequencyBinCount() * 360;
  36271. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  36272. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  36273. }
  36274. }
  36275. }
  36276. };
  36277. Analyser.prototype.stopDebugCanvas = function () {
  36278. if (this._debugCanvas) {
  36279. this._scene.unregisterBeforeRender(this._registerFunc);
  36280. this._registerFunc = null;
  36281. document.body.removeChild(this._debugCanvas);
  36282. this._debugCanvas = null;
  36283. this._debugCanvasContext = null;
  36284. }
  36285. };
  36286. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  36287. if (this._audioEngine.canUseWebAudio) {
  36288. inputAudioNode.connect(this._webAudioAnalyser);
  36289. this._webAudioAnalyser.connect(outputAudioNode);
  36290. }
  36291. };
  36292. Analyser.prototype.dispose = function () {
  36293. if (this._audioEngine.canUseWebAudio) {
  36294. this._webAudioAnalyser.disconnect();
  36295. }
  36296. };
  36297. return Analyser;
  36298. })();
  36299. BABYLON.Analyser = Analyser;
  36300. })(BABYLON || (BABYLON = {}));
  36301. var BABYLON;
  36302. (function (BABYLON) {
  36303. var DepthRenderer = (function () {
  36304. function DepthRenderer(scene, type) {
  36305. var _this = this;
  36306. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  36307. this._viewMatrix = BABYLON.Matrix.Zero();
  36308. this._projectionMatrix = BABYLON.Matrix.Zero();
  36309. this._transformMatrix = BABYLON.Matrix.Zero();
  36310. this._worldViewProjection = BABYLON.Matrix.Zero();
  36311. this._scene = scene;
  36312. var engine = scene.getEngine();
  36313. // Render target
  36314. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  36315. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36316. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36317. this._depthMap.refreshRate = 1;
  36318. this._depthMap.renderParticles = false;
  36319. this._depthMap.renderList = null;
  36320. // set default depth value to 1.0 (far away)
  36321. this._depthMap.onClear = function (engine) {
  36322. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  36323. };
  36324. // Custom render function
  36325. var renderSubMesh = function (subMesh) {
  36326. var mesh = subMesh.getRenderingMesh();
  36327. var scene = _this._scene;
  36328. var engine = scene.getEngine();
  36329. // Culling
  36330. engine.setState(subMesh.getMaterial().backFaceCulling);
  36331. // Managing instances
  36332. var batch = mesh._getInstancesRenderList(subMesh._id);
  36333. if (batch.mustReturn) {
  36334. return;
  36335. }
  36336. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36337. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36338. engine.enableEffect(_this._effect);
  36339. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  36340. var material = subMesh.getMaterial();
  36341. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  36342. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  36343. // Alpha test
  36344. if (material && material.needAlphaTesting()) {
  36345. var alphaTexture = material.getAlphaTestTexture();
  36346. _this._effect.setTexture("diffuseSampler", alphaTexture);
  36347. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36348. }
  36349. // Bones
  36350. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36351. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36352. }
  36353. // Draw
  36354. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  36355. }
  36356. };
  36357. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  36358. var index;
  36359. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36360. renderSubMesh(opaqueSubMeshes.data[index]);
  36361. }
  36362. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36363. renderSubMesh(alphaTestSubMeshes.data[index]);
  36364. }
  36365. };
  36366. }
  36367. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  36368. var defines = [];
  36369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36370. var mesh = subMesh.getMesh();
  36371. var scene = mesh.getScene();
  36372. var material = subMesh.getMaterial();
  36373. // Alpha test
  36374. if (material && material.needAlphaTesting()) {
  36375. defines.push("#define ALPHATEST");
  36376. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36377. attribs.push(BABYLON.VertexBuffer.UVKind);
  36378. defines.push("#define UV1");
  36379. }
  36380. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36381. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36382. defines.push("#define UV2");
  36383. }
  36384. }
  36385. // Bones
  36386. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36389. if (mesh.numBoneInfluencers > 4) {
  36390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36392. }
  36393. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36394. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36395. }
  36396. else {
  36397. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36398. }
  36399. // Instances
  36400. if (useInstances) {
  36401. defines.push("#define INSTANCES");
  36402. attribs.push("world0");
  36403. attribs.push("world1");
  36404. attribs.push("world2");
  36405. attribs.push("world3");
  36406. }
  36407. // Get correct effect
  36408. var join = defines.join("\n");
  36409. if (this._cachedDefines !== join) {
  36410. this._cachedDefines = join;
  36411. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36412. }
  36413. return this._effect.isReady();
  36414. };
  36415. DepthRenderer.prototype.getDepthMap = function () {
  36416. return this._depthMap;
  36417. };
  36418. // Methods
  36419. DepthRenderer.prototype.dispose = function () {
  36420. this._depthMap.dispose();
  36421. };
  36422. return DepthRenderer;
  36423. })();
  36424. BABYLON.DepthRenderer = DepthRenderer;
  36425. })(BABYLON || (BABYLON = {}));
  36426. var BABYLON;
  36427. (function (BABYLON) {
  36428. var SSAORenderingPipeline = (function (_super) {
  36429. __extends(SSAORenderingPipeline, _super);
  36430. /**
  36431. * @constructor
  36432. * @param {string} name - The rendering pipeline name
  36433. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36434. * @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 }
  36435. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36436. */
  36437. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36438. var _this = this;
  36439. _super.call(this, scene.getEngine(), name);
  36440. // Members
  36441. /**
  36442. * The PassPostProcess id in the pipeline that contains the original scene color
  36443. * @type {string}
  36444. */
  36445. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36446. /**
  36447. * The SSAO PostProcess id in the pipeline
  36448. * @type {string}
  36449. */
  36450. this.SSAORenderEffect = "SSAORenderEffect";
  36451. /**
  36452. * The horizontal blur PostProcess id in the pipeline
  36453. * @type {string}
  36454. */
  36455. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36456. /**
  36457. * The vertical blur PostProcess id in the pipeline
  36458. * @type {string}
  36459. */
  36460. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36461. /**
  36462. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36463. * @type {string}
  36464. */
  36465. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36466. /**
  36467. * The output strength of the SSAO post-process. Default value is 1.0.
  36468. * @type {number}
  36469. */
  36470. this.totalStrength = 1.0;
  36471. /**
  36472. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36473. * @type {number}
  36474. */
  36475. this.radius = 0.0001;
  36476. /**
  36477. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36478. * Must not be equal to fallOff and superior to fallOff.
  36479. * Default value is 0.975
  36480. * @type {number}
  36481. */
  36482. this.area = 0.0075;
  36483. /**
  36484. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36485. * Must not be equal to area and inferior to area.
  36486. * Default value is 0.0
  36487. * @type {number}
  36488. */
  36489. this.fallOff = 0.000001;
  36490. /**
  36491. * The base color of the SSAO post-process
  36492. * The final result is "base + ssao" between [0, 1]
  36493. * @type {number}
  36494. */
  36495. this.base = 0.5;
  36496. this._firstUpdate = true;
  36497. this._scene = scene;
  36498. // Set up assets
  36499. this._createRandomTexture();
  36500. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36501. var ssaoRatio = ratio.ssaoRatio || ratio;
  36502. var combineRatio = ratio.combineRatio || ratio;
  36503. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36504. this._createSSAOPostProcess(ssaoRatio);
  36505. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36506. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36507. this._createSSAOCombinePostProcess(combineRatio);
  36508. // Set up pipeline
  36509. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36514. // Finish
  36515. scene.postProcessRenderPipelineManager.addPipeline(this);
  36516. if (cameras)
  36517. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36518. }
  36519. // Public Methods
  36520. /**
  36521. * Returns the horizontal blur PostProcess
  36522. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36523. */
  36524. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36525. return this._blurHPostProcess;
  36526. };
  36527. /**
  36528. * Returns the vertical blur PostProcess
  36529. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36530. */
  36531. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36532. return this._blurVPostProcess;
  36533. };
  36534. /**
  36535. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36536. */
  36537. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36538. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36539. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36540. this._originalColorPostProcess = undefined;
  36541. this._ssaoPostProcess = undefined;
  36542. this._blurHPostProcess = undefined;
  36543. this._blurVPostProcess = undefined;
  36544. this._ssaoCombinePostProcess = undefined;
  36545. this._randomTexture.dispose();
  36546. if (disableDepthRender)
  36547. this._scene.disableDepthRenderer();
  36548. };
  36549. // Private Methods
  36550. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36551. var _this = this;
  36552. var numSamples = 16;
  36553. var sampleSphere = [
  36554. 0.5381, 0.1856, -0.4319,
  36555. 0.1379, 0.2486, 0.4430,
  36556. 0.3371, 0.5679, -0.0057,
  36557. -0.6999, -0.0451, -0.0019,
  36558. 0.0689, -0.1598, -0.8547,
  36559. 0.0560, 0.0069, -0.1843,
  36560. -0.0146, 0.1402, 0.0762,
  36561. 0.0100, -0.1924, -0.0344,
  36562. -0.3577, -0.5301, -0.4358,
  36563. -0.3169, 0.1063, 0.0158,
  36564. 0.0103, -0.5869, 0.0046,
  36565. -0.0897, -0.4940, 0.3287,
  36566. 0.7119, -0.0154, -0.0918,
  36567. -0.0533, 0.0596, -0.5411,
  36568. 0.0352, -0.0631, 0.5460,
  36569. -0.4776, 0.2847, -0.0271
  36570. ];
  36571. var samplesFactor = 1.0 / numSamples;
  36572. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36573. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36574. "area", "fallOff", "base"
  36575. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36576. this._ssaoPostProcess.onApply = function (effect) {
  36577. if (_this._firstUpdate) {
  36578. effect.setArray3("sampleSphere", sampleSphere);
  36579. effect.setFloat("samplesFactor", samplesFactor);
  36580. effect.setFloat("randTextureTiles", 4.0);
  36581. _this._firstUpdate = false;
  36582. }
  36583. effect.setFloat("totalStrength", _this.totalStrength);
  36584. effect.setFloat("radius", _this.radius);
  36585. effect.setFloat("area", _this.area);
  36586. effect.setFloat("fallOff", _this.fallOff);
  36587. effect.setFloat("base", _this.base);
  36588. effect.setTexture("textureSampler", _this._depthTexture);
  36589. effect.setTexture("randomSampler", _this._randomTexture);
  36590. };
  36591. };
  36592. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36593. var _this = this;
  36594. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36595. this._ssaoCombinePostProcess.onApply = function (effect) {
  36596. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36597. };
  36598. };
  36599. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36600. var size = 512;
  36601. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36602. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36603. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36604. var context = this._randomTexture.getContext();
  36605. var rand = function (min, max) {
  36606. return Math.random() * (max - min) + min;
  36607. };
  36608. var randVector = BABYLON.Vector3.Zero();
  36609. for (var x = 0; x < size; x++) {
  36610. for (var y = 0; y < size; y++) {
  36611. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36612. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36613. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36614. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36615. context.fillRect(x, y, 1, 1);
  36616. }
  36617. }
  36618. this._randomTexture.update(false);
  36619. };
  36620. return SSAORenderingPipeline;
  36621. })(BABYLON.PostProcessRenderPipeline);
  36622. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36623. })(BABYLON || (BABYLON = {}));
  36624. var BABYLON;
  36625. (function (BABYLON) {
  36626. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36627. var VolumetricLightScatteringPostProcess = (function (_super) {
  36628. __extends(VolumetricLightScatteringPostProcess, _super);
  36629. /**
  36630. * @constructor
  36631. * @param {string} name - The post-process name
  36632. * @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)
  36633. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36634. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36635. * @param {number} samples - The post-process quality, default 100
  36636. * @param {number} samplingMode - The post-process filtering mode
  36637. * @param {BABYLON.Engine} engine - The babylon engine
  36638. * @param {boolean} reusable - If the post-process is reusable
  36639. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36640. */
  36641. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36642. var _this = this;
  36643. if (samples === void 0) { samples = 100; }
  36644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36645. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36646. this._screenCoordinates = BABYLON.Vector2.Zero();
  36647. /**
  36648. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36649. * @type {boolean}
  36650. */
  36651. this.useCustomMeshPosition = false;
  36652. /**
  36653. * If the post-process should inverse the light scattering direction
  36654. * @type {boolean}
  36655. */
  36656. this.invert = true;
  36657. /**
  36658. * Set to true to use the diffuseColor instead of the diffuseTexture
  36659. * @type {boolean}
  36660. */
  36661. this.useDiffuseColor = false;
  36662. /**
  36663. * Array containing the excluded meshes not rendered in the internal pass
  36664. */
  36665. this.excludedMeshes = new Array();
  36666. /**
  36667. * Controls the overall intensity of the post-process
  36668. * @type {number}
  36669. */
  36670. this.exposure = 0.3;
  36671. /**
  36672. * Dissipates each sample's contribution in range [0, 1]
  36673. * @type {number}
  36674. */
  36675. this.decay = 0.96815;
  36676. /**
  36677. * Controls the overall intensity of each sample
  36678. * @type {number}
  36679. */
  36680. this.weight = 0.58767;
  36681. /**
  36682. * Controls the density of each sample
  36683. * @type {number}
  36684. */
  36685. this.density = 0.926;
  36686. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36687. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  36688. // Configure mesh
  36689. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36690. // Configure
  36691. this._createPass(scene, ratio.passRatio || ratio);
  36692. this.onActivate = function (camera) {
  36693. if (!_this.isSupported) {
  36694. _this.dispose(camera);
  36695. }
  36696. _this.onActivate = null;
  36697. };
  36698. this.onApply = function (effect) {
  36699. _this._updateMeshScreenCoordinates(scene);
  36700. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36701. effect.setFloat("exposure", _this.exposure);
  36702. effect.setFloat("decay", _this.decay);
  36703. effect.setFloat("weight", _this.weight);
  36704. effect.setFloat("density", _this.density);
  36705. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36706. };
  36707. }
  36708. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36709. var mesh = subMesh.getMesh();
  36710. var defines = [];
  36711. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36712. var material = subMesh.getMaterial();
  36713. var needUV = false;
  36714. // Render this.mesh as default
  36715. if (mesh === this.mesh) {
  36716. if (this.useDiffuseColor) {
  36717. defines.push("#define DIFFUSE_COLOR_RENDER");
  36718. }
  36719. else if (material) {
  36720. if (material.diffuseTexture !== undefined) {
  36721. defines.push("#define BASIC_RENDER");
  36722. }
  36723. else {
  36724. defines.push("#define DIFFUSE_COLOR_RENDER");
  36725. }
  36726. }
  36727. defines.push("#define NEED_UV");
  36728. needUV = true;
  36729. }
  36730. // Alpha test
  36731. if (material) {
  36732. if (material.needAlphaTesting()) {
  36733. defines.push("#define ALPHATEST");
  36734. }
  36735. if (material.opacityTexture !== undefined) {
  36736. defines.push("#define OPACITY");
  36737. if (material.opacityTexture.getAlphaFromRGB) {
  36738. defines.push("#define OPACITYRGB");
  36739. }
  36740. if (!needUV) {
  36741. defines.push("#define NEED_UV");
  36742. }
  36743. }
  36744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36745. attribs.push(BABYLON.VertexBuffer.UVKind);
  36746. defines.push("#define UV1");
  36747. }
  36748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36750. defines.push("#define UV2");
  36751. }
  36752. }
  36753. // Bones
  36754. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36755. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36756. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36757. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36758. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36759. }
  36760. else {
  36761. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36762. }
  36763. // Instances
  36764. if (useInstances) {
  36765. defines.push("#define INSTANCES");
  36766. attribs.push("world0");
  36767. attribs.push("world1");
  36768. attribs.push("world2");
  36769. attribs.push("world3");
  36770. }
  36771. // Get correct effect
  36772. var join = defines.join("\n");
  36773. if (this._cachedDefines !== join) {
  36774. this._cachedDefines = join;
  36775. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36776. }
  36777. return this._volumetricLightScatteringPass.isReady();
  36778. };
  36779. /**
  36780. * Sets the new light position for light scattering effect
  36781. * @param {BABYLON.Vector3} The new custom light position
  36782. */
  36783. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36784. this._customMeshPosition = position;
  36785. };
  36786. /**
  36787. * Returns the light position for light scattering effect
  36788. * @return {BABYLON.Vector3} The custom light position
  36789. */
  36790. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36791. return this._customMeshPosition;
  36792. };
  36793. /**
  36794. * Disposes the internal assets and detaches the post-process from the camera
  36795. */
  36796. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36797. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36798. if (rttIndex !== -1) {
  36799. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36800. }
  36801. this._volumetricLightScatteringRTT.dispose();
  36802. _super.prototype.dispose.call(this, camera);
  36803. };
  36804. /**
  36805. * Returns the render target texture used by the post-process
  36806. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36807. */
  36808. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36809. return this._volumetricLightScatteringRTT;
  36810. };
  36811. // Private methods
  36812. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36813. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36814. return true;
  36815. }
  36816. return false;
  36817. };
  36818. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36819. var _this = this;
  36820. var engine = scene.getEngine();
  36821. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36822. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36823. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36824. this._volumetricLightScatteringRTT.renderList = null;
  36825. this._volumetricLightScatteringRTT.renderParticles = false;
  36826. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36827. // Custom render function for submeshes
  36828. var renderSubMesh = function (subMesh) {
  36829. var mesh = subMesh.getRenderingMesh();
  36830. if (_this._meshExcluded(mesh)) {
  36831. return;
  36832. }
  36833. var scene = mesh.getScene();
  36834. var engine = scene.getEngine();
  36835. // Culling
  36836. engine.setState(subMesh.getMaterial().backFaceCulling);
  36837. // Managing instances
  36838. var batch = mesh._getInstancesRenderList(subMesh._id);
  36839. if (batch.mustReturn) {
  36840. return;
  36841. }
  36842. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36843. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36844. engine.enableEffect(_this._volumetricLightScatteringPass);
  36845. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36846. var material = subMesh.getMaterial();
  36847. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36848. // Alpha test
  36849. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36850. var alphaTexture = material.getAlphaTestTexture();
  36851. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36852. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36853. }
  36854. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36855. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36856. if (alphaTexture) {
  36857. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36858. }
  36859. }
  36860. if (material.opacityTexture !== undefined) {
  36861. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36862. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36863. }
  36864. }
  36865. // Bones
  36866. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36867. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36868. }
  36869. // Draw
  36870. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36871. }
  36872. };
  36873. // Render target texture callbacks
  36874. var savedSceneClearColor;
  36875. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36876. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36877. savedSceneClearColor = scene.clearColor;
  36878. scene.clearColor = sceneClearColor;
  36879. };
  36880. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36881. scene.clearColor = savedSceneClearColor;
  36882. };
  36883. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36884. var engine = scene.getEngine();
  36885. var index;
  36886. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36887. renderSubMesh(opaqueSubMeshes.data[index]);
  36888. }
  36889. engine.setAlphaTesting(true);
  36890. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36891. renderSubMesh(alphaTestSubMeshes.data[index]);
  36892. }
  36893. engine.setAlphaTesting(false);
  36894. if (transparentSubMeshes.length) {
  36895. // Sort sub meshes
  36896. for (index = 0; index < transparentSubMeshes.length; index++) {
  36897. var submesh = transparentSubMeshes.data[index];
  36898. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36899. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36900. }
  36901. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36902. sortedArray.sort(function (a, b) {
  36903. // Alpha index first
  36904. if (a._alphaIndex > b._alphaIndex) {
  36905. return 1;
  36906. }
  36907. if (a._alphaIndex < b._alphaIndex) {
  36908. return -1;
  36909. }
  36910. // Then distance to camera
  36911. if (a._distanceToCamera < b._distanceToCamera) {
  36912. return 1;
  36913. }
  36914. if (a._distanceToCamera > b._distanceToCamera) {
  36915. return -1;
  36916. }
  36917. return 0;
  36918. });
  36919. // Render sub meshes
  36920. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36921. for (index = 0; index < sortedArray.length; index++) {
  36922. renderSubMesh(sortedArray[index]);
  36923. }
  36924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36925. }
  36926. };
  36927. };
  36928. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36929. var transform = scene.getTransformMatrix();
  36930. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36931. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36932. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36933. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36934. if (this.invert)
  36935. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36936. };
  36937. // Static methods
  36938. /**
  36939. * Creates a default mesh for the Volumeric Light Scattering post-process
  36940. * @param {string} The mesh name
  36941. * @param {BABYLON.Scene} The scene where to create the mesh
  36942. * @return {BABYLON.Mesh} the default mesh
  36943. */
  36944. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36945. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36946. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36947. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36948. return mesh;
  36949. };
  36950. return VolumetricLightScatteringPostProcess;
  36951. })(BABYLON.PostProcess);
  36952. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36953. })(BABYLON || (BABYLON = {}));
  36954. // BABYLON.JS Chromatic Aberration GLSL Shader
  36955. // Author: Olivier Guyot
  36956. // Separates very slightly R, G and B colors on the edges of the screen
  36957. // Inspired by Francois Tarlier & Martins Upitis
  36958. var BABYLON;
  36959. (function (BABYLON) {
  36960. var LensRenderingPipeline = (function (_super) {
  36961. __extends(LensRenderingPipeline, _super);
  36962. /**
  36963. * @constructor
  36964. *
  36965. * Effect parameters are as follow:
  36966. * {
  36967. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36968. * edge_blur: number; // from 0 to x (1 for realism)
  36969. * distortion: number; // from 0 to x (1 for realism)
  36970. * grain_amount: number; // from 0 to 1
  36971. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36972. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36973. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36974. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36975. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36976. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36977. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36978. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36979. * }
  36980. * Note: if an effect parameter is unset, effect is disabled
  36981. *
  36982. * @param {string} name - The rendering pipeline name
  36983. * @param {object} parameters - An object containing all parameters (see above)
  36984. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36985. * @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)
  36986. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36987. */
  36988. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36989. var _this = this;
  36990. if (ratio === void 0) { ratio = 1.0; }
  36991. _super.call(this, scene.getEngine(), name);
  36992. // Lens effects can be of the following:
  36993. // - chromatic aberration (slight shift of RGB colors)
  36994. // - blur on the edge of the lens
  36995. // - lens distortion
  36996. // - depth-of-field blur & highlights enhancing
  36997. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36998. // - grain effect (noise or custom texture)
  36999. // Two additional texture samplers are needed:
  37000. // - depth map (for depth-of-field)
  37001. // - grain texture
  37002. /**
  37003. * The chromatic aberration PostProcess id in the pipeline
  37004. * @type {string}
  37005. */
  37006. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  37007. /**
  37008. * The highlights enhancing PostProcess id in the pipeline
  37009. * @type {string}
  37010. */
  37011. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  37012. /**
  37013. * The depth-of-field PostProcess id in the pipeline
  37014. * @type {string}
  37015. */
  37016. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  37017. this._scene = scene;
  37018. // Fetch texture samplers
  37019. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  37020. if (parameters.grain_texture) {
  37021. this._grainTexture = parameters.grain_texture;
  37022. }
  37023. else {
  37024. this._createGrainTexture();
  37025. }
  37026. // save parameters
  37027. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  37028. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  37029. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  37030. this._distortion = parameters.distortion ? parameters.distortion : 0;
  37031. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  37032. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  37033. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  37034. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  37035. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  37036. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  37037. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  37038. // Create effects
  37039. this._createChromaticAberrationPostProcess(ratio);
  37040. this._createHighlightsPostProcess(ratio);
  37041. this._createDepthOfFieldPostProcess(ratio / 4);
  37042. // Set up pipeline
  37043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  37044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  37045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  37046. if (this._highlightsGain === -1) {
  37047. this._disableEffect(this.HighlightsEnhancingEffect, null);
  37048. }
  37049. // Finish
  37050. scene.postProcessRenderPipelineManager.addPipeline(this);
  37051. if (cameras) {
  37052. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37053. }
  37054. }
  37055. // public methods (self explanatory)
  37056. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  37057. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  37058. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  37059. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  37060. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  37061. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  37062. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  37063. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  37064. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  37065. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  37066. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  37067. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  37068. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  37069. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  37070. };
  37071. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  37072. this._highlightsPostProcess.updateEffect();
  37073. };
  37074. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  37075. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  37076. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  37077. this._highlightsGain = amount;
  37078. };
  37079. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  37080. if (this._highlightsGain === -1) {
  37081. this._highlightsGain = 1.0;
  37082. }
  37083. this._highlightsThreshold = amount;
  37084. };
  37085. LensRenderingPipeline.prototype.disableHighlights = function () {
  37086. this._highlightsGain = -1;
  37087. };
  37088. /**
  37089. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  37090. */
  37091. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  37092. if (disableDepthRender === void 0) { disableDepthRender = false; }
  37093. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37094. this._chromaticAberrationPostProcess = undefined;
  37095. this._highlightsPostProcess = undefined;
  37096. this._depthOfFieldPostProcess = undefined;
  37097. this._grainTexture.dispose();
  37098. if (disableDepthRender)
  37099. this._scene.disableDepthRenderer();
  37100. };
  37101. // colors shifting and distortion
  37102. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  37103. var _this = this;
  37104. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  37105. [], // samplers
  37106. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  37107. this._chromaticAberrationPostProcess.onApply = function (effect) {
  37108. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  37109. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  37110. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  37111. };
  37112. };
  37113. // highlights enhancing
  37114. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  37115. var _this = this;
  37116. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  37117. [], // samplers
  37118. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  37119. this._highlightsPostProcess.onApply = function (effect) {
  37120. effect.setFloat('gain', _this._highlightsGain);
  37121. effect.setFloat('threshold', _this._highlightsThreshold);
  37122. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  37123. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  37124. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  37125. };
  37126. };
  37127. // colors shifting and distortion
  37128. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  37129. var _this = this;
  37130. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  37131. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  37132. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  37133. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  37134. this._depthOfFieldPostProcess.onApply = function (effect) {
  37135. effect.setTexture("depthSampler", _this._depthTexture);
  37136. effect.setTexture("grainSampler", _this._grainTexture);
  37137. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  37138. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  37139. effect.setFloat('grain_amount', _this._grainAmount);
  37140. effect.setBool('blur_noise', _this._blurNoise);
  37141. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  37142. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  37143. effect.setFloat('distortion', _this._distortion);
  37144. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  37145. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  37146. effect.setFloat('aperture', _this._dofAperture);
  37147. effect.setFloat('darken', _this._dofDarken);
  37148. effect.setFloat('edge_blur', _this._edgeBlur);
  37149. effect.setBool('highlights', (_this._highlightsGain !== -1));
  37150. effect.setFloat('near', _this._scene.activeCamera.minZ);
  37151. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  37152. };
  37153. };
  37154. // creates a black and white random noise texture, 512x512
  37155. LensRenderingPipeline.prototype._createGrainTexture = function () {
  37156. var size = 512;
  37157. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37158. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  37159. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  37160. var context = this._grainTexture.getContext();
  37161. var rand = function (min, max) {
  37162. return Math.random() * (max - min) + min;
  37163. };
  37164. var value;
  37165. for (var x = 0; x < size; x++) {
  37166. for (var y = 0; y < size; y++) {
  37167. value = Math.floor(rand(0.42, 0.58) * 255);
  37168. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  37169. context.fillRect(x, y, 1, 1);
  37170. }
  37171. }
  37172. this._grainTexture.update(false);
  37173. };
  37174. return LensRenderingPipeline;
  37175. })(BABYLON.PostProcessRenderPipeline);
  37176. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  37177. })(BABYLON || (BABYLON = {}));
  37178. //
  37179. // This post-process allows the modification of rendered colors by using
  37180. // a 'look-up table' (LUT). This effect is also called Color Grading.
  37181. //
  37182. // The object needs to be provided an url to a texture containing the color
  37183. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  37184. // Use an image editing software to tweak the LUT to match your needs.
  37185. //
  37186. // For an example of a color LUT, see here:
  37187. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  37188. // For explanations on color grading, see here:
  37189. // http://udn.epicgames.com/Three/ColorGrading.html
  37190. //
  37191. var BABYLON;
  37192. (function (BABYLON) {
  37193. var ColorCorrectionPostProcess = (function (_super) {
  37194. __extends(ColorCorrectionPostProcess, _super);
  37195. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  37196. var _this = this;
  37197. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  37198. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  37199. this._colorTableTexture.anisotropicFilteringLevel = 1;
  37200. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37201. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37202. this.onApply = function (effect) {
  37203. effect.setTexture("colorTable", _this._colorTableTexture);
  37204. };
  37205. }
  37206. return ColorCorrectionPostProcess;
  37207. })(BABYLON.PostProcess);
  37208. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  37209. })(BABYLON || (BABYLON = {}));
  37210. var BABYLON;
  37211. (function (BABYLON) {
  37212. var AnaglyphFreeCamera = (function (_super) {
  37213. __extends(AnaglyphFreeCamera, _super);
  37214. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  37215. _super.call(this, name, position, scene);
  37216. this.interaxialDistance = interaxialDistance;
  37217. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37218. }
  37219. AnaglyphFreeCamera.prototype.getTypeName = function () {
  37220. return "AnaglyphFreeCamera";
  37221. };
  37222. return AnaglyphFreeCamera;
  37223. })(BABYLON.FreeCamera);
  37224. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  37225. var AnaglyphArcRotateCamera = (function (_super) {
  37226. __extends(AnaglyphArcRotateCamera, _super);
  37227. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  37228. _super.call(this, name, alpha, beta, radius, target, scene);
  37229. this.interaxialDistance = interaxialDistance;
  37230. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37231. }
  37232. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  37233. return "AnaglyphArcRotateCamera";
  37234. };
  37235. return AnaglyphArcRotateCamera;
  37236. })(BABYLON.ArcRotateCamera);
  37237. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  37238. var AnaglyphGamepadCamera = (function (_super) {
  37239. __extends(AnaglyphGamepadCamera, _super);
  37240. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  37241. _super.call(this, name, position, scene);
  37242. this.interaxialDistance = interaxialDistance;
  37243. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37244. }
  37245. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  37246. return "AnaglyphGamepadCamera";
  37247. };
  37248. return AnaglyphGamepadCamera;
  37249. })(BABYLON.GamepadCamera);
  37250. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  37251. var AnaglyphUniversalCamera = (function (_super) {
  37252. __extends(AnaglyphUniversalCamera, _super);
  37253. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  37254. _super.call(this, name, position, scene);
  37255. this.interaxialDistance = interaxialDistance;
  37256. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37257. }
  37258. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  37259. return "AnaglyphUniversalCamera";
  37260. };
  37261. return AnaglyphUniversalCamera;
  37262. })(BABYLON.UniversalCamera);
  37263. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  37264. var StereoscopicFreeCamera = (function (_super) {
  37265. __extends(StereoscopicFreeCamera, _super);
  37266. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  37267. _super.call(this, name, position, scene);
  37268. this.interaxialDistance = interaxialDistance;
  37269. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  37270. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37271. }
  37272. StereoscopicFreeCamera.prototype.getTypeName = function () {
  37273. return "StereoscopicFreeCamera";
  37274. };
  37275. return StereoscopicFreeCamera;
  37276. })(BABYLON.FreeCamera);
  37277. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  37278. var StereoscopicArcRotateCamera = (function (_super) {
  37279. __extends(StereoscopicArcRotateCamera, _super);
  37280. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  37281. _super.call(this, name, alpha, beta, radius, target, scene);
  37282. this.interaxialDistance = interaxialDistance;
  37283. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  37284. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37285. }
  37286. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  37287. return "StereoscopicArcRotateCamera";
  37288. };
  37289. return StereoscopicArcRotateCamera;
  37290. })(BABYLON.ArcRotateCamera);
  37291. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  37292. var StereoscopicGamepadCamera = (function (_super) {
  37293. __extends(StereoscopicGamepadCamera, _super);
  37294. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  37295. _super.call(this, name, position, scene);
  37296. this.interaxialDistance = interaxialDistance;
  37297. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  37298. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37299. }
  37300. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  37301. return "StereoscopicGamepadCamera";
  37302. };
  37303. return StereoscopicGamepadCamera;
  37304. })(BABYLON.GamepadCamera);
  37305. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  37306. var StereoscopicUniversalCamera = (function (_super) {
  37307. __extends(StereoscopicUniversalCamera, _super);
  37308. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  37309. _super.call(this, name, position, scene);
  37310. this.interaxialDistance = interaxialDistance;
  37311. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  37312. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37313. }
  37314. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  37315. return "StereoscopicUniversalCamera";
  37316. };
  37317. return StereoscopicUniversalCamera;
  37318. })(BABYLON.UniversalCamera);
  37319. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  37320. })(BABYLON || (BABYLON = {}));
  37321. var BABYLON;
  37322. (function (BABYLON) {
  37323. var HDRRenderingPipeline = (function (_super) {
  37324. __extends(HDRRenderingPipeline, _super);
  37325. /**
  37326. * @constructor
  37327. * @param {string} name - The rendering pipeline name
  37328. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  37329. * @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)
  37330. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  37331. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  37332. */
  37333. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  37334. var _this = this;
  37335. if (originalPostProcess === void 0) { originalPostProcess = null; }
  37336. _super.call(this, scene.getEngine(), name);
  37337. /**
  37338. * Public members
  37339. */
  37340. // Gaussian Blur
  37341. /**
  37342. * Gaussian blur coefficient
  37343. * @type {number}
  37344. */
  37345. this.gaussCoeff = 0.3;
  37346. /**
  37347. * Gaussian blur mean
  37348. * @type {number}
  37349. */
  37350. this.gaussMean = 1.0;
  37351. /**
  37352. * Gaussian blur standard deviation
  37353. * @type {number}
  37354. */
  37355. this.gaussStandDev = 0.8;
  37356. /**
  37357. * Gaussian blur multiplier. Multiplies the blur effect
  37358. * @type {number}
  37359. */
  37360. this.gaussMultiplier = 4.0;
  37361. // HDR
  37362. /**
  37363. * Exposure, controls the overall intensity of the pipeline
  37364. * @type {number}
  37365. */
  37366. this.exposure = 1.0;
  37367. /**
  37368. * Minimum luminance that the post-process can output. Luminance is >= 0
  37369. * @type {number}
  37370. */
  37371. this.minimumLuminance = 1.0;
  37372. /**
  37373. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  37374. * @type {number}
  37375. */
  37376. this.maximumLuminance = 1e20;
  37377. /**
  37378. * Increase rate for luminance: eye adaptation speed to dark
  37379. * @type {number}
  37380. */
  37381. this.luminanceIncreaserate = 0.5;
  37382. /**
  37383. * Decrease rate for luminance: eye adaptation speed to bright
  37384. * @type {number}
  37385. */
  37386. this.luminanceDecreaseRate = 0.5;
  37387. // Bright pass
  37388. /**
  37389. * Minimum luminance needed to compute HDR
  37390. * @type {number}
  37391. */
  37392. this.brightThreshold = 0.8;
  37393. this._needUpdate = true;
  37394. this._scene = scene;
  37395. // Bright pass
  37396. this._createBrightPassPostProcess(scene, ratio);
  37397. // Down sample X4
  37398. this._createDownSampleX4PostProcess(scene, ratio);
  37399. // Create gaussian blur post-processes
  37400. this._createGaussianBlurPostProcess(scene, ratio);
  37401. // Texture adder
  37402. this._createTextureAdderPostProcess(scene, ratio);
  37403. // Luminance generator
  37404. this._createLuminanceGeneratorPostProcess(scene);
  37405. // HDR
  37406. this._createHDRPostProcess(scene, ratio);
  37407. // Pass postprocess
  37408. if (originalPostProcess === null) {
  37409. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  37410. }
  37411. else {
  37412. this._originalPostProcess = originalPostProcess;
  37413. }
  37414. // Configure pipeline
  37415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  37416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  37417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  37418. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  37419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  37420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  37421. var addDownSamplerPostProcess = function (id) {
  37422. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  37423. };
  37424. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37425. addDownSamplerPostProcess(i);
  37426. }
  37427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  37428. // Finish
  37429. scene.postProcessRenderPipelineManager.addPipeline(this);
  37430. if (cameras !== null) {
  37431. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37432. }
  37433. this.update();
  37434. }
  37435. /**
  37436. * Tells the pipeline to update its post-processes
  37437. */
  37438. HDRRenderingPipeline.prototype.update = function () {
  37439. this._needUpdate = true;
  37440. };
  37441. /**
  37442. * Returns the current calculated luminance
  37443. */
  37444. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  37445. return this._hdrCurrentLuminance;
  37446. };
  37447. /**
  37448. * Returns the currently drawn luminance
  37449. */
  37450. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  37451. return this._hdrOutputLuminance;
  37452. };
  37453. /**
  37454. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  37455. */
  37456. HDRRenderingPipeline.prototype.dispose = function () {
  37457. this._originalPostProcess = undefined;
  37458. this._brightPassPostProcess = undefined;
  37459. this._downSampleX4PostProcess = undefined;
  37460. this._guassianBlurHPostProcess = undefined;
  37461. this._guassianBlurVPostProcess = undefined;
  37462. this._textureAdderPostProcess = undefined;
  37463. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37464. this._downSamplePostProcesses[i] = undefined;
  37465. }
  37466. this._hdrPostProcess = undefined;
  37467. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37468. };
  37469. /**
  37470. * Creates the HDR post-process and computes the luminance adaptation
  37471. */
  37472. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  37473. var _this = this;
  37474. var hdrLastLuminance = 0.0;
  37475. this._hdrOutputLuminance = -1.0;
  37476. this._hdrCurrentLuminance = 1.0;
  37477. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  37478. this._hdrPostProcess.onApply = function (effect) {
  37479. if (_this._hdrOutputLuminance < 0.0) {
  37480. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37481. }
  37482. else {
  37483. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  37484. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  37485. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  37486. }
  37487. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  37488. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  37489. }
  37490. else {
  37491. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37492. }
  37493. }
  37494. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  37495. hdrLastLuminance += scene.getEngine().getDeltaTime();
  37496. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37497. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37498. effect.setFloat("exposure", _this.exposure);
  37499. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  37500. _this._needUpdate = false;
  37501. };
  37502. };
  37503. /**
  37504. * Texture Adder post-process
  37505. */
  37506. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  37507. var _this = this;
  37508. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  37509. this._textureAdderPostProcess.onApply = function (effect) {
  37510. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37511. };
  37512. };
  37513. /**
  37514. * Down sample X4 post-process
  37515. */
  37516. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37517. var _this = this;
  37518. var downSampleX4Offsets = new Array(32);
  37519. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37520. this._downSampleX4PostProcess.onApply = function (effect) {
  37521. if (_this._needUpdate) {
  37522. var id = 0;
  37523. for (var i = -2; i < 2; i++) {
  37524. for (var j = -2; j < 2; j++) {
  37525. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37526. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37527. id += 2;
  37528. }
  37529. }
  37530. }
  37531. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37532. };
  37533. };
  37534. /**
  37535. * Bright pass post-process
  37536. */
  37537. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37538. var _this = this;
  37539. var brightOffsets = new Array(8);
  37540. var brightPassCallback = function (effect) {
  37541. if (_this._needUpdate) {
  37542. var sU = (1.0 / _this._brightPassPostProcess.width);
  37543. var sV = (1.0 / _this._brightPassPostProcess.height);
  37544. brightOffsets[0] = -0.5 * sU;
  37545. brightOffsets[1] = 0.5 * sV;
  37546. brightOffsets[2] = 0.5 * sU;
  37547. brightOffsets[3] = 0.5 * sV;
  37548. brightOffsets[4] = -0.5 * sU;
  37549. brightOffsets[5] = -0.5 * sV;
  37550. brightOffsets[6] = 0.5 * sU;
  37551. brightOffsets[7] = -0.5 * sV;
  37552. }
  37553. effect.setArray2("dsOffsets", brightOffsets);
  37554. effect.setFloat("brightThreshold", _this.brightThreshold);
  37555. };
  37556. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37557. this._brightPassPostProcess.onApply = brightPassCallback;
  37558. };
  37559. /**
  37560. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37561. */
  37562. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37563. var _this = this;
  37564. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37565. var luminanceOffsets = new Array(8);
  37566. var downSampleOffsets = new Array(18);
  37567. var halfDestPixelSize;
  37568. this._downSamplePostProcesses = new Array(lumSteps);
  37569. // Utils for luminance
  37570. var luminanceUpdateSourceOffsets = function (width, height) {
  37571. var sU = (1.0 / width);
  37572. var sV = (1.0 / height);
  37573. luminanceOffsets[0] = -0.5 * sU;
  37574. luminanceOffsets[1] = 0.5 * sV;
  37575. luminanceOffsets[2] = 0.5 * sU;
  37576. luminanceOffsets[3] = 0.5 * sV;
  37577. luminanceOffsets[4] = -0.5 * sU;
  37578. luminanceOffsets[5] = -0.5 * sV;
  37579. luminanceOffsets[6] = 0.5 * sU;
  37580. luminanceOffsets[7] = -0.5 * sV;
  37581. };
  37582. var luminanceUpdateDestOffsets = function (width, height) {
  37583. var id = 0;
  37584. for (var x = -1; x < 2; x++) {
  37585. for (var y = -1; y < 2; y++) {
  37586. downSampleOffsets[id] = (x) / width;
  37587. downSampleOffsets[id + 1] = (y) / height;
  37588. id += 2;
  37589. }
  37590. }
  37591. };
  37592. // Luminance callback
  37593. var luminanceCallback = function (effect) {
  37594. if (_this._needUpdate) {
  37595. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37596. }
  37597. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37598. effect.setArray2("lumOffsets", luminanceOffsets);
  37599. };
  37600. // Down sample callbacks
  37601. var downSampleCallback = function (indice) {
  37602. var i = indice;
  37603. return function (effect) {
  37604. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37605. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37606. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37607. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37608. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37609. effect.setArray2("dsOffsets", downSampleOffsets);
  37610. };
  37611. };
  37612. var downSampleAfterRenderCallback = function (effect) {
  37613. // Unpack result
  37614. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37615. 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);
  37616. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37617. };
  37618. // Create luminance post-process
  37619. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37620. 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);
  37621. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37622. // Create down sample post-processes
  37623. for (var i = lumSteps - 2; i >= 0; i--) {
  37624. var length = Math.pow(3, i);
  37625. ratio = { width: length, height: length };
  37626. var defines = "#define DOWN_SAMPLE\n";
  37627. if (i === 0) {
  37628. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37629. }
  37630. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37631. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37632. if (i === 0) {
  37633. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37634. }
  37635. }
  37636. };
  37637. /**
  37638. * Gaussian blur post-processes. Horizontal and Vertical
  37639. */
  37640. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37641. var _this = this;
  37642. var blurOffsetsW = new Array(9);
  37643. var blurOffsetsH = new Array(9);
  37644. var blurWeights = new Array(9);
  37645. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37646. // Utils for gaussian blur
  37647. var calculateBlurOffsets = function (height) {
  37648. var lastOutputDimensions = {
  37649. width: scene.getEngine().getRenderWidth(),
  37650. height: scene.getEngine().getRenderHeight()
  37651. };
  37652. for (var i = 0; i < 9; i++) {
  37653. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37654. if (height) {
  37655. blurOffsetsH[i] = value;
  37656. }
  37657. else {
  37658. blurOffsetsW[i] = value;
  37659. }
  37660. }
  37661. };
  37662. var calculateWeights = function () {
  37663. var x = 0.0;
  37664. for (var i = 0; i < 9; i++) {
  37665. x = (i - 4.0) / 4.0;
  37666. 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));
  37667. }
  37668. };
  37669. // Callback
  37670. var gaussianBlurCallback = function (height) {
  37671. return function (effect) {
  37672. if (_this._needUpdate) {
  37673. calculateWeights();
  37674. calculateBlurOffsets(height);
  37675. }
  37676. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37677. effect.setArray("blurWeights", blurWeights);
  37678. effect.setFloat("multiplier", _this.gaussMultiplier);
  37679. };
  37680. };
  37681. // Create horizontal gaussian blur post-processes
  37682. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37683. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37684. // Create vertical gaussian blur post-process
  37685. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37686. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37687. };
  37688. // Luminance generator
  37689. HDRRenderingPipeline.LUM_STEPS = 6;
  37690. return HDRRenderingPipeline;
  37691. })(BABYLON.PostProcessRenderPipeline);
  37692. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37693. })(BABYLON || (BABYLON = {}));
  37694. var BABYLON;
  37695. (function (BABYLON) {
  37696. var FaceAdjacencies = (function () {
  37697. function FaceAdjacencies() {
  37698. this.edges = new Array();
  37699. this.edgesConnectedCount = 0;
  37700. }
  37701. return FaceAdjacencies;
  37702. })();
  37703. var EdgesRenderer = (function () {
  37704. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37705. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37706. if (epsilon === void 0) { epsilon = 0.95; }
  37707. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37708. this.edgesWidthScalerForOrthographic = 1000.0;
  37709. this.edgesWidthScalerForPerspective = 50.0;
  37710. this._linesPositions = new Array();
  37711. this._linesNormals = new Array();
  37712. this._linesIndices = new Array();
  37713. this._buffers = new Array();
  37714. this._checkVerticesInsteadOfIndices = false;
  37715. this._source = source;
  37716. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37717. this._epsilon = epsilon;
  37718. this._prepareRessources();
  37719. this._generateEdgesLines();
  37720. }
  37721. EdgesRenderer.prototype._prepareRessources = function () {
  37722. if (this._lineShader) {
  37723. return;
  37724. }
  37725. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37726. attributes: ["position", "normal"],
  37727. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37728. });
  37729. this._lineShader.disableDepthWrite = true;
  37730. this._lineShader.backFaceCulling = false;
  37731. };
  37732. EdgesRenderer.prototype.dispose = function () {
  37733. this._vb0.dispose();
  37734. this._vb1.dispose();
  37735. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37736. this._lineShader.dispose();
  37737. };
  37738. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37739. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37740. return 0;
  37741. }
  37742. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37743. return 1;
  37744. }
  37745. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37746. return 2;
  37747. }
  37748. return -1;
  37749. };
  37750. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37751. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37752. return 0;
  37753. }
  37754. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37755. return 1;
  37756. }
  37757. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37758. return 2;
  37759. }
  37760. return -1;
  37761. };
  37762. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37763. var needToCreateLine;
  37764. if (edge === undefined) {
  37765. needToCreateLine = true;
  37766. }
  37767. else {
  37768. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37769. needToCreateLine = dotProduct < this._epsilon;
  37770. }
  37771. if (needToCreateLine) {
  37772. var offset = this._linesPositions.length / 3;
  37773. var normal = p0.subtract(p1);
  37774. normal.normalize();
  37775. // Positions
  37776. this._linesPositions.push(p0.x);
  37777. this._linesPositions.push(p0.y);
  37778. this._linesPositions.push(p0.z);
  37779. this._linesPositions.push(p0.x);
  37780. this._linesPositions.push(p0.y);
  37781. this._linesPositions.push(p0.z);
  37782. this._linesPositions.push(p1.x);
  37783. this._linesPositions.push(p1.y);
  37784. this._linesPositions.push(p1.z);
  37785. this._linesPositions.push(p1.x);
  37786. this._linesPositions.push(p1.y);
  37787. this._linesPositions.push(p1.z);
  37788. // Normals
  37789. this._linesNormals.push(p1.x);
  37790. this._linesNormals.push(p1.y);
  37791. this._linesNormals.push(p1.z);
  37792. this._linesNormals.push(-1);
  37793. this._linesNormals.push(p1.x);
  37794. this._linesNormals.push(p1.y);
  37795. this._linesNormals.push(p1.z);
  37796. this._linesNormals.push(1);
  37797. this._linesNormals.push(p0.x);
  37798. this._linesNormals.push(p0.y);
  37799. this._linesNormals.push(p0.z);
  37800. this._linesNormals.push(-1);
  37801. this._linesNormals.push(p0.x);
  37802. this._linesNormals.push(p0.y);
  37803. this._linesNormals.push(p0.z);
  37804. this._linesNormals.push(1);
  37805. // Indices
  37806. this._linesIndices.push(offset);
  37807. this._linesIndices.push(offset + 1);
  37808. this._linesIndices.push(offset + 2);
  37809. this._linesIndices.push(offset);
  37810. this._linesIndices.push(offset + 2);
  37811. this._linesIndices.push(offset + 3);
  37812. }
  37813. };
  37814. EdgesRenderer.prototype._generateEdgesLines = function () {
  37815. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37816. var indices = this._source.getIndices();
  37817. // First let's find adjacencies
  37818. var adjacencies = new Array();
  37819. var faceNormals = new Array();
  37820. var index;
  37821. var faceAdjacencies;
  37822. // Prepare faces
  37823. for (index = 0; index < indices.length; index += 3) {
  37824. faceAdjacencies = new FaceAdjacencies();
  37825. var p0Index = indices[index];
  37826. var p1Index = indices[index + 1];
  37827. var p2Index = indices[index + 2];
  37828. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37829. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37830. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37831. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37832. faceNormal.normalize();
  37833. faceNormals.push(faceNormal);
  37834. adjacencies.push(faceAdjacencies);
  37835. }
  37836. // Scan
  37837. for (index = 0; index < adjacencies.length; index++) {
  37838. faceAdjacencies = adjacencies[index];
  37839. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37840. var otherFaceAdjacencies = adjacencies[otherIndex];
  37841. if (faceAdjacencies.edgesConnectedCount === 3) {
  37842. break;
  37843. }
  37844. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37845. continue;
  37846. }
  37847. var otherP0 = indices[otherIndex * 3];
  37848. var otherP1 = indices[otherIndex * 3 + 1];
  37849. var otherP2 = indices[otherIndex * 3 + 2];
  37850. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37851. var otherEdgeIndex;
  37852. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37853. continue;
  37854. }
  37855. switch (edgeIndex) {
  37856. case 0:
  37857. if (this._checkVerticesInsteadOfIndices) {
  37858. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37859. }
  37860. else {
  37861. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37862. }
  37863. break;
  37864. case 1:
  37865. if (this._checkVerticesInsteadOfIndices) {
  37866. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37867. }
  37868. else {
  37869. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37870. }
  37871. break;
  37872. case 2:
  37873. if (this._checkVerticesInsteadOfIndices) {
  37874. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37875. }
  37876. else {
  37877. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37878. }
  37879. break;
  37880. }
  37881. if (otherEdgeIndex === -1) {
  37882. continue;
  37883. }
  37884. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37885. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37886. faceAdjacencies.edgesConnectedCount++;
  37887. otherFaceAdjacencies.edgesConnectedCount++;
  37888. if (faceAdjacencies.edgesConnectedCount === 3) {
  37889. break;
  37890. }
  37891. }
  37892. }
  37893. }
  37894. // Create lines
  37895. for (index = 0; index < adjacencies.length; index++) {
  37896. // 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
  37897. var current = adjacencies[index];
  37898. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37899. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37900. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37901. }
  37902. // Merge into a single mesh
  37903. var engine = this._source.getScene().getEngine();
  37904. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37905. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37906. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37907. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37908. this._ib = engine.createIndexBuffer(this._linesIndices);
  37909. this._indicesCount = this._linesIndices.length;
  37910. };
  37911. EdgesRenderer.prototype.render = function () {
  37912. if (!this._lineShader.isReady()) {
  37913. return;
  37914. }
  37915. var scene = this._source.getScene();
  37916. var engine = scene.getEngine();
  37917. this._lineShader._preBind();
  37918. // VBOs
  37919. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37920. scene.resetCachedMaterial();
  37921. this._lineShader.setColor4("color", this._source.edgesColor);
  37922. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37923. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37924. }
  37925. else {
  37926. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37927. }
  37928. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37929. this._lineShader.bind(this._source.getWorldMatrix());
  37930. // Draw order
  37931. engine.draw(true, 0, this._indicesCount);
  37932. this._lineShader.unbind();
  37933. engine.setDepthWrite(true);
  37934. };
  37935. return EdgesRenderer;
  37936. })();
  37937. BABYLON.EdgesRenderer = EdgesRenderer;
  37938. })(BABYLON || (BABYLON = {}));
  37939. var BABYLON;
  37940. (function (BABYLON) {
  37941. (function (TonemappingOperator) {
  37942. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37943. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37944. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37945. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37946. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37947. var TonemappingOperator = BABYLON.TonemappingOperator;
  37948. ;
  37949. var TonemapPostProcess = (function (_super) {
  37950. __extends(TonemapPostProcess, _super);
  37951. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37952. var _this = this;
  37953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37954. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37955. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37956. this._operator = _operator;
  37957. this.exposureAdjustment = exposureAdjustment;
  37958. var defines = "#define ";
  37959. if (this._operator === TonemappingOperator.Hable)
  37960. defines += "HABLE_TONEMAPPING";
  37961. else if (this._operator === TonemappingOperator.Reinhard)
  37962. defines += "REINHARD_TONEMAPPING";
  37963. else if (this._operator === TonemappingOperator.HejiDawson)
  37964. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37965. else if (this._operator === TonemappingOperator.Photographic)
  37966. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37967. //sadly a second call to create the effect.
  37968. this.updateEffect(defines);
  37969. this.onApply = function (effect) {
  37970. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37971. };
  37972. }
  37973. return TonemapPostProcess;
  37974. })(BABYLON.PostProcess);
  37975. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37976. })(BABYLON || (BABYLON = {}));
  37977. var BABYLON;
  37978. (function (BABYLON) {
  37979. var ReflectionProbe = (function () {
  37980. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37981. var _this = this;
  37982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37983. this.name = name;
  37984. this._viewMatrix = BABYLON.Matrix.Identity();
  37985. this._target = BABYLON.Vector3.Zero();
  37986. this._add = BABYLON.Vector3.Zero();
  37987. this.position = BABYLON.Vector3.Zero();
  37988. this._scene = scene;
  37989. this._scene.reflectionProbes.push(this);
  37990. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37991. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37992. switch (faceIndex) {
  37993. case 0:
  37994. _this._add.copyFromFloats(1, 0, 0);
  37995. break;
  37996. case 1:
  37997. _this._add.copyFromFloats(-1, 0, 0);
  37998. break;
  37999. case 2:
  38000. _this._add.copyFromFloats(0, -1, 0);
  38001. break;
  38002. case 3:
  38003. _this._add.copyFromFloats(0, 1, 0);
  38004. break;
  38005. case 4:
  38006. _this._add.copyFromFloats(0, 0, 1);
  38007. break;
  38008. case 5:
  38009. _this._add.copyFromFloats(0, 0, -1);
  38010. break;
  38011. }
  38012. if (_this._attachedMesh) {
  38013. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  38014. }
  38015. _this.position.addToRef(_this._add, _this._target);
  38016. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  38017. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  38018. };
  38019. this._renderTargetTexture.onAfterUnbind = function () {
  38020. scene.updateTransformMatrix(true);
  38021. };
  38022. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  38023. }
  38024. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  38025. get: function () {
  38026. return this._renderTargetTexture.refreshRate;
  38027. },
  38028. set: function (value) {
  38029. this._renderTargetTexture.refreshRate = value;
  38030. },
  38031. enumerable: true,
  38032. configurable: true
  38033. });
  38034. ReflectionProbe.prototype.getScene = function () {
  38035. return this._scene;
  38036. };
  38037. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  38038. get: function () {
  38039. return this._renderTargetTexture;
  38040. },
  38041. enumerable: true,
  38042. configurable: true
  38043. });
  38044. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  38045. get: function () {
  38046. return this._renderTargetTexture.renderList;
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  38052. this._attachedMesh = mesh;
  38053. };
  38054. ReflectionProbe.prototype.dispose = function () {
  38055. var index = this._scene.reflectionProbes.indexOf(this);
  38056. if (index !== -1) {
  38057. // Remove from the scene if found
  38058. this._scene.reflectionProbes.splice(index, 1);
  38059. }
  38060. if (this._renderTargetTexture) {
  38061. this._renderTargetTexture.dispose();
  38062. this._renderTargetTexture = null;
  38063. }
  38064. };
  38065. return ReflectionProbe;
  38066. })();
  38067. BABYLON.ReflectionProbe = ReflectionProbe;
  38068. })(BABYLON || (BABYLON = {}));
  38069. var BABYLON;
  38070. (function (BABYLON) {
  38071. var SolidParticle = (function () {
  38072. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  38073. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  38074. this.position = BABYLON.Vector3.Zero(); // position
  38075. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38076. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  38077. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  38078. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38079. this.alive = true; // alive
  38080. this.idx = particleIndex;
  38081. this._pos = positionIndex;
  38082. this._model = model;
  38083. this.shapeId = shapeId;
  38084. this.idxInShape = idxInShape;
  38085. }
  38086. return SolidParticle;
  38087. })();
  38088. BABYLON.SolidParticle = SolidParticle;
  38089. var ModelShape = (function () {
  38090. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38091. this.shapeID = id;
  38092. this._shape = shape;
  38093. this._shapeUV = shapeUV;
  38094. this._positionFunction = posFunction;
  38095. this._vertexFunction = vtxFunction;
  38096. }
  38097. return ModelShape;
  38098. })();
  38099. BABYLON.ModelShape = ModelShape;
  38100. })(BABYLON || (BABYLON = {}));
  38101. var BABYLON;
  38102. (function (BABYLON) {
  38103. /**
  38104. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  38105. */
  38106. var SolidParticleSystem = (function () {
  38107. /**
  38108. * Creates a SPS (Solid Particle System) object.
  38109. * @param name the SPS name, this will be the underlying mesh name
  38110. * @param scene the scene in which the SPS is added
  38111. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  38112. */
  38113. function SolidParticleSystem(name, scene, options) {
  38114. // public members
  38115. /**
  38116. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38117. * Example : var p = SPS.particles[i];
  38118. */
  38119. this.particles = new Array();
  38120. /**
  38121. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38122. */
  38123. this.nbParticles = 0;
  38124. /**
  38125. * If the particles must ever face the camera (default false). Useful for planar particles.
  38126. */
  38127. this.billboard = false;
  38128. /**
  38129. * This a counter ofr your own usage. It's not set by any SPS functions.
  38130. */
  38131. this.counter = 0;
  38132. /**
  38133. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38134. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  38135. */
  38136. this.vars = {};
  38137. this._positions = new Array();
  38138. this._indices = new Array();
  38139. this._normals = new Array();
  38140. this._colors = new Array();
  38141. this._uvs = new Array();
  38142. this._index = 0; // indices index
  38143. this._updatable = true;
  38144. this._pickable = false;
  38145. this._isVisibilityBoxLocked = false;
  38146. this._alwaysVisible = false;
  38147. this._shapeCounter = 0;
  38148. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  38149. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38150. this._computeParticleColor = true;
  38151. this._computeParticleTexture = true;
  38152. this._computeParticleRotation = true;
  38153. this._computeParticleVertex = false;
  38154. this._computeBoundingBox = false;
  38155. this._cam_axisZ = BABYLON.Vector3.Zero();
  38156. this._cam_axisY = BABYLON.Vector3.Zero();
  38157. this._cam_axisX = BABYLON.Vector3.Zero();
  38158. this._axisX = BABYLON.Axis.X;
  38159. this._axisY = BABYLON.Axis.Y;
  38160. this._axisZ = BABYLON.Axis.Z;
  38161. this._fakeCamPos = BABYLON.Vector3.Zero();
  38162. this._rotMatrix = new BABYLON.Matrix();
  38163. this._invertMatrix = new BABYLON.Matrix();
  38164. this._rotated = BABYLON.Vector3.Zero();
  38165. this._quaternion = new BABYLON.Quaternion();
  38166. this._vertex = BABYLON.Vector3.Zero();
  38167. this._normal = BABYLON.Vector3.Zero();
  38168. this._yaw = 0.0;
  38169. this._pitch = 0.0;
  38170. this._roll = 0.0;
  38171. this._halfroll = 0.0;
  38172. this._halfpitch = 0.0;
  38173. this._halfyaw = 0.0;
  38174. this._sinRoll = 0.0;
  38175. this._cosRoll = 0.0;
  38176. this._sinPitch = 0.0;
  38177. this._cosPitch = 0.0;
  38178. this._sinYaw = 0.0;
  38179. this._cosYaw = 0.0;
  38180. this._w = 0.0;
  38181. this._minimum = BABYLON.Tmp.Vector3[0];
  38182. this._maximum = BABYLON.Tmp.Vector3[1];
  38183. this.name = name;
  38184. this._scene = scene;
  38185. this._camera = scene.activeCamera;
  38186. this._pickable = options ? options.isPickable : false;
  38187. if (options && options.updatable) {
  38188. this._updatable = options.updatable;
  38189. }
  38190. else {
  38191. this._updatable = true;
  38192. }
  38193. if (this._pickable) {
  38194. this.pickedParticles = [];
  38195. }
  38196. }
  38197. /**
  38198. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38199. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  38200. */
  38201. SolidParticleSystem.prototype.buildMesh = function () {
  38202. if (this.nbParticles === 0) {
  38203. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38204. this.addShape(triangle, 1);
  38205. triangle.dispose();
  38206. }
  38207. this._positions32 = new Float32Array(this._positions);
  38208. this._uvs32 = new Float32Array(this._uvs);
  38209. this._colors32 = new Float32Array(this._colors);
  38210. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38211. this._normals32 = new Float32Array(this._normals);
  38212. this._fixedNormal32 = new Float32Array(this._normals);
  38213. var vertexData = new BABYLON.VertexData();
  38214. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38215. vertexData.indices = this._indices;
  38216. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38217. if (this._uvs32) {
  38218. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38219. ;
  38220. }
  38221. if (this._colors32) {
  38222. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38223. }
  38224. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38225. vertexData.applyToMesh(mesh, this._updatable);
  38226. this.mesh = mesh;
  38227. this.mesh.isPickable = this._pickable;
  38228. // free memory
  38229. this._positions = null;
  38230. this._normals = null;
  38231. this._uvs = null;
  38232. this._colors = null;
  38233. if (!this._updatable) {
  38234. this.particles.length = 0;
  38235. }
  38236. return mesh;
  38237. };
  38238. /**
  38239. * Digests the mesh and generates as many solid particles in the system as wanted.
  38240. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38241. * Thus the particles generated from digest() have their property "positiion" yet set.
  38242. * @param mesh the mesh to be digested
  38243. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  38244. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  38245. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  38246. */
  38247. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38248. var size = (options && options.facetNb) || 1;
  38249. var number = (options && options.number);
  38250. var delta = (options && options.delta) || 0;
  38251. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38252. var meshInd = mesh.getIndices();
  38253. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38254. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38255. var f = 0; // facet counter
  38256. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38257. // compute size from number
  38258. if (number) {
  38259. number = (number > totalFacets) ? totalFacets : number;
  38260. size = Math.round(totalFacets / number);
  38261. delta = 0;
  38262. }
  38263. else {
  38264. size = (size > totalFacets) ? totalFacets : size;
  38265. }
  38266. var facetPos = []; // submesh positions
  38267. var facetInd = []; // submesh indices
  38268. var facetUV = []; // submesh UV
  38269. var facetCol = []; // submesh colors
  38270. var barycenter = BABYLON.Tmp.Vector3[0];
  38271. var rand;
  38272. var sizeO = size;
  38273. while (f < totalFacets) {
  38274. size = sizeO + Math.floor((1 + delta) * Math.random());
  38275. if (f > totalFacets - size) {
  38276. size = totalFacets - f;
  38277. }
  38278. // reset temp arrays
  38279. facetPos.length = 0;
  38280. facetInd.length = 0;
  38281. facetUV.length = 0;
  38282. facetCol.length = 0;
  38283. // iterate over "size" facets
  38284. var fi = 0;
  38285. for (var j = f * 3; j < (f + size) * 3; j++) {
  38286. facetInd.push(fi);
  38287. var i = meshInd[j];
  38288. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38289. if (meshUV) {
  38290. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38291. }
  38292. if (meshCol) {
  38293. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38294. }
  38295. fi++;
  38296. }
  38297. // create a model shape for each single particle
  38298. var idx = this.nbParticles;
  38299. var shape = this._posToShape(facetPos);
  38300. var shapeUV = this._uvsToShapeUV(facetUV);
  38301. // compute the barycenter of the shape
  38302. var v;
  38303. for (v = 0; v < shape.length; v++) {
  38304. barycenter.addInPlace(shape[v]);
  38305. }
  38306. barycenter.scaleInPlace(1 / shape.length);
  38307. // shift the shape from its barycenter to the origin
  38308. for (v = 0; v < shape.length; v++) {
  38309. shape[v].subtractInPlace(barycenter);
  38310. }
  38311. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38312. // add the particle in the SPS
  38313. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  38314. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  38315. // initialize the particle position
  38316. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38317. this._index += shape.length;
  38318. idx++;
  38319. this.nbParticles++;
  38320. this._shapeCounter++;
  38321. f += size;
  38322. }
  38323. };
  38324. //reset copy
  38325. SolidParticleSystem.prototype._resetCopy = function () {
  38326. this._copy.position.x = 0;
  38327. this._copy.position.y = 0;
  38328. this._copy.position.z = 0;
  38329. this._copy.rotation.x = 0;
  38330. this._copy.rotation.y = 0;
  38331. this._copy.rotation.z = 0;
  38332. this._copy.quaternion = null;
  38333. this._copy.scale.x = 1;
  38334. this._copy.scale.y = 1;
  38335. this._copy.scale.z = 1;
  38336. this._copy.uvs.x = 0;
  38337. this._copy.uvs.y = 0;
  38338. this._copy.uvs.z = 1;
  38339. this._copy.uvs.w = 1;
  38340. this._copy.color = null;
  38341. };
  38342. // _meshBuilder : inserts the shape model in the global SPS mesh
  38343. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  38344. var i;
  38345. var u = 0;
  38346. var c = 0;
  38347. this._resetCopy();
  38348. if (options && options.positionFunction) {
  38349. options.positionFunction(this._copy, idx, idxInShape);
  38350. }
  38351. if (this._copy.quaternion) {
  38352. this._quaternion.x = this._copy.quaternion.x;
  38353. this._quaternion.y = this._copy.quaternion.y;
  38354. this._quaternion.z = this._copy.quaternion.z;
  38355. this._quaternion.w = this._copy.quaternion.w;
  38356. }
  38357. else {
  38358. this._yaw = this._copy.rotation.y;
  38359. this._pitch = this._copy.rotation.x;
  38360. this._roll = this._copy.rotation.z;
  38361. this._quaternionRotationYPR();
  38362. }
  38363. this._quaternionToRotationMatrix();
  38364. for (i = 0; i < shape.length; i++) {
  38365. this._vertex.x = shape[i].x;
  38366. this._vertex.y = shape[i].y;
  38367. this._vertex.z = shape[i].z;
  38368. if (options && options.vertexFunction) {
  38369. options.vertexFunction(this._copy, this._vertex, i);
  38370. }
  38371. this._vertex.x *= this._copy.scale.x;
  38372. this._vertex.y *= this._copy.scale.y;
  38373. this._vertex.z *= this._copy.scale.z;
  38374. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38375. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38376. if (meshUV) {
  38377. 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);
  38378. u += 2;
  38379. }
  38380. if (this._copy.color) {
  38381. this._color = this._copy.color;
  38382. }
  38383. else if (meshCol && meshCol[c]) {
  38384. this._color.r = meshCol[c];
  38385. this._color.g = meshCol[c + 1];
  38386. this._color.b = meshCol[c + 2];
  38387. this._color.a = meshCol[c + 3];
  38388. }
  38389. else {
  38390. this._color.r = 1;
  38391. this._color.g = 1;
  38392. this._color.b = 1;
  38393. this._color.a = 1;
  38394. }
  38395. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38396. c += 4;
  38397. }
  38398. for (i = 0; i < meshInd.length; i++) {
  38399. indices.push(p + meshInd[i]);
  38400. }
  38401. if (this._pickable) {
  38402. var nbfaces = meshInd.length / 3;
  38403. for (i = 0; i < nbfaces; i++) {
  38404. this.pickedParticles.push({ idx: idx, faceId: i });
  38405. }
  38406. }
  38407. };
  38408. // returns a shape array from positions array
  38409. SolidParticleSystem.prototype._posToShape = function (positions) {
  38410. var shape = [];
  38411. for (var i = 0; i < positions.length; i += 3) {
  38412. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38413. }
  38414. return shape;
  38415. };
  38416. // returns a shapeUV array from a Vector4 uvs
  38417. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38418. var shapeUV = [];
  38419. if (uvs) {
  38420. for (var i = 0; i < uvs.length; i++)
  38421. shapeUV.push(uvs[i]);
  38422. }
  38423. return shapeUV;
  38424. };
  38425. // adds a new particle object in the particles array
  38426. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  38427. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  38428. };
  38429. /**
  38430. * Adds some particles to the SPS from the model shape.
  38431. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  38432. * @param mesh any Mesh object that will be used as a model for the solid particles.
  38433. * @param nb the number of particles to be created from this model
  38434. * @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
  38435. */
  38436. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38437. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38438. var meshInd = mesh.getIndices();
  38439. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38440. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38441. var shape = this._posToShape(meshPos);
  38442. var shapeUV = this._uvsToShapeUV(meshUV);
  38443. var posfunc = options ? options.positionFunction : null;
  38444. var vtxfunc = options ? options.vertexFunction : null;
  38445. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38446. // particles
  38447. var idx = this.nbParticles;
  38448. for (var i = 0; i < nb; i++) {
  38449. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  38450. if (this._updatable) {
  38451. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  38452. }
  38453. this._index += shape.length;
  38454. idx++;
  38455. }
  38456. this.nbParticles += nb;
  38457. this._shapeCounter++;
  38458. return this._shapeCounter - 1;
  38459. };
  38460. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38461. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38462. this._resetCopy();
  38463. if (particle._model._positionFunction) {
  38464. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38465. }
  38466. if (this._copy.quaternion) {
  38467. this._quaternion.x = this._copy.quaternion.x;
  38468. this._quaternion.y = this._copy.quaternion.y;
  38469. this._quaternion.z = this._copy.quaternion.z;
  38470. this._quaternion.w = this._copy.quaternion.w;
  38471. }
  38472. else {
  38473. this._yaw = this._copy.rotation.y;
  38474. this._pitch = this._copy.rotation.x;
  38475. this._roll = this._copy.rotation.z;
  38476. this._quaternionRotationYPR();
  38477. }
  38478. this._quaternionToRotationMatrix();
  38479. this._shape = particle._model._shape;
  38480. for (var pt = 0; pt < this._shape.length; pt++) {
  38481. this._vertex.x = this._shape[pt].x;
  38482. this._vertex.y = this._shape[pt].y;
  38483. this._vertex.z = this._shape[pt].z;
  38484. if (particle._model._vertexFunction) {
  38485. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38486. }
  38487. this._vertex.x *= this._copy.scale.x;
  38488. this._vertex.y *= this._copy.scale.y;
  38489. this._vertex.z *= this._copy.scale.z;
  38490. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38491. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38492. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38493. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38494. }
  38495. particle.position.x = 0;
  38496. particle.position.y = 0;
  38497. particle.position.z = 0;
  38498. particle.rotation.x = 0;
  38499. particle.rotation.y = 0;
  38500. particle.rotation.z = 0;
  38501. particle.quaternion = null;
  38502. particle.scale.x = 1;
  38503. particle.scale.y = 1;
  38504. particle.scale.z = 1;
  38505. };
  38506. /**
  38507. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38508. */
  38509. SolidParticleSystem.prototype.rebuildMesh = function () {
  38510. for (var p = 0; p < this.particles.length; p++) {
  38511. this._rebuildParticle(this.particles[p]);
  38512. }
  38513. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38514. };
  38515. /**
  38516. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38517. * This method calls updateParticle() for each particles of the SPS.
  38518. * For an animated SPS, it is usually called within the render loop.
  38519. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38520. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38521. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38522. */
  38523. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38524. if (start === void 0) { start = 0; }
  38525. if (end === void 0) { end = this.nbParticles - 1; }
  38526. if (update === void 0) { update = true; }
  38527. if (!this._updatable) {
  38528. return;
  38529. }
  38530. // custom beforeUpdate
  38531. this.beforeUpdateParticles(start, end, update);
  38532. this._cam_axisX.x = 1;
  38533. this._cam_axisX.y = 0;
  38534. this._cam_axisX.z = 0;
  38535. this._cam_axisY.x = 0;
  38536. this._cam_axisY.y = 1;
  38537. this._cam_axisY.z = 0;
  38538. this._cam_axisZ.x = 0;
  38539. this._cam_axisZ.y = 0;
  38540. this._cam_axisZ.z = 1;
  38541. // if the particles will always face the camera
  38542. if (this.billboard) {
  38543. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38544. this._yaw = this.mesh.rotation.y;
  38545. this._pitch = this.mesh.rotation.x;
  38546. this._roll = this.mesh.rotation.z;
  38547. this._quaternionRotationYPR();
  38548. this._quaternionToRotationMatrix();
  38549. this._rotMatrix.invertToRef(this._invertMatrix);
  38550. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38551. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38552. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38553. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38554. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38555. this._cam_axisY.normalize();
  38556. this._cam_axisX.normalize();
  38557. this._cam_axisZ.normalize();
  38558. }
  38559. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38560. var idx = 0;
  38561. var index = 0;
  38562. var colidx = 0;
  38563. var colorIndex = 0;
  38564. var uvidx = 0;
  38565. var uvIndex = 0;
  38566. if (this._computeBoundingBox) {
  38567. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38568. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38569. }
  38570. // particle loop
  38571. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38572. for (var p = start; p <= end; p++) {
  38573. this._particle = this.particles[p];
  38574. this._shape = this._particle._model._shape;
  38575. this._shapeUV = this._particle._model._shapeUV;
  38576. // call to custom user function to update the particle properties
  38577. this.updateParticle(this._particle);
  38578. // particle rotation matrix
  38579. if (this.billboard) {
  38580. this._particle.rotation.x = 0.0;
  38581. this._particle.rotation.y = 0.0;
  38582. }
  38583. if (this._computeParticleRotation) {
  38584. if (this._particle.quaternion) {
  38585. this._quaternion.x = this._particle.quaternion.x;
  38586. this._quaternion.y = this._particle.quaternion.y;
  38587. this._quaternion.z = this._particle.quaternion.z;
  38588. this._quaternion.w = this._particle.quaternion.w;
  38589. }
  38590. else {
  38591. this._yaw = this._particle.rotation.y;
  38592. this._pitch = this._particle.rotation.x;
  38593. this._roll = this._particle.rotation.z;
  38594. this._quaternionRotationYPR();
  38595. }
  38596. this._quaternionToRotationMatrix();
  38597. }
  38598. for (var pt = 0; pt < this._shape.length; pt++) {
  38599. idx = index + pt * 3;
  38600. colidx = colorIndex + pt * 4;
  38601. uvidx = uvIndex + pt * 2;
  38602. this._vertex.x = this._shape[pt].x;
  38603. this._vertex.y = this._shape[pt].y;
  38604. this._vertex.z = this._shape[pt].z;
  38605. if (this._computeParticleVertex) {
  38606. this.updateParticleVertex(this._particle, this._vertex, pt);
  38607. }
  38608. // positions
  38609. this._vertex.x *= this._particle.scale.x;
  38610. this._vertex.y *= this._particle.scale.y;
  38611. this._vertex.z *= this._particle.scale.z;
  38612. 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];
  38613. 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;
  38614. 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;
  38615. 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;
  38616. 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;
  38617. 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;
  38618. 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;
  38619. if (this._computeBoundingBox) {
  38620. if (this._positions32[idx] < this._minimum.x) {
  38621. this._minimum.x = this._positions32[idx];
  38622. }
  38623. if (this._positions32[idx] > this._maximum.x) {
  38624. this._maximum.x = this._positions32[idx];
  38625. }
  38626. if (this._positions32[idx + 1] < this._minimum.y) {
  38627. this._minimum.y = this._positions32[idx + 1];
  38628. }
  38629. if (this._positions32[idx + 1] > this._maximum.y) {
  38630. this._maximum.y = this._positions32[idx + 1];
  38631. }
  38632. if (this._positions32[idx + 2] < this._minimum.z) {
  38633. this._minimum.z = this._positions32[idx + 2];
  38634. }
  38635. if (this._positions32[idx + 2] > this._maximum.z) {
  38636. this._maximum.z = this._positions32[idx + 2];
  38637. }
  38638. }
  38639. // normals : if the particles can't be morphed then just rotate the normals
  38640. if (!this._computeParticleVertex && !this.billboard) {
  38641. this._normal.x = this._fixedNormal32[idx];
  38642. this._normal.y = this._fixedNormal32[idx + 1];
  38643. this._normal.z = this._fixedNormal32[idx + 2];
  38644. 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];
  38645. 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;
  38646. 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;
  38647. 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;
  38648. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38649. 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;
  38650. 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;
  38651. }
  38652. if (this._computeParticleColor) {
  38653. this._colors32[colidx] = this._particle.color.r;
  38654. this._colors32[colidx + 1] = this._particle.color.g;
  38655. this._colors32[colidx + 2] = this._particle.color.b;
  38656. this._colors32[colidx + 3] = this._particle.color.a;
  38657. }
  38658. if (this._computeParticleTexture) {
  38659. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38660. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38661. }
  38662. }
  38663. index = idx + 3;
  38664. colorIndex = colidx + 4;
  38665. uvIndex = uvidx + 2;
  38666. }
  38667. if (update) {
  38668. if (this._computeParticleColor) {
  38669. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38670. }
  38671. if (this._computeParticleTexture) {
  38672. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38673. }
  38674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38675. if (!this.mesh.areNormalsFrozen) {
  38676. if (this._computeParticleVertex || this.billboard) {
  38677. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38678. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38679. for (var i = 0; i < this._normals32.length; i++) {
  38680. this._fixedNormal32[i] = this._normals32[i];
  38681. }
  38682. }
  38683. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38684. }
  38685. }
  38686. if (this._computeBoundingBox) {
  38687. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38688. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38689. }
  38690. this.afterUpdateParticles(start, end, update);
  38691. };
  38692. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38693. this._halfroll = this._roll * 0.5;
  38694. this._halfpitch = this._pitch * 0.5;
  38695. this._halfyaw = this._yaw * 0.5;
  38696. this._sinRoll = Math.sin(this._halfroll);
  38697. this._cosRoll = Math.cos(this._halfroll);
  38698. this._sinPitch = Math.sin(this._halfpitch);
  38699. this._cosPitch = Math.cos(this._halfpitch);
  38700. this._sinYaw = Math.sin(this._halfyaw);
  38701. this._cosYaw = Math.cos(this._halfyaw);
  38702. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38703. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38704. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38705. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38706. };
  38707. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38708. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38709. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38710. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38711. this._rotMatrix.m[3] = 0;
  38712. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38713. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38714. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38715. this._rotMatrix.m[7] = 0;
  38716. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38717. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38718. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38719. this._rotMatrix.m[11] = 0;
  38720. this._rotMatrix.m[12] = 0;
  38721. this._rotMatrix.m[13] = 0;
  38722. this._rotMatrix.m[14] = 0;
  38723. this._rotMatrix.m[15] = 1.0;
  38724. };
  38725. /**
  38726. * Disposes the SPS
  38727. */
  38728. SolidParticleSystem.prototype.dispose = function () {
  38729. this.mesh.dispose();
  38730. this.vars = null;
  38731. // drop references to internal big arrays for the GC
  38732. this._positions = null;
  38733. this._indices = null;
  38734. this._normals = null;
  38735. this._uvs = null;
  38736. this._colors = null;
  38737. this._positions32 = null;
  38738. this._normals32 = null;
  38739. this._fixedNormal32 = null;
  38740. this._uvs32 = null;
  38741. this._colors32 = null;
  38742. this.pickedParticles = null;
  38743. };
  38744. /**
  38745. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38746. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38747. */
  38748. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38749. if (!this._isVisibilityBoxLocked) {
  38750. this.mesh.refreshBoundingInfo();
  38751. }
  38752. };
  38753. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38754. * @param size the size (float) of the visibility box
  38755. * note : this doesn't lock the SPS mesh bounding box.
  38756. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38757. */
  38758. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38759. var vis = size / 2;
  38760. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38761. };
  38762. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38763. // getter and setter
  38764. /**
  38765. * True if the SPS is set as always visible
  38766. */
  38767. get: function () {
  38768. return this._alwaysVisible;
  38769. },
  38770. /**
  38771. * Sets the SPS as always visible or not
  38772. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38773. */
  38774. set: function (val) {
  38775. this._alwaysVisible = val;
  38776. this.mesh.alwaysSelectAsActiveMesh = val;
  38777. },
  38778. enumerable: true,
  38779. configurable: true
  38780. });
  38781. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38782. /**
  38783. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38784. */
  38785. get: function () {
  38786. return this._isVisibilityBoxLocked;
  38787. },
  38788. /**
  38789. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38790. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38791. */
  38792. set: function (val) {
  38793. this._isVisibilityBoxLocked = val;
  38794. this.mesh.getBoundingInfo().isLocked = val;
  38795. },
  38796. enumerable: true,
  38797. configurable: true
  38798. });
  38799. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38800. // getters
  38801. get: function () {
  38802. return this._computeParticleRotation;
  38803. },
  38804. // Optimizer setters
  38805. /**
  38806. * Tells to setParticles() to compute the particle rotations or not.
  38807. * Default value : true. The SPS is faster when it's set to false.
  38808. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38809. */
  38810. set: function (val) {
  38811. this._computeParticleRotation = val;
  38812. },
  38813. enumerable: true,
  38814. configurable: true
  38815. });
  38816. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38817. get: function () {
  38818. return this._computeParticleColor;
  38819. },
  38820. /**
  38821. * Tells to setParticles() to compute the particle colors or not.
  38822. * Default value : true. The SPS is faster when it's set to false.
  38823. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38824. */
  38825. set: function (val) {
  38826. this._computeParticleColor = val;
  38827. },
  38828. enumerable: true,
  38829. configurable: true
  38830. });
  38831. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38832. get: function () {
  38833. return this._computeParticleTexture;
  38834. },
  38835. /**
  38836. * Tells to setParticles() to compute the particle textures or not.
  38837. * Default value : true. The SPS is faster when it's set to false.
  38838. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38839. */
  38840. set: function (val) {
  38841. this._computeParticleTexture = val;
  38842. },
  38843. enumerable: true,
  38844. configurable: true
  38845. });
  38846. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38847. get: function () {
  38848. return this._computeParticleVertex;
  38849. },
  38850. /**
  38851. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38852. * Default value : false. The SPS is faster when it's set to false.
  38853. * Note : the particle custom vertex positions aren't stored values.
  38854. */
  38855. set: function (val) {
  38856. this._computeParticleVertex = val;
  38857. },
  38858. enumerable: true,
  38859. configurable: true
  38860. });
  38861. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38862. get: function () {
  38863. return this._computeBoundingBox;
  38864. },
  38865. /**
  38866. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38867. */
  38868. set: function (val) {
  38869. this._computeBoundingBox = val;
  38870. },
  38871. enumerable: true,
  38872. configurable: true
  38873. });
  38874. // =======================================================================
  38875. // Particle behavior logic
  38876. // these following methods may be overwritten by the user to fit his needs
  38877. /**
  38878. * This function does nothing. It may be overwritten to set all the particles first values.
  38879. * The SPS doesn't call this function, you may have to call it by your own.
  38880. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38881. */
  38882. SolidParticleSystem.prototype.initParticles = function () {
  38883. };
  38884. /**
  38885. * This function does nothing. It may be overwritten to recycle a particle.
  38886. * The SPS doesn't call this function, you may have to call it by your own.
  38887. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38888. */
  38889. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38890. return particle;
  38891. };
  38892. /**
  38893. * Updates a particle : this function should be overwritten by the user.
  38894. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38895. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38896. * ex : just set a particle position or velocity and recycle conditions
  38897. */
  38898. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38899. return particle;
  38900. };
  38901. /**
  38902. * Updates a vertex of a particle : it can be overwritten by the user.
  38903. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38904. * @param particle the current particle
  38905. * @param vertex the current index of the current particle
  38906. * @param pt the index of the current vertex in the particle shape
  38907. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38908. * ex : just set a vertex particle position
  38909. */
  38910. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38911. return vertex;
  38912. };
  38913. /**
  38914. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38915. * This does nothing and may be overwritten by the user.
  38916. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38917. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38918. * @param update the boolean update value actually passed to setParticles()
  38919. */
  38920. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38921. };
  38922. /**
  38923. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38924. * This will be passed three parameters.
  38925. * This does nothing and may be overwritten by the user.
  38926. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38927. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38928. * @param update the boolean update value actually passed to setParticles()
  38929. */
  38930. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38931. };
  38932. return SolidParticleSystem;
  38933. })();
  38934. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38935. })(BABYLON || (BABYLON = {}));
  38936. var BABYLON;
  38937. (function (BABYLON) {
  38938. var Internals;
  38939. (function (Internals) {
  38940. var FileFaceOrientation = (function () {
  38941. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38942. this.name = name;
  38943. this.worldAxisForNormal = worldAxisForNormal;
  38944. this.worldAxisForFileX = worldAxisForFileX;
  38945. this.worldAxisForFileY = worldAxisForFileY;
  38946. }
  38947. return FileFaceOrientation;
  38948. })();
  38949. ;
  38950. var CubeMapToSphericalPolynomialTools = (function () {
  38951. function CubeMapToSphericalPolynomialTools() {
  38952. }
  38953. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38954. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38955. var totalSolidAngle = 0.0;
  38956. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38957. var du = 2.0 / cubeInfo.size;
  38958. var dv = du;
  38959. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38960. var minUV = du * 0.5 - 1.0;
  38961. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38962. var fileFace = this.FileFaces[faceIndex];
  38963. var dataArray = cubeInfo[fileFace.name];
  38964. var v = minUV;
  38965. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38966. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38967. // Because SP is still linear, so summation is fine in that basis.
  38968. for (var y = 0; y < cubeInfo.size; y++) {
  38969. var u = minUV;
  38970. for (var x = 0; x < cubeInfo.size; x++) {
  38971. // World direction (not normalised)
  38972. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38973. worldDirection.normalize();
  38974. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38975. if (1) {
  38976. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38977. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38978. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38979. var color = new BABYLON.Color3(r, g, b);
  38980. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38981. }
  38982. else {
  38983. if (faceIndex == 0) {
  38984. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38985. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38986. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38987. }
  38988. else if (faceIndex == 1) {
  38989. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38990. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38991. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38992. }
  38993. else if (faceIndex == 2) {
  38994. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38995. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38996. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38997. }
  38998. else if (faceIndex == 3) {
  38999. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  39000. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  39001. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  39002. }
  39003. else if (faceIndex == 4) {
  39004. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  39005. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  39006. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  39007. }
  39008. else if (faceIndex == 5) {
  39009. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  39010. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  39011. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  39012. }
  39013. 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]);
  39014. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  39015. }
  39016. totalSolidAngle += deltaSolidAngle;
  39017. u += du;
  39018. }
  39019. v += dv;
  39020. }
  39021. }
  39022. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  39023. var correction = correctSolidAngle / totalSolidAngle;
  39024. sphericalHarmonics.scale(correction);
  39025. // Additionally scale by pi -- audit needed
  39026. sphericalHarmonics.scale(1.0 / Math.PI);
  39027. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  39028. };
  39029. CubeMapToSphericalPolynomialTools.FileFaces = [
  39030. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  39031. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  39032. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  39033. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  39034. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  39035. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  39036. ];
  39037. return CubeMapToSphericalPolynomialTools;
  39038. })();
  39039. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  39040. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39041. })(BABYLON || (BABYLON = {}));
  39042. var BABYLON;
  39043. (function (BABYLON) {
  39044. var Internals;
  39045. (function (Internals) {
  39046. var PanoramaToCubeMapTools = (function () {
  39047. function PanoramaToCubeMapTools() {
  39048. }
  39049. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  39050. if (!float32Array) {
  39051. throw "ConvertPanoramaToCubemap: input cannot be null";
  39052. }
  39053. if (float32Array.length != inputWidth * inputHeight * 3) {
  39054. throw "ConvertPanoramaToCubemap: input size is wrong";
  39055. }
  39056. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  39057. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  39058. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  39059. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  39060. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  39061. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  39062. return {
  39063. front: textureFront,
  39064. back: textureBack,
  39065. left: textureLeft,
  39066. right: textureRight,
  39067. up: textureUp,
  39068. down: textureDown,
  39069. size: size
  39070. };
  39071. };
  39072. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  39073. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  39074. var textureArray = new Float32Array(buffer);
  39075. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  39076. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  39077. var dy = 1 / texSize;
  39078. var fy = 0;
  39079. for (var y = 0; y < texSize; y++) {
  39080. var xv1 = faceData[0];
  39081. var xv2 = faceData[2];
  39082. for (var x = 0; x < texSize; x++) {
  39083. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  39084. v.normalize();
  39085. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  39086. // 3 channels per pixels
  39087. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  39088. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  39089. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  39090. xv1 = xv1.add(rotDX1);
  39091. xv2 = xv2.add(rotDX2);
  39092. }
  39093. fy += dy;
  39094. }
  39095. return textureArray;
  39096. };
  39097. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  39098. var theta = Math.atan2(vDir.z, vDir.x);
  39099. var phi = Math.acos(vDir.y);
  39100. while (theta < -Math.PI)
  39101. theta += 2 * Math.PI;
  39102. while (theta > Math.PI)
  39103. theta -= 2 * Math.PI;
  39104. var dx = theta / Math.PI;
  39105. var dy = phi / Math.PI;
  39106. // recenter.
  39107. dx = dx * 0.5 + 0.5;
  39108. var px = Math.round(dx * inputWidth);
  39109. if (px < 0)
  39110. px = 0;
  39111. else if (px >= inputWidth)
  39112. px = inputWidth - 1;
  39113. var py = Math.round(dy * inputHeight);
  39114. if (py < 0)
  39115. py = 0;
  39116. else if (py >= inputHeight)
  39117. py = inputHeight - 1;
  39118. var inputY = (inputHeight - py - 1);
  39119. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  39120. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  39121. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  39122. return {
  39123. r: r,
  39124. g: g,
  39125. b: b
  39126. };
  39127. };
  39128. PanoramaToCubeMapTools.FACE_FRONT = [
  39129. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39130. new BABYLON.Vector3(1.0, -1.0, -1.0),
  39131. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  39132. new BABYLON.Vector3(1.0, 1.0, -1.0)
  39133. ];
  39134. PanoramaToCubeMapTools.FACE_BACK = [
  39135. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39136. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39137. new BABYLON.Vector3(1.0, 1.0, 1.0),
  39138. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  39139. ];
  39140. PanoramaToCubeMapTools.FACE_LEFT = [
  39141. new BABYLON.Vector3(1.0, -1.0, -1.0),
  39142. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39143. new BABYLON.Vector3(1.0, 1.0, -1.0),
  39144. new BABYLON.Vector3(1.0, 1.0, 1.0)
  39145. ];
  39146. PanoramaToCubeMapTools.FACE_RIGHT = [
  39147. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39148. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39149. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  39150. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  39151. ];
  39152. PanoramaToCubeMapTools.FACE_UP = [
  39153. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  39154. new BABYLON.Vector3(1.0, 1.0, -1.0),
  39155. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  39156. new BABYLON.Vector3(1.0, 1.0, 1.0)
  39157. ];
  39158. PanoramaToCubeMapTools.FACE_DOWN = [
  39159. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39160. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39161. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39162. new BABYLON.Vector3(1.0, -1.0, -1.0)
  39163. ];
  39164. return PanoramaToCubeMapTools;
  39165. })();
  39166. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  39167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39168. })(BABYLON || (BABYLON = {}));
  39169. var BABYLON;
  39170. (function (BABYLON) {
  39171. var Internals;
  39172. (function (Internals) {
  39173. ;
  39174. var HDRTools = (function () {
  39175. function HDRTools() {
  39176. }
  39177. HDRTools.Ldexp = function (mantissa, exponent) {
  39178. if (exponent > 1023) {
  39179. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  39180. }
  39181. if (exponent < -1074) {
  39182. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  39183. }
  39184. return mantissa * Math.pow(2, exponent);
  39185. };
  39186. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  39187. if (exponent > 0) {
  39188. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  39189. float32array[index + 0] = red * exponent;
  39190. float32array[index + 1] = green * exponent;
  39191. float32array[index + 2] = blue * exponent;
  39192. }
  39193. else {
  39194. float32array[index + 0] = 0;
  39195. float32array[index + 1] = 0;
  39196. float32array[index + 2] = 0;
  39197. }
  39198. };
  39199. HDRTools.readStringLine = function (uint8array, startIndex) {
  39200. var line = "";
  39201. var character = "";
  39202. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  39203. character = String.fromCharCode(uint8array[i]);
  39204. if (character == "\n") {
  39205. break;
  39206. }
  39207. line += character;
  39208. }
  39209. return line;
  39210. };
  39211. /* minimal header reading. modify if you want to parse more information */
  39212. HDRTools.RGBE_ReadHeader = function (uint8array) {
  39213. var height = 0;
  39214. var width = 0;
  39215. var line = this.readStringLine(uint8array, 0);
  39216. if (line[0] != '#' || line[1] != '?') {
  39217. throw "Bad HDR Format.";
  39218. }
  39219. var endOfHeader = false;
  39220. var findFormat = false;
  39221. var lineIndex = 0;
  39222. do {
  39223. lineIndex += (line.length + 1);
  39224. line = this.readStringLine(uint8array, lineIndex);
  39225. if (line == "FORMAT=32-bit_rle_rgbe") {
  39226. findFormat = true;
  39227. }
  39228. else if (line.length == 0) {
  39229. endOfHeader = true;
  39230. }
  39231. } while (!endOfHeader);
  39232. if (!findFormat) {
  39233. throw "HDR Bad header format, unsupported FORMAT";
  39234. }
  39235. lineIndex += (line.length + 1);
  39236. line = this.readStringLine(uint8array, lineIndex);
  39237. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  39238. var match = sizeRegexp.exec(line);
  39239. // TODO. Support +Y and -X if needed.
  39240. if (match.length < 3) {
  39241. throw "HDR Bad header format, no size";
  39242. }
  39243. width = parseInt(match[2]);
  39244. height = parseInt(match[1]);
  39245. if (width < 8 || width > 0x7fff) {
  39246. throw "HDR Bad header format, unsupported size";
  39247. }
  39248. lineIndex += (line.length + 1);
  39249. return {
  39250. height: height,
  39251. width: width,
  39252. dataPosition: lineIndex
  39253. };
  39254. };
  39255. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  39256. var uint8array = new Uint8Array(buffer);
  39257. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  39258. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  39259. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  39260. return cubeMapData;
  39261. };
  39262. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  39263. // Keep for multi format supports.
  39264. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  39265. };
  39266. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  39267. var num_scanlines = hdrInfo.height;
  39268. var scanline_width = hdrInfo.width;
  39269. var a, b, c, d, count;
  39270. var dataIndex = hdrInfo.dataPosition;
  39271. var index = 0, endIndex = 0, i = 0;
  39272. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  39273. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  39274. // 3 channels of 4 bytes per pixel in float.
  39275. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  39276. var resultArray = new Float32Array(resultBuffer);
  39277. // read in each successive scanline
  39278. while (num_scanlines > 0) {
  39279. a = uint8array[dataIndex++];
  39280. b = uint8array[dataIndex++];
  39281. c = uint8array[dataIndex++];
  39282. d = uint8array[dataIndex++];
  39283. if (a != 2 || b != 2 || (c & 0x80)) {
  39284. // this file is not run length encoded
  39285. throw "HDR Bad header format, not RLE";
  39286. }
  39287. if (((c << 8) | d) != scanline_width) {
  39288. throw "HDR Bad header format, wrong scan line width";
  39289. }
  39290. index = 0;
  39291. // read each of the four channels for the scanline into the buffer
  39292. for (i = 0; i < 4; i++) {
  39293. endIndex = (i + 1) * scanline_width;
  39294. while (index < endIndex) {
  39295. a = uint8array[dataIndex++];
  39296. b = uint8array[dataIndex++];
  39297. if (a > 128) {
  39298. // a run of the same value
  39299. count = a - 128;
  39300. if ((count == 0) || (count > endIndex - index)) {
  39301. throw "HDR Bad Format, bad scanline data (run)";
  39302. }
  39303. while (count-- > 0) {
  39304. scanLineArray[index++] = b;
  39305. }
  39306. }
  39307. else {
  39308. // a non-run
  39309. count = a;
  39310. if ((count == 0) || (count > endIndex - index)) {
  39311. throw "HDR Bad Format, bad scanline data (non-run)";
  39312. }
  39313. scanLineArray[index++] = b;
  39314. if (--count > 0) {
  39315. for (var j = 0; j < count; j++) {
  39316. scanLineArray[index++] = uint8array[dataIndex++];
  39317. }
  39318. }
  39319. }
  39320. }
  39321. }
  39322. // now convert data from buffer into floats
  39323. for (i = 0; i < scanline_width; i++) {
  39324. a = scanLineArray[i];
  39325. b = scanLineArray[i + scanline_width];
  39326. c = scanLineArray[i + 2 * scanline_width];
  39327. d = scanLineArray[i + 3 * scanline_width];
  39328. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  39329. }
  39330. num_scanlines--;
  39331. }
  39332. return resultArray;
  39333. };
  39334. return HDRTools;
  39335. })();
  39336. Internals.HDRTools = HDRTools;
  39337. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39338. })(BABYLON || (BABYLON = {}));
  39339. var BABYLON;
  39340. (function (BABYLON) {
  39341. var Internals;
  39342. (function (Internals) {
  39343. var PMREMGenerator = (function () {
  39344. function PMREMGenerator() {
  39345. }
  39346. return PMREMGenerator;
  39347. })();
  39348. Internals.PMREMGenerator = PMREMGenerator;
  39349. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39350. })(BABYLON || (BABYLON = {}));
  39351. var BABYLON;
  39352. (function (BABYLON) {
  39353. var HDRCubeTexture = (function (_super) {
  39354. __extends(HDRCubeTexture, _super);
  39355. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace) {
  39356. if (noMipmap === void 0) { noMipmap = false; }
  39357. if (generateHarmonics === void 0) { generateHarmonics = true; }
  39358. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  39359. _super.call(this, scene);
  39360. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  39361. this._useInGammaSpace = false;
  39362. this._generateHarmonics = true;
  39363. this.sphericalPolynomial = null;
  39364. this.name = url;
  39365. this.url = url;
  39366. this._noMipmap = noMipmap;
  39367. this.hasAlpha = false;
  39368. this._size = size;
  39369. this._useInGammaSpace = useInGammaSpace;
  39370. if (!url) {
  39371. return;
  39372. }
  39373. this._texture = this._getFromCache(url, noMipmap);
  39374. if (!this._texture) {
  39375. if (!scene.useDelayedTextureLoading) {
  39376. this.loadTexture();
  39377. }
  39378. else {
  39379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39380. }
  39381. }
  39382. this.isCube = true;
  39383. this._textureMatrix = BABYLON.Matrix.Identity();
  39384. }
  39385. HDRCubeTexture.prototype.loadTexture = function () {
  39386. var _this = this;
  39387. var callback = function (buffer) {
  39388. // Extract the raw linear data.
  39389. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  39390. // Generate harmonics if needed.
  39391. if (_this._generateHarmonics) {
  39392. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  39393. }
  39394. var results = [];
  39395. var byteArray = null;
  39396. // Create uintarray fallback.
  39397. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  39398. // 3 channels of 1 bytes per pixel in bytes.
  39399. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  39400. byteArray = new Uint8Array(byteBuffer);
  39401. }
  39402. // Push each faces.
  39403. for (var j = 0; j < 6; j++) {
  39404. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  39405. // If special cases.
  39406. if (_this._useInGammaSpace || byteArray) {
  39407. for (var i = 0; i < _this._size * _this._size; i++) {
  39408. // Put in gamma space if requested.
  39409. if (_this._useInGammaSpace) {
  39410. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  39411. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  39412. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  39413. }
  39414. // Convert to int texture for fallback.
  39415. if (byteArray) {
  39416. // R
  39417. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  39418. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  39419. // G
  39420. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  39421. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  39422. // B
  39423. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  39424. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  39425. }
  39426. }
  39427. }
  39428. results.push(dataFace);
  39429. }
  39430. return results;
  39431. };
  39432. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  39433. };
  39434. HDRCubeTexture.prototype.clone = function () {
  39435. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace);
  39436. // Base texture
  39437. newTexture.level = this.level;
  39438. newTexture.wrapU = this.wrapU;
  39439. newTexture.wrapV = this.wrapV;
  39440. newTexture.coordinatesIndex = this.coordinatesIndex;
  39441. newTexture.coordinatesMode = this.coordinatesMode;
  39442. return newTexture;
  39443. };
  39444. // Methods
  39445. HDRCubeTexture.prototype.delayLoad = function () {
  39446. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39447. return;
  39448. }
  39449. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39450. this._texture = this._getFromCache(this.url, this._noMipmap);
  39451. if (!this._texture) {
  39452. this.loadTexture();
  39453. }
  39454. };
  39455. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  39456. return this._textureMatrix;
  39457. };
  39458. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39459. var texture = null;
  39460. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39461. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace);
  39462. texture.name = parsedTexture.name;
  39463. texture.hasAlpha = parsedTexture.hasAlpha;
  39464. texture.level = parsedTexture.level;
  39465. texture.coordinatesMode = parsedTexture.coordinatesMode;
  39466. }
  39467. return texture;
  39468. };
  39469. HDRCubeTexture.prototype.serialize = function () {
  39470. if (!this.name) {
  39471. return null;
  39472. }
  39473. var serializationObject = {};
  39474. serializationObject.name = this.name;
  39475. serializationObject.hasAlpha = this.hasAlpha;
  39476. serializationObject.isCube = true;
  39477. serializationObject.level = this.level;
  39478. serializationObject.size = this._size;
  39479. serializationObject.coordinatesMode = this.coordinatesMode;
  39480. serializationObject.useInGammaSpace = this._useInGammaSpace;
  39481. serializationObject.generateHarmonics = this._generateHarmonics;
  39482. return serializationObject;
  39483. };
  39484. HDRCubeTexture._facesMapping = [
  39485. "left",
  39486. "down",
  39487. "front",
  39488. "right",
  39489. "up",
  39490. "back"
  39491. ];
  39492. return HDRCubeTexture;
  39493. })(BABYLON.BaseTexture);
  39494. BABYLON.HDRCubeTexture = HDRCubeTexture;
  39495. })(BABYLON || (BABYLON = {}));
  39496. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}","blackAndWhitePixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}","blurPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n gl_FragColor = baseColor;\n}","chromaticAberrationPixelShader":"precision highp float;\n\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n vec4 original = texture2D(textureSampler, vUV);\n if (chromatic_aberration > 0.0) {\n \n vec3 ref_indices = vec3(-0.3, 0.0, 0.3);\n float ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n \n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n gl_FragColor = original;\n}","colorPixelShader":"precision highp float;\nuniform vec4 color;\nvoid main(void) {\n gl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"precision highp float;\n\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; \n float slicePixelSize = sliceSize / width; \n float sliceInnerSize = slicePixelSize * (width - 1.0); \n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n}","convolutionPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<light0FragmentDeclaration>\n#include<light1FragmentDeclaration>\n#include<light2FragmentDeclaration>\n#include<light3FragmentDeclaration>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n \n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n \n float alpha = vDiffuseColor.a;\n \n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n#ifdef DIFFUSE\n vec2 diffuseUV = vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, diffuseUV);\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n \n vec3 baseAmbientColor = vec3(1., 1., 1.);\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n \n#ifdef SPECULARTERM\n float glossiness = vSpecularColor.a;\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n vec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\n specularColor = specularMapColor.rgb;\n#ifdef GLOSSINESS\n glossiness = glossiness * specularMapColor.a;\n#endif\n#endif\n#else\n float glossiness = 0.;\n#endif\n \n vec3 diffuseBase = vec3(0., 0., 0.);\n#ifdef SPECULARTERM\n vec3 specularBase = vec3(0., 0., 0.);\n#endif\n float shadow = 1.;\n#include<light0Fragment>\n#include<light1Fragment>\n#include<light2Fragment>\n#include<light3Fragment>\n \n vec3 refractionColor = vec3(0., 0., 0.);\n#ifdef REFRACTION\n vec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n refractionVector.y = refractionVector.y * vRefractionInfos.w;\n if (dot(refractionVector, viewDirectionW) < 1.0)\n {\n refractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\n }\n#else\n vec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\n vec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\n refractionCoords.y = 1.0 - refractionCoords.y;\n refractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\n#endif\n#endif\n \n vec3 reflectionColor = vec3(0., 0., 0.);\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\n float bias = vReflectionInfos.y;\n #ifdef SPECULARTERM\n #ifdef SPECULAR\n #ifdef GLOSSINESS\n bias *= (1.0 - specularMapColor.a);\n #endif\n #endif\n #endif\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\n#else\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\n#endif\n#else\n vec2 coords = vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\n coords /= vReflectionUVW.z;\n#endif\n coords.y = 1.0 - coords.y;\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\n reflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#else\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#else\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\n float refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\n refractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n \n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n \n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n \n#ifdef EMISSIVEASILLUMINATION\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\n vec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n#else\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\n vec3 finalSpecular = specularBase * specularColor;\n#else\n vec3 finalSpecular = vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\n alpha = clamp(alpha + dot(reflectionColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n \n#ifdef EMISSIVEASILLUMINATION\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\n#else\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\n#endif\n#ifdef LIGHTMAP\n vec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\n color.rgb *= lightmapColor;\n#else\n color.rgb += lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n gl_FragColor = color;\n}","defaultVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n vPositionUVW = position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\n vDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\n#endif\n \n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef LIGHTMAP\n if (vLightmapInfos.x == 0.)\n {\n vLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n \n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"precision highp float;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}","depthVertexShader":"precision highp float;\n\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}","depthOfFieldPixelShader":"\n\n\n\nprecision highp float;\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\n if (distortion == 0.0) { return coords; }\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n dist_coords = mix(coords, dist_coords, dist_amount);\n return dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\n \n vec2 coords = distorted_coords;\n float angle = rand(coords * 100.0).x * TWOPI;\n coords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\n color += texture2D(textureSampler, coords)*weight;\n return weight;\n}\n\nfloat getBlurLevel(float size) {\n return min(3.0, ceil(size / 1.0));\n}\n\nvec4 getBlurColor(float size) {\n vec4 col = texture2D(textureSampler, distorted_coords);\n if (size == 0.0) { return col; }\n \n \n float blur_level = getBlurLevel(size);\n float w = (size / screen_width);\n float h = (size / screen_height);\n float total_weight = 1.0;\n vec2 sample_coords;\n total_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\n total_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\n total_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\n total_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\n total_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\n total_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\n total_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\n total_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\n total_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\n total_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\n if (blur_level > 1.0) {\n total_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\n total_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\n total_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\n total_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\n total_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\n total_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\n total_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\n total_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\n total_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\n total_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\n }\n if (blur_level > 2.0) {\n total_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\n total_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\n total_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\n total_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\n total_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\n total_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\n total_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\n total_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\n total_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\n }\n col /= total_weight; \n \n if (darken > 0.0) {\n col.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\n }\n \n \n \n \n return col;\n}\nvoid main(void)\n{\n \n centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n distorted_coords = getDistortedCoords(vUV); \n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); \n float depth = texture2D(depthSampler, distorted_coords).r; \n float distance = near + (far - near)*depth; \n vec4 color = texture2D(textureSampler, vUV); \n \n \n float coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\n \n if (dof_enabled == false || coc < 0.07) { coc = 0.0; }\n \n float edge_blur_amount = 0.0;\n if (edge_blur > 0.0) {\n edge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n }\n \n float blur_amount = max(edge_blur_amount, coc);\n \n if (blur_amount == 0.0) {\n gl_FragColor = texture2D(textureSampler, distorted_coords);\n }\n else {\n \n gl_FragColor = getBlurColor(blur_amount * 1.7);\n \n if (highlights) {\n gl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\n }\n if (blur_noise) {\n \n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n }\n }\n \n if (grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\n }\n}\n","displayPassPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}","filterPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n gl_FragColor = vec4(updatedColor, 1.0);\n}","fxaaPixelShader":"precision highp float;\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}","hdrPixelShader":"precision highp float;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\n vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n for (int i = 0; i < 9; i++) {\n #ifdef GAUSSIAN_BLUR_H\n color += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\n #else\n color += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\n #endif\n }\n color.a = 1.0;\n gl_FragColor = color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\n vec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\n sum.a = clamp(sum.a, 0.0, 1.0);\n gl_FragColor = sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\n float average = 0.0;\n vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n float maximum = -1e20;\n for (int i = 0; i < 4; i++) {\n color = texture2D(textureSampler, vUV + lumOffsets[i]);\n float GreyValue = length(color.rgb);\n maximum = max(maximum, GreyValue);\n average += (0.25 * log(1e-5 + GreyValue));\n }\n average = exp(average);\n gl_FragColor = vec4(average, maximum, 0.0, 1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n vec4 res = fract(value * bit_shift);\n res -= res.xxyz * bit_mask;\n return res;\n}\n#endif\nvoid main() {\n vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n float average = 0.0;\n for (int i = 0; i < 9; i++) {\n color = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\n average += color.r;\n }\n average /= 9.0;\n #ifndef FINAL_DOWN_SAMPLE\n gl_FragColor = vec4(average, average, 0.0, 1.0);\n #else\n gl_FragColor = pack(average);\n #endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\n vec4 average = vec4(0.0, 0.0, 0.0, 0.0);\n average = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\n average += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\n average += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\n average += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\n average *= 0.25;\n float luminance = length(average.rgb);\n if (luminance < brightThreshold) {\n average = vec4(0.0, 0.0, 0.0, 1.0);\n }\n gl_FragColor = average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\n vec4 average = vec4(0.0, 0.0, 0.0, 0.0);\n average = texture2D(textureSampler, vUV + dsOffsets[0]);\n average += texture2D(textureSampler, vUV + dsOffsets[1]);\n average += texture2D(textureSampler, vUV + dsOffsets[2]);\n average += texture2D(textureSampler, vUV + dsOffsets[3]);\n average += texture2D(textureSampler, vUV + dsOffsets[4]);\n average += texture2D(textureSampler, vUV + dsOffsets[5]);\n average += texture2D(textureSampler, vUV + dsOffsets[6]);\n average += texture2D(textureSampler, vUV + dsOffsets[7]);\n average += texture2D(textureSampler, vUV + dsOffsets[8]);\n average += texture2D(textureSampler, vUV + dsOffsets[9]);\n average += texture2D(textureSampler, vUV + dsOffsets[10]);\n average += texture2D(textureSampler, vUV + dsOffsets[11]);\n average += texture2D(textureSampler, vUV + dsOffsets[12]);\n average += texture2D(textureSampler, vUV + dsOffsets[13]);\n average += texture2D(textureSampler, vUV + dsOffsets[14]);\n average += texture2D(textureSampler, vUV + dsOffsets[15]);\n average /= 16.0;\n gl_FragColor = average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\n vec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\n vec4 adjustedColor = color / avgLuminance * exposure;\n color = adjustedColor;\n color.a = 1.0;\n gl_FragColor = color;\n}\n#endif\n","layerPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n gl_FragColor = baseColor * color;\n}","layerVertexShader":"precision highp float;\n\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd = vec2(0.5, 0.5);\nvoid main(void) { \n vec2 shiftedPosition = position * scale + offset;\n vUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\n gl_Position = vec4(shiftedPosition, 0.0, 1.0);\n}","legacydefaultPixelShader":"precision highp float;\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<light0FragmentDeclaration>\n#include<light1FragmentDeclaration>\n#include<light2FragmentDeclaration>\n#include<light3FragmentDeclaration>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n \n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n \n vec3 normalW = normalize(vNormalW);\n \n vec3 baseAmbientColor = vec3(1., 1., 1.);\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n \n vec3 diffuseBase = vec3(0., 0., 0.);\n float glossiness = 0.;\n#ifdef SPECULARTERM\n vec3 specularBase = vec3(0., 0., 0.);\n glossiness = vSpecularColor.a;\n#endif\n float shadow = 1.;\n#include<light0Fragment>\n#include<light1Fragment>\n#include<light2Fragment>\n#include<light3Fragment>\n \n vec3 reflectionColor = vec3(0., 0., 0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\n#else\n vec2 coords = vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\n coords /= vReflectionUVW.z;\n#endif\n coords.y = 1.0 - coords.y;\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n \n float alpha = vDiffuseColor.a;\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n \n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n \n#ifdef SPECULARTERM\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n#endif\n \n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n \n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n#ifdef SPECULARTERM\n vec3 finalSpecular = specularBase * specularColor;\n#else\n vec3 finalSpecular = vec3(0.0);\n#endif\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n#include<fogFragment>\n gl_FragColor = color;\n}","legacydefaultVertexShader":"precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n return vec3(reflectionMatrix * vec4(coords, 1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n#ifdef INVERTCUBICMAP\n coords.y = 1.0 - coords.y;\n#endif\n return vec3(reflectionMatrix * vec4(coords, 0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\n return vec3(reflectionMatrix * (view * worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\n return position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\n return vec3(0, 0, 0);\n#endif\n}\n#endif\nvoid main(void) {\n mat4 finalWorld = world;\n#include<bonesVertex>\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n \n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\n#endif\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n \n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}","lensFlarePixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n gl_FragColor = baseColor * color;\n}","lensFlareVertexShader":"precision highp float;\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd = vec2(0.5, 0.5);\nvoid main(void) { \n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}","lensHighlightsPixelShader":"precision highp float;\n\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\n vec4 highlight = color;\n float luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n luminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n highlight *= luminance * gain;\n highlight.a = 1.0;\n return highlight;\n}\nvoid main(void)\n{\n vec4 original = texture2D(textureSampler, vUV);\n \n if (gain == -1.0) {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n return;\n }\n float w = 2.0 / screen_width;\n float h = 2.0 / screen_height;\n float weight = 1.0;\n \n vec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n#ifdef PENTAGON\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n#else\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\n blurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n#endif\n blurred /= 39.0;\n gl_FragColor = blurred;\n \n}","linePixelShader":"precision highp float;\nuniform vec4 color;\nvoid main(void) {\n gl_FragColor = color;\n}","lineVertexShader":"precision highp float;\n\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\n vec4 viewPosition = worldViewProjection * vec4(position, 1.0);\n vec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\n vec2 currentScreen = viewPosition.xy / viewPosition.w;\n vec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\n currentScreen.x *= aspectRatio;\n nextScreen.x *= aspectRatio;\n vec2 dir = normalize(nextScreen - currentScreen);\n vec2 normalDir = vec2(-dir.y, dir.x);\n normalDir *= width / 2.0;\n normalDir.x /= aspectRatio;\n vec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\n gl_Position = viewPosition + offset;\n}","outlinePixelShader":"precision highp float;\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n gl_FragColor = color;\n}","outlineVertexShader":"precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n vec3 offsetPosition = position + normal * offset;\n#include<instancesVertex>\n#include<bonesVertex>\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}","particlesVertexShader":"precision highp float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n \n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n \n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n vColor = color;\n vUV = offset;\n \n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}","passPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}","postprocessVertexShader":"precision highp float;\n\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd = vec2(0.5, 0.5);\nvoid main(void) { \n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}","proceduralVertexShader":"precision highp float;\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd = vec2(0.5, 0.5);\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}","refractionPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}","shadowMapPixelShader":"precision highp float;\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n return res;\n}\n\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n return color - (color.yy * bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n#ifdef CUBEMAP\n vec3 directionToLight = vPosition.xyz - lightPosition;\n float depth = length(directionToLight);\n depth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\n depth = clamp(depth, 0., 1.0);\n#else\n float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n#endif\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}","shadowMapVertexShader":"precision highp float;\n\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\n vPosition = finalWorld * vec4(position, 1.0);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}","spritesPixelShader":"precision highp float;\nuniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n vec4 color = texture2D(diffuseSampler, vUV);\n if (alphaTest) \n {\n if (color.a < 0.95)\n discard;\n }\n color *= vColor;\n#include<fogFragment>\n gl_FragColor = color;\n}","spritesVertexShader":"precision highp float;\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \n vec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \n vec2 cornerPos;\n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n \n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n \n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n \n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n \n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}","ssaoPixelShader":"precision highp float;\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth, vec2 coords) {\n vec2 offset1 = vec2(0.0, radius);\n vec2 offset2 = vec2(radius, 0.0);\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n return normalize(normal);\n}\nvoid main()\n{\n vec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + sign(dot(ray, normal)) * ray;\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\n difference = depth - occlusionDepth;\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}\n","ssaoCombinePixelShader":"precision highp float;\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\n vec4 ssaoColor = texture2D(textureSampler, vUV);\n vec4 sceneColor = texture2D(originalColor, vUV);\n gl_FragColor = sceneColor * ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"precision highp float;\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\n bool useCamB;\n vec2 texCoord1;\n vec2 texCoord2;\n vec3 frag1;\n vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\n useCamB = vUV.x > 0.5;\n texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\n texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\n#else\n useCamB = vUV.y > 0.5;\n texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\n texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\n#endif\n \n if (useCamB){\n frag1 = texture2D(textureSampler, texCoord1).rgb;\n frag2 = texture2D(textureSampler, texCoord2).rgb;\n }else{\n frag1 = texture2D(camASampler , texCoord1).rgb;\n frag2 = texture2D(camASampler , texCoord2).rgb;\n }\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\n}","tonemapPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\n const float A = 0.15;\n const float B = 0.50;\n const float C = 0.10;\n const float D = 0.20;\n const float E = 0.02;\n const float F = 0.30;\n const float W = 11.2;\n#endif\nfloat Luminance(vec3 c)\n{\n return dot(c, vec3(0.22, 0.707, 0.071));\n}\nvoid main(void) \n{\n vec3 colour = texture2D(textureSampler, vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\n float lum = Luminance(colour.rgb); \n float lumTm = lum * _ExposureAdjustment;\n float scale = lumTm / (1.0 + lumTm); \n colour *= scale / lum;\n#elif defined(HABLE_TONEMAPPING)\n colour *= _ExposureAdjustment;\n const float ExposureBias = 2.0;\n vec3 x = ExposureBias * colour;\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\n x = vec3(W, W, W);\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\n colour = curr * whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\n colour *= _ExposureAdjustment;\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\n colour = retColor * retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\n#endif\n gl_FragColor = vec4(colour.rgb, 1.0);\n}","volumetricLightScatteringPixelShader":"precision highp float;\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n float illuminationDecay = 1.0;\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"precision highp float;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n#ifdef OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #elif defined(DIFFUSE_COLOR_RENDER)\n gl_FragColor = vec4(color.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n gl_FragColor.a = alpha;\n#else\n #if defined(BASIC_RENDER)\n gl_FragColor = diffuseColor;\n #elif defined(DIFFUSE_COLOR_RENDER)\n gl_FragColor = vec4(color.rgb, 1.0);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"precision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\n vec2 theta = (in01 - LensCenter) * ScaleIn; \n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}"};
  39497. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS > 0\n uniform mat4 mBones[BonesPerMesh];\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #if NUM_BONE_INFLUENCERS > 4\n attribute vec4 matricesIndicesExtra;\n attribute vec4 matricesWeightsExtra;\n #endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS > 0\n mat4 influence;\n influence = mBones[int(matricesIndices[0])] * matricesWeights[0];\n #if NUM_BONE_INFLUENCERS > 1\n influence += mBones[int(matricesIndices[1])] * matricesWeights[1];\n #endif \n #if NUM_BONE_INFLUENCERS > 2\n influence += mBones[int(matricesIndices[2])] * matricesWeights[2];\n #endif \n #if NUM_BONE_INFLUENCERS > 3\n influence += mBones[int(matricesIndices[3])] * matricesWeights[3];\n #endif \n #if NUM_BONE_INFLUENCERS > 4\n influence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\n #endif \n #if NUM_BONE_INFLUENCERS > 5\n influence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\n #endif \n #if NUM_BONE_INFLUENCERS > 6\n influence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\n #endif \n #if NUM_BONE_INFLUENCERS > 7\n influence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\n #endif \n finalWorld = finalWorld * influence;\n#endif","bumpFragment":"#ifdef BUMP\n vec2 bumpUV = vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\n mat3 TBN = cotangent_frame(normalW * vBumpInfos.y, -viewDirectionW, bumpUV);\n#endif\n#ifdef PARALLAX\n mat3 invTBN = transposeMat3(TBN);\n #ifdef PARALLAXOCCLUSION\n vec2 uvOffset = parallaxOcclusion(invTBN * -viewDirectionW, invTBN * normalW, bumpUV, vBumpInfos.z);\n #else\n vec2 uvOffset = parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z);\n #endif\n diffuseUV += uvOffset;\n bumpUV += uvOffset;\n \n #ifdef PARALLAXOCCLUSION\n if (diffuseUV.x > 1.0 || diffuseUV.y > 1.0 || diffuseUV.x < 0.0 || diffuseUV.y < 0.0) {\n discard;\n }\n #endif\n#endif\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW, TBN, bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\n varying vec2 vBumpUV;\n uniform vec3 vBumpInfos;\n uniform sampler2D bumpSampler;\n \n mat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n {\n \n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n \n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n }\n vec3 perturbNormal(vec3 viewDir, mat3 cotangentFrame, vec2 uv)\n {\n vec3 map = texture2D(bumpSampler, uv).xyz;\n map = map * 255. / 127. - 128. / 127.;\n return normalize(cotangentFrame * map);\n }\n #ifdef PARALLAX\n const float minSamples = 4.;\n const float maxSamples = 15.;\n const int iMaxSamples = 15;\n \n vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale) {\n float parallaxLimit = length(vViewDirCoT.xy) / vViewDirCoT.z;\n parallaxLimit *= parallaxScale;\n vec2 vOffsetDir = normalize(vViewDirCoT.xy);\n vec2 vMaxOffset = vOffsetDir * parallaxLimit;\n float numSamples = maxSamples + (dot(vViewDirCoT, vNormalCoT) * (minSamples - maxSamples));\n float stepSize = 1.0 / numSamples;\n \n float currRayHeight = 1.0;\n vec2 vCurrOffset = vec2(0, 0);\n vec2 vLastOffset = vec2(0, 0);\n float lastSampledHeight = 1.0;\n float currSampledHeight = 1.0;\n for (int i = 0; i < iMaxSamples; i++)\n {\n currSampledHeight = texture2D(bumpSampler, vBumpUV + vCurrOffset).w;\n \n if (currSampledHeight > currRayHeight)\n {\n float delta1 = currSampledHeight - currRayHeight;\n float delta2 = (currRayHeight + stepSize) - lastSampledHeight;\n float ratio = delta1 / (delta1 + delta2);\n vCurrOffset = (ratio)* vLastOffset + (1.0 - ratio) * vCurrOffset;\n \n break;\n }\n else\n {\n currRayHeight -= stepSize;\n vLastOffset = vCurrOffset;\n vCurrOffset += stepSize * vMaxOffset;\n lastSampledHeight = currSampledHeight;\n }\n }\n return vCurrOffset;\n }\n vec2 parallaxOffset(vec3 viewDir, float heightScale)\n {\n \n float height = texture2D(bumpSampler, vBumpUV).w;\n vec2 texCoordOffset = heightScale * viewDir.xy * height;\n return -texCoordOffset;\n }\n #endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n {\n discard;\n }\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\n varying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\n uniform vec4 vClipPlane;\n varying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\n varying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\n float computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n {\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n }\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\n vec3 i0 = inMatrix[0];\n vec3 i1 = inMatrix[1];\n vec3 i2 = inMatrix[2];\n mat3 outMatrix = mat3(\n vec3(i0.x, i1.x, i2.x),\n vec3(i0.y, i1.y, i2.y),\n vec3(i0.z, i1.z, i2.z)\n );\n return outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\n attribute vec4 world0;\n attribute vec4 world1;\n attribute vec4 world2;\n attribute vec4 world3;\n#else\n uniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif","light0Fragment":"#ifdef LIGHT0\n #ifndef SPECULARTERM\n vec3 vLightSpecular0 = vec3(0.0);\n #endif\n #ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\n #endif\n #ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\n #endif\n #if defined(POINTLIGHT0) || defined(DIRLIGHT0)\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\n #endif\n #ifdef SHADOW0\n #ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\n #else\n #ifdef SHADOWPCF0\n #if defined(POINTLIGHT0)\n shadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\n #else\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\n #endif\n #else\n #if defined(POINTLIGHT0)\n shadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #endif\n #endif\n #endif\n #else\n shadow = 1.;\n #endif\n diffuseBase += info.diffuse * shadow;\n #ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n #endif\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\n uniform vec4 vLightData0;\n uniform vec4 vLightDiffuse0;\n #ifdef SPECULARTERM\n uniform vec3 vLightSpecular0;\n #endif\n #ifdef SHADOW0\n #if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\n varying vec4 vPositionFromLight0;\n uniform sampler2D shadowSampler0;\n #else\n uniform samplerCube shadowSampler0;\n #endif\n uniform vec3 shadowsInfo0;\n #endif\n #ifdef SPOTLIGHT0\n uniform vec4 vLightDirection0;\n #endif\n #ifdef HEMILIGHT0\n uniform vec3 vLightGround0;\n #endif\n#endif","light1Fragment":"#ifdef LIGHT1\n #ifndef SPECULARTERM\n vec3 vLightSpecular1 = vec3(0.0);\n #endif\n #ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\n #endif\n #ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\n #endif\n #if defined(POINTLIGHT1) || defined(DIRLIGHT1)\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\n #endif\n #ifdef SHADOW1\n #ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\n #else\n #ifdef SHADOWPCF1\n #if defined(POINTLIGHT1)\n shadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\n #else\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\n #endif\n #else\n #if defined(POINTLIGHT1)\n shadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #endif\n #endif\n #endif\n #else\n shadow = 1.;\n #endif\n diffuseBase += info.diffuse * shadow;\n #ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n #endif\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\n uniform vec4 vLightData1;\n uniform vec4 vLightDiffuse1;\n #ifdef SPECULARTERM\n uniform vec3 vLightSpecular1;\n #endif\n #ifdef SHADOW1\n #if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\n varying vec4 vPositionFromLight1;\n uniform sampler2D shadowSampler1;\n #else\n uniform samplerCube shadowSampler1;\n #endif\n uniform vec3 shadowsInfo1;\n #endif\n #ifdef SPOTLIGHT1\n uniform vec4 vLightDirection1;\n #endif\n #ifdef HEMILIGHT1\n uniform vec3 vLightGround1;\n #endif\n#endif","light2Fragment":"#ifdef LIGHT2\n #ifndef SPECULARTERM\n vec3 vLightSpecular2 = vec3(0.0);\n #endif\n #ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\n #endif\n #ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\n #endif\n #if defined(POINTLIGHT2) || defined(DIRLIGHT2)\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\n #endif\n #ifdef SHADOW2\n #ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\n #else\n #ifdef SHADOWPCF2\n #if defined(POINTLIGHT2)\n shadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\n #else\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\n #endif\n #else\n #if defined(POINTLIGHT2)\n shadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #endif\n #endif \n #endif \n #else\n shadow = 1.;\n #endif\n diffuseBase += info.diffuse * shadow;\n #ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n #endif\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\n uniform vec4 vLightData2;\n uniform vec4 vLightDiffuse2;\n #ifdef SPECULARTERM\n uniform vec3 vLightSpecular2;\n #endif\n #ifdef SHADOW2\n #if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\n varying vec4 vPositionFromLight2;\n uniform sampler2D shadowSampler2;\n #else\n uniform samplerCube shadowSampler2;\n #endif\n uniform vec3 shadowsInfo2;\n #endif\n #ifdef SPOTLIGHT2\n uniform vec4 vLightDirection2;\n #endif\n #ifdef HEMILIGHT2\n uniform vec3 vLightGround2;\n #endif\n#endif","light3Fragment":"#ifdef LIGHT3\n #ifndef SPECULARTERM\n vec3 vLightSpecular3 = vec3(0.0);\n #endif\n #ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\n #endif\n #ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\n #endif\n #if defined(POINTLIGHT3) || defined(DIRLIGHT3)\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\n #endif\n #ifdef SHADOW3\n #ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\n #else\n #ifdef SHADOWPCF3\n #if defined(POINTLIGHT3)\n shadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\n #else\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\n #endif\n #else\n #if defined(POINTLIGHT3)\n shadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #endif\n #endif \n #endif \n #else\n shadow = 1.;\n #endif\n diffuseBase += info.diffuse * shadow;\n #ifdef SPECULARTERM\n specularBase += info.specular * shadow;\n #endif\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\n uniform vec4 vLightData3;\n uniform vec4 vLightDiffuse3;\n #ifdef SPECULARTERM\n uniform vec3 vLightSpecular3;\n #endif\n #ifdef SHADOW3\n #if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\n varying vec4 vPositionFromLight3;\n uniform sampler2D shadowSampler3;\n #else\n uniform samplerCube shadowSampler3;\n #endif\n uniform vec3 shadowsInfo3;\n #endif\n #ifdef SPOTLIGHT3\n uniform vec4 vLightDirection3;\n #endif\n #ifdef HEMILIGHT3\n uniform vec3 vLightGround3;\n #endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\n vec3 diffuse;\n#ifdef SPECULARTERM\n vec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\n lightingInfo result;\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n \n float ndl = max(0., dot(vNormal, lightVectorW));\n result.diffuse = ndl * diffuseColor * attenuation;\n#ifdef SPECULARTERM\n \n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., glossiness));\n result.specular = specComp * specularColor * attenuation;\n#endif\n return result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\n lightingInfo result;\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n \n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n attenuation *= cosAngle;\n \n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n result.diffuse = ndl * diffuseColor * attenuation;\n#ifdef SPECULARTERM\n \n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., glossiness));\n result.specular = specComp * specularColor * attenuation;\n#endif\n return result;\n }\n result.diffuse = vec3(0.);\n#ifdef SPECULARTERM\n result.specular = vec3(0.);\n#endif\n return result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\n lightingInfo result;\n \n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n#ifdef SPECULARTERM\n \n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., glossiness));\n result.specular = specComp * specularColor;\n#endif\n return result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\n uniform float logarithmicDepthConstant;\n varying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\n gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\n vFragmentDepth = 1.0 + gl_Position.w;\n gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\n uniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\n vec3 direction = normalize(vDirectionW);\n float t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\n float s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\n return vec3(s, t, 0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\n vec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\n vec3 r = reflect(cameraToVertex, worldNormal);\n float t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\n float s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\n return vec3(s, t, 0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\n vec3 viewDir = normalize(vec3(view * worldPos));\n vec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\n vec3 r = reflect(viewDir, viewNormal);\n r.z = r.z - 1.0;\n float m = 2.0 * length(r);\n return vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n return vec3(reflectionMatrix * vec4(coords, 1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n#ifdef INVERTCUBICMAP\n coords.y = 1.0 - coords.y;\n#endif\n return vec3(reflectionMatrix * vec4(coords, 0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\n return vec3(reflectionMatrix * (view * worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\n return vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\n return vec3(0, 0, 0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n float unpack(vec4 color)\n {\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n }\n #if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\n uniform vec2 depthValues;\n float computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\n {\n vec3 directionToLight = vPositionW - lightPosition;\n float depth = length(directionToLight);\n depth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\n depth = clamp(depth, 0., 1.0);\n directionToLight = normalize(directionToLight);\n directionToLight.y = -directionToLight.y;\n float shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\n if (depth > shadow)\n {\n return darkness;\n }\n return 1.0;\n }\n float computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\n {\n vec3 directionToLight = vPositionW - lightPosition;\n float depth = length(directionToLight);\n depth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\n depth = clamp(depth, 0., 1.0);\n directionToLight = normalize(directionToLight);\n directionToLight.y = -directionToLight.y;\n float visibility = 1.;\n vec3 poissonDisk[4];\n poissonDisk[0] = vec3(-1.0, 1.0, -1.0);\n poissonDisk[1] = vec3(1.0, -1.0, -1.0);\n poissonDisk[2] = vec3(-1.0, -1.0, -1.0);\n poissonDisk[3] = vec3(1.0, -1.0, 1.0);\n \n float biasedDepth = depth - bias;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\n return min(1.0, visibility + darkness);\n }\n #endif\n #if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\n float computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n {\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n }\n float computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\n {\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n float visibility = 1.;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n \n float biasedDepth = depth.z - bias;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\n return min(1.0, visibility + darkness);\n }\n \n float unpackHalf(vec2 color)\n {\n return color.x + (color.y / 255.0);\n }\n float linstep(float low, float high, float v) {\n return clamp((v - low) / (high - low), 0.0, 1.0);\n }\n float ChebychevInequality(vec2 moments, float compare, float bias)\n {\n float p = smoothstep(compare - bias, compare, moments.x);\n float variance = max(moments.y - moments.x * moments.x, 0.02);\n float d = compare - moments.x;\n float p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n return clamp(max(p, p_max), 0.0, 1.0);\n }\n float computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\n {\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n {\n return 1.0;\n }\n vec4 texel = texture2D(shadowSampler, uv);\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\n }\n #endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n #if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\n vPositionFromLight0 = lightMatrix0 * worldPos;\n #endif\n #if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\n vPositionFromLight1 = lightMatrix1 * worldPos;\n #endif\n #if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\n vPositionFromLight2 = lightMatrix2 * worldPos;\n #endif\n #if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\n vPositionFromLight3 = lightMatrix3 * worldPos;\n #endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n #if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\n uniform mat4 lightMatrix0;\n varying vec4 vPositionFromLight0;\n #endif\n #if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\n uniform mat4 lightMatrix1;\n varying vec4 vPositionFromLight1;\n #endif\n #if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\n uniform mat4 lightMatrix2;\n varying vec4 vPositionFromLight2;\n #endif\n #if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\n uniform mat4 lightMatrix3;\n varying vec4 vPositionFromLight3;\n #endif\n#endif"};
  39498. 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={}));";
  39499. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  39500. module.exports = BABYLON;
  39501. };