babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614
  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. BABYLON.Epsilon = 0.001;
  12. var MathTools = (function () {
  13. function MathTools() {
  14. }
  15. MathTools.WithinEpsilon = function (a, b, epsilon) {
  16. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  17. var num = a - b;
  18. return -epsilon <= num && num <= epsilon;
  19. };
  20. MathTools.ToHex = function (i) {
  21. var str = i.toString(16);
  22. if (i <= 15) {
  23. return ("0" + str).toUpperCase();
  24. }
  25. return str.toUpperCase();
  26. };
  27. // Returns -1 when value is a negative number and
  28. // +1 when value is a positive number.
  29. MathTools.Sign = function (value) {
  30. value = +value; // convert to a number
  31. if (value === 0 || isNaN(value))
  32. return value;
  33. return value > 0 ? 1 : -1;
  34. };
  35. MathTools.Clamp = function (value, min, max) {
  36. if (min === void 0) { min = 0; }
  37. if (max === void 0) { max = 1; }
  38. return Math.min(max, Math.max(min, value));
  39. };
  40. return MathTools;
  41. })();
  42. BABYLON.MathTools = MathTools;
  43. var Color3 = (function () {
  44. function Color3(r, g, b) {
  45. if (r === void 0) { r = 0; }
  46. if (g === void 0) { g = 0; }
  47. if (b === void 0) { b = 0; }
  48. this.r = r;
  49. this.g = g;
  50. this.b = b;
  51. }
  52. Color3.prototype.toString = function () {
  53. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  54. };
  55. // Operators
  56. Color3.prototype.toArray = function (array, index) {
  57. if (index === undefined) {
  58. index = 0;
  59. }
  60. array[index] = this.r;
  61. array[index + 1] = this.g;
  62. array[index + 2] = this.b;
  63. return this;
  64. };
  65. Color3.prototype.toColor4 = function (alpha) {
  66. if (alpha === void 0) { alpha = 1; }
  67. return new Color4(this.r, this.g, this.b, alpha);
  68. };
  69. Color3.prototype.asArray = function () {
  70. var result = [];
  71. this.toArray(result, 0);
  72. return result;
  73. };
  74. Color3.prototype.toLuminance = function () {
  75. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  76. };
  77. Color3.prototype.multiply = function (otherColor) {
  78. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  79. };
  80. Color3.prototype.multiplyToRef = function (otherColor, result) {
  81. result.r = this.r * otherColor.r;
  82. result.g = this.g * otherColor.g;
  83. result.b = this.b * otherColor.b;
  84. return this;
  85. };
  86. Color3.prototype.equals = function (otherColor) {
  87. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  88. };
  89. Color3.prototype.equalsFloats = function (r, g, b) {
  90. return this.r === r && this.g === g && this.b === b;
  91. };
  92. Color3.prototype.scale = function (scale) {
  93. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  94. };
  95. Color3.prototype.scaleToRef = function (scale, result) {
  96. result.r = this.r * scale;
  97. result.g = this.g * scale;
  98. result.b = this.b * scale;
  99. return this;
  100. };
  101. Color3.prototype.add = function (otherColor) {
  102. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  103. };
  104. Color3.prototype.addToRef = function (otherColor, result) {
  105. result.r = this.r + otherColor.r;
  106. result.g = this.g + otherColor.g;
  107. result.b = this.b + otherColor.b;
  108. return this;
  109. };
  110. Color3.prototype.subtract = function (otherColor) {
  111. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  112. };
  113. Color3.prototype.subtractToRef = function (otherColor, result) {
  114. result.r = this.r - otherColor.r;
  115. result.g = this.g - otherColor.g;
  116. result.b = this.b - otherColor.b;
  117. return this;
  118. };
  119. Color3.prototype.clone = function () {
  120. return new Color3(this.r, this.g, this.b);
  121. };
  122. Color3.prototype.copyFrom = function (source) {
  123. this.r = source.r;
  124. this.g = source.g;
  125. this.b = source.b;
  126. return this;
  127. };
  128. Color3.prototype.copyFromFloats = function (r, g, b) {
  129. this.r = r;
  130. this.g = g;
  131. this.b = b;
  132. return this;
  133. };
  134. Color3.prototype.toHexString = function () {
  135. var intR = (this.r * 255) | 0;
  136. var intG = (this.g * 255) | 0;
  137. var intB = (this.b * 255) | 0;
  138. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  139. };
  140. Color3.prototype.toLinearSpace = function () {
  141. var convertedColor = new Color3();
  142. this.toLinearSpaceToRef(convertedColor);
  143. return convertedColor;
  144. };
  145. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  149. return this;
  150. };
  151. Color3.prototype.toGammaSpace = function () {
  152. var convertedColor = new Color3();
  153. this.toGammaSpaceToRef(convertedColor);
  154. return convertedColor;
  155. };
  156. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  157. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  158. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  159. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  160. return this;
  161. };
  162. // Statics
  163. Color3.FromHexString = function (hex) {
  164. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  165. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  166. return new Color3(0, 0, 0);
  167. }
  168. var r = parseInt(hex.substring(1, 3), 16);
  169. var g = parseInt(hex.substring(3, 5), 16);
  170. var b = parseInt(hex.substring(5, 7), 16);
  171. return Color3.FromInts(r, g, b);
  172. };
  173. Color3.FromArray = function (array, offset) {
  174. if (offset === void 0) { offset = 0; }
  175. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  176. };
  177. Color3.FromInts = function (r, g, b) {
  178. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  179. };
  180. Color3.Lerp = function (start, end, amount) {
  181. var r = start.r + ((end.r - start.r) * amount);
  182. var g = start.g + ((end.g - start.g) * amount);
  183. var b = start.b + ((end.b - start.b) * amount);
  184. return new Color3(r, g, b);
  185. };
  186. Color3.Red = function () { return new Color3(1, 0, 0); };
  187. Color3.Green = function () { return new Color3(0, 1, 0); };
  188. Color3.Blue = function () { return new Color3(0, 0, 1); };
  189. Color3.Black = function () { return new Color3(0, 0, 0); };
  190. Color3.White = function () { return new Color3(1, 1, 1); };
  191. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  192. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  193. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  194. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  195. return Color3;
  196. })();
  197. BABYLON.Color3 = Color3;
  198. var Color4 = (function () {
  199. function Color4(r, g, b, a) {
  200. this.r = r;
  201. this.g = g;
  202. this.b = b;
  203. this.a = a;
  204. }
  205. // Operators
  206. Color4.prototype.addInPlace = function (right) {
  207. this.r += right.r;
  208. this.g += right.g;
  209. this.b += right.b;
  210. this.a += right.a;
  211. return this;
  212. };
  213. Color4.prototype.asArray = function () {
  214. var result = [];
  215. this.toArray(result, 0);
  216. return result;
  217. };
  218. Color4.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.r;
  223. array[index + 1] = this.g;
  224. array[index + 2] = this.b;
  225. array[index + 3] = this.a;
  226. return this;
  227. };
  228. Color4.prototype.add = function (right) {
  229. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  230. };
  231. Color4.prototype.subtract = function (right) {
  232. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  233. };
  234. Color4.prototype.subtractToRef = function (right, result) {
  235. result.r = this.r - right.r;
  236. result.g = this.g - right.g;
  237. result.b = this.b - right.b;
  238. result.a = this.a - right.a;
  239. return this;
  240. };
  241. Color4.prototype.scale = function (scale) {
  242. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  243. };
  244. Color4.prototype.scaleToRef = function (scale, result) {
  245. result.r = this.r * scale;
  246. result.g = this.g * scale;
  247. result.b = this.b * scale;
  248. result.a = this.a * scale;
  249. return this;
  250. };
  251. Color4.prototype.toString = function () {
  252. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  253. };
  254. Color4.prototype.clone = function () {
  255. return new Color4(this.r, this.g, this.b, this.a);
  256. };
  257. Color4.prototype.copyFrom = function (source) {
  258. this.r = source.r;
  259. this.g = source.g;
  260. this.b = source.b;
  261. this.a = source.a;
  262. return this;
  263. };
  264. Color4.prototype.toHexString = function () {
  265. var intR = (this.r * 255) | 0;
  266. var intG = (this.g * 255) | 0;
  267. var intB = (this.b * 255) | 0;
  268. var intA = (this.a * 255) | 0;
  269. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  270. };
  271. // Statics
  272. Color4.FromHexString = function (hex) {
  273. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  274. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  275. return new Color4(0, 0, 0, 0);
  276. }
  277. var r = parseInt(hex.substring(1, 3), 16);
  278. var g = parseInt(hex.substring(3, 5), 16);
  279. var b = parseInt(hex.substring(5, 7), 16);
  280. var a = parseInt(hex.substring(7, 9), 16);
  281. return Color4.FromInts(r, g, b, a);
  282. };
  283. Color4.Lerp = function (left, right, amount) {
  284. var result = new Color4(0, 0, 0, 0);
  285. Color4.LerpToRef(left, right, amount, result);
  286. return result;
  287. };
  288. Color4.LerpToRef = function (left, right, amount, result) {
  289. result.r = left.r + (right.r - left.r) * amount;
  290. result.g = left.g + (right.g - left.g) * amount;
  291. result.b = left.b + (right.b - left.b) * amount;
  292. result.a = left.a + (right.a - left.a) * amount;
  293. };
  294. Color4.FromArray = function (array, offset) {
  295. if (offset === void 0) { offset = 0; }
  296. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  297. };
  298. Color4.FromInts = function (r, g, b, a) {
  299. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  300. };
  301. Color4.CheckColors4 = function (colors, count) {
  302. // Check if color3 was used
  303. if (colors.length === count * 3) {
  304. var colors4 = [];
  305. for (var index = 0; index < colors.length; index += 3) {
  306. var newIndex = (index / 3) * 4;
  307. colors4[newIndex] = colors[index];
  308. colors4[newIndex + 1] = colors[index + 1];
  309. colors4[newIndex + 2] = colors[index + 2];
  310. colors4[newIndex + 3] = 1.0;
  311. }
  312. return colors4;
  313. }
  314. return colors;
  315. };
  316. return Color4;
  317. })();
  318. BABYLON.Color4 = Color4;
  319. var Vector2 = (function () {
  320. function Vector2(x, y) {
  321. this.x = x;
  322. this.y = y;
  323. }
  324. Vector2.prototype.toString = function () {
  325. return "{X: " + this.x + " Y:" + this.y + "}";
  326. };
  327. // Operators
  328. Vector2.prototype.toArray = function (array, index) {
  329. if (index === void 0) { index = 0; }
  330. array[index] = this.x;
  331. array[index + 1] = this.y;
  332. return this;
  333. };
  334. Vector2.prototype.asArray = function () {
  335. var result = [];
  336. this.toArray(result, 0);
  337. return result;
  338. };
  339. Vector2.prototype.copyFrom = function (source) {
  340. this.x = source.x;
  341. this.y = source.y;
  342. return this;
  343. };
  344. Vector2.prototype.copyFromFloats = function (x, y) {
  345. this.x = x;
  346. this.y = y;
  347. return this;
  348. };
  349. Vector2.prototype.add = function (otherVector) {
  350. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  351. };
  352. Vector2.prototype.addVector3 = function (otherVector) {
  353. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  354. };
  355. Vector2.prototype.subtract = function (otherVector) {
  356. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  357. };
  358. Vector2.prototype.subtractInPlace = function (otherVector) {
  359. this.x -= otherVector.x;
  360. this.y -= otherVector.y;
  361. return this;
  362. };
  363. Vector2.prototype.multiplyInPlace = function (otherVector) {
  364. this.x *= otherVector.x;
  365. this.y *= otherVector.y;
  366. return this;
  367. };
  368. Vector2.prototype.multiply = function (otherVector) {
  369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  370. };
  371. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  372. result.x = this.x * otherVector.x;
  373. result.y = this.y * otherVector.y;
  374. return this;
  375. };
  376. Vector2.prototype.multiplyByFloats = function (x, y) {
  377. return new Vector2(this.x * x, this.y * y);
  378. };
  379. Vector2.prototype.divide = function (otherVector) {
  380. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  381. };
  382. Vector2.prototype.divideToRef = function (otherVector, result) {
  383. result.x = this.x / otherVector.x;
  384. result.y = this.y / otherVector.y;
  385. return this;
  386. };
  387. Vector2.prototype.negate = function () {
  388. return new Vector2(-this.x, -this.y);
  389. };
  390. Vector2.prototype.scaleInPlace = function (scale) {
  391. this.x *= scale;
  392. this.y *= scale;
  393. return this;
  394. };
  395. Vector2.prototype.scale = function (scale) {
  396. return new Vector2(this.x * scale, this.y * scale);
  397. };
  398. Vector2.prototype.equals = function (otherVector) {
  399. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  400. };
  401. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  402. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  403. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  404. };
  405. // Properties
  406. Vector2.prototype.length = function () {
  407. return Math.sqrt(this.x * this.x + this.y * this.y);
  408. };
  409. Vector2.prototype.lengthSquared = function () {
  410. return (this.x * this.x + this.y * this.y);
  411. };
  412. // Methods
  413. Vector2.prototype.normalize = function () {
  414. var len = this.length();
  415. if (len === 0)
  416. return this;
  417. var num = 1.0 / len;
  418. this.x *= num;
  419. this.y *= num;
  420. return this;
  421. };
  422. Vector2.prototype.clone = function () {
  423. return new Vector2(this.x, this.y);
  424. };
  425. // Statics
  426. Vector2.Zero = function () {
  427. return new Vector2(0, 0);
  428. };
  429. Vector2.FromArray = function (array, offset) {
  430. if (offset === void 0) { offset = 0; }
  431. return new Vector2(array[offset], array[offset + 1]);
  432. };
  433. Vector2.FromArrayToRef = function (array, offset, result) {
  434. result.x = array[offset];
  435. result.y = array[offset + 1];
  436. };
  437. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  438. var squared = amount * amount;
  439. var cubed = amount * squared;
  440. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  441. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  442. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  443. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  444. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  445. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  446. return new Vector2(x, y);
  447. };
  448. Vector2.Clamp = function (value, min, max) {
  449. var x = value.x;
  450. x = (x > max.x) ? max.x : x;
  451. x = (x < min.x) ? min.x : x;
  452. var y = value.y;
  453. y = (y > max.y) ? max.y : y;
  454. y = (y < min.y) ? min.y : y;
  455. return new Vector2(x, y);
  456. };
  457. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  458. var squared = amount * amount;
  459. var cubed = amount * squared;
  460. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  461. var part2 = (-2.0 * cubed) + (3.0 * squared);
  462. var part3 = (cubed - (2.0 * squared)) + amount;
  463. var part4 = cubed - squared;
  464. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  465. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  466. return new Vector2(x, y);
  467. };
  468. Vector2.Lerp = function (start, end, amount) {
  469. var x = start.x + ((end.x - start.x) * amount);
  470. var y = start.y + ((end.y - start.y) * amount);
  471. return new Vector2(x, y);
  472. };
  473. Vector2.Dot = function (left, right) {
  474. return left.x * right.x + left.y * right.y;
  475. };
  476. Vector2.Normalize = function (vector) {
  477. var newVector = vector.clone();
  478. newVector.normalize();
  479. return newVector;
  480. };
  481. Vector2.Minimize = function (left, right) {
  482. var x = (left.x < right.x) ? left.x : right.x;
  483. var y = (left.y < right.y) ? left.y : right.y;
  484. return new Vector2(x, y);
  485. };
  486. Vector2.Maximize = function (left, right) {
  487. var x = (left.x > right.x) ? left.x : right.x;
  488. var y = (left.y > right.y) ? left.y : right.y;
  489. return new Vector2(x, y);
  490. };
  491. Vector2.Transform = function (vector, transformation) {
  492. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  493. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  494. return new Vector2(x, y);
  495. };
  496. Vector2.Distance = function (value1, value2) {
  497. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  498. };
  499. Vector2.DistanceSquared = function (value1, value2) {
  500. var x = value1.x - value2.x;
  501. var y = value1.y - value2.y;
  502. return (x * x) + (y * y);
  503. };
  504. return Vector2;
  505. })();
  506. BABYLON.Vector2 = Vector2;
  507. var Vector3 = (function () {
  508. function Vector3(x, y, z) {
  509. this.x = x;
  510. this.y = y;
  511. this.z = z;
  512. }
  513. Vector3.prototype.toString = function () {
  514. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  515. };
  516. // Operators
  517. Vector3.prototype.asArray = function () {
  518. var result = [];
  519. this.toArray(result, 0);
  520. return result;
  521. };
  522. Vector3.prototype.toArray = function (array, index) {
  523. if (index === void 0) { index = 0; }
  524. array[index] = this.x;
  525. array[index + 1] = this.y;
  526. array[index + 2] = this.z;
  527. return this;
  528. };
  529. Vector3.prototype.toQuaternion = function () {
  530. var result = new Quaternion(0, 0, 0, 1);
  531. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  532. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  533. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  534. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  535. var cosy = Math.cos(this.y * 0.5);
  536. var siny = Math.sin(this.y * 0.5);
  537. result.x = coszMinusx * siny;
  538. result.y = -sinzMinusx * siny;
  539. result.z = sinxPlusz * cosy;
  540. result.w = cosxPlusz * cosy;
  541. return result;
  542. };
  543. Vector3.prototype.addInPlace = function (otherVector) {
  544. this.x += otherVector.x;
  545. this.y += otherVector.y;
  546. this.z += otherVector.z;
  547. return this;
  548. };
  549. Vector3.prototype.add = function (otherVector) {
  550. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  551. };
  552. Vector3.prototype.addToRef = function (otherVector, result) {
  553. result.x = this.x + otherVector.x;
  554. result.y = this.y + otherVector.y;
  555. result.z = this.z + otherVector.z;
  556. return this;
  557. };
  558. Vector3.prototype.subtractInPlace = function (otherVector) {
  559. this.x -= otherVector.x;
  560. this.y -= otherVector.y;
  561. this.z -= otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtract = function (otherVector) {
  565. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  566. };
  567. Vector3.prototype.subtractToRef = function (otherVector, result) {
  568. result.x = this.x - otherVector.x;
  569. result.y = this.y - otherVector.y;
  570. result.z = this.z - otherVector.z;
  571. return this;
  572. };
  573. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  574. return new Vector3(this.x - x, this.y - y, this.z - z);
  575. };
  576. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  577. result.x = this.x - x;
  578. result.y = this.y - y;
  579. result.z = this.z - z;
  580. return this;
  581. };
  582. Vector3.prototype.negate = function () {
  583. return new Vector3(-this.x, -this.y, -this.z);
  584. };
  585. Vector3.prototype.scaleInPlace = function (scale) {
  586. this.x *= scale;
  587. this.y *= scale;
  588. this.z *= scale;
  589. return this;
  590. };
  591. Vector3.prototype.scale = function (scale) {
  592. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  593. };
  594. Vector3.prototype.scaleToRef = function (scale, result) {
  595. result.x = this.x * scale;
  596. result.y = this.y * scale;
  597. result.z = this.z * scale;
  598. };
  599. Vector3.prototype.equals = function (otherVector) {
  600. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  601. };
  602. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  603. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  604. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  605. };
  606. Vector3.prototype.equalsToFloats = function (x, y, z) {
  607. return this.x === x && this.y === y && this.z === z;
  608. };
  609. Vector3.prototype.multiplyInPlace = function (otherVector) {
  610. this.x *= otherVector.x;
  611. this.y *= otherVector.y;
  612. this.z *= otherVector.z;
  613. return this;
  614. };
  615. Vector3.prototype.multiply = function (otherVector) {
  616. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  617. };
  618. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  619. result.x = this.x * otherVector.x;
  620. result.y = this.y * otherVector.y;
  621. result.z = this.z * otherVector.z;
  622. return this;
  623. };
  624. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  625. return new Vector3(this.x * x, this.y * y, this.z * z);
  626. };
  627. Vector3.prototype.divide = function (otherVector) {
  628. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  629. };
  630. Vector3.prototype.divideToRef = function (otherVector, result) {
  631. result.x = this.x / otherVector.x;
  632. result.y = this.y / otherVector.y;
  633. result.z = this.z / otherVector.z;
  634. return this;
  635. };
  636. Vector3.prototype.MinimizeInPlace = function (other) {
  637. if (other.x < this.x)
  638. this.x = other.x;
  639. if (other.y < this.y)
  640. this.y = other.y;
  641. if (other.z < this.z)
  642. this.z = other.z;
  643. return this;
  644. };
  645. Vector3.prototype.MaximizeInPlace = function (other) {
  646. if (other.x > this.x)
  647. this.x = other.x;
  648. if (other.y > this.y)
  649. this.y = other.y;
  650. if (other.z > this.z)
  651. this.z = other.z;
  652. return this;
  653. };
  654. // Properties
  655. Vector3.prototype.length = function () {
  656. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  657. };
  658. Vector3.prototype.lengthSquared = function () {
  659. return (this.x * this.x + this.y * this.y + this.z * this.z);
  660. };
  661. // Methods
  662. Vector3.prototype.normalize = function () {
  663. var len = this.length();
  664. if (len === 0 || len === 1.0)
  665. return this;
  666. var num = 1.0 / len;
  667. this.x *= num;
  668. this.y *= num;
  669. this.z *= num;
  670. return this;
  671. };
  672. Vector3.prototype.clone = function () {
  673. return new Vector3(this.x, this.y, this.z);
  674. };
  675. Vector3.prototype.copyFrom = function (source) {
  676. this.x = source.x;
  677. this.y = source.y;
  678. this.z = source.z;
  679. return this;
  680. };
  681. Vector3.prototype.copyFromFloats = function (x, y, z) {
  682. this.x = x;
  683. this.y = y;
  684. this.z = z;
  685. return this;
  686. };
  687. // Statics
  688. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  689. var d0 = Vector3.Dot(vector0, axis) - size;
  690. var d1 = Vector3.Dot(vector1, axis) - size;
  691. var s = d0 / (d0 - d1);
  692. return s;
  693. };
  694. Vector3.FromArray = function (array, offset) {
  695. if (!offset) {
  696. offset = 0;
  697. }
  698. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  699. };
  700. Vector3.FromFloatArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromArrayToRef = function (array, offset, result) {
  707. result.x = array[offset];
  708. result.y = array[offset + 1];
  709. result.z = array[offset + 2];
  710. };
  711. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  712. result.x = array[offset];
  713. result.y = array[offset + 1];
  714. result.z = array[offset + 2];
  715. };
  716. Vector3.FromFloatsToRef = function (x, y, z, result) {
  717. result.x = x;
  718. result.y = y;
  719. result.z = z;
  720. };
  721. Vector3.Zero = function () {
  722. return new Vector3(0, 0, 0);
  723. };
  724. Vector3.Up = function () {
  725. return new Vector3(0, 1.0, 0);
  726. };
  727. Vector3.TransformCoordinates = function (vector, transformation) {
  728. var result = Vector3.Zero();
  729. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  730. return result;
  731. };
  732. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  733. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  734. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  735. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  736. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  737. result.x = x / w;
  738. result.y = y / w;
  739. result.z = z / w;
  740. };
  741. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  742. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  743. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  744. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  745. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  746. result.x = rx / rw;
  747. result.y = ry / rw;
  748. result.z = rz / rw;
  749. };
  750. Vector3.TransformNormal = function (vector, transformation) {
  751. var result = Vector3.Zero();
  752. Vector3.TransformNormalToRef(vector, transformation, result);
  753. return result;
  754. };
  755. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  756. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  757. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  758. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  759. };
  760. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  761. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  762. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  763. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  764. };
  765. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  766. var squared = amount * amount;
  767. var cubed = amount * squared;
  768. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  769. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  770. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  771. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  772. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  773. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  774. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  775. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  776. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  777. return new Vector3(x, y, z);
  778. };
  779. Vector3.Clamp = function (value, min, max) {
  780. var x = value.x;
  781. x = (x > max.x) ? max.x : x;
  782. x = (x < min.x) ? min.x : x;
  783. var y = value.y;
  784. y = (y > max.y) ? max.y : y;
  785. y = (y < min.y) ? min.y : y;
  786. var z = value.z;
  787. z = (z > max.z) ? max.z : z;
  788. z = (z < min.z) ? min.z : z;
  789. return new Vector3(x, y, z);
  790. };
  791. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  792. var squared = amount * amount;
  793. var cubed = amount * squared;
  794. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  795. var part2 = (-2.0 * cubed) + (3.0 * squared);
  796. var part3 = (cubed - (2.0 * squared)) + amount;
  797. var part4 = cubed - squared;
  798. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  799. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  800. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  801. return new Vector3(x, y, z);
  802. };
  803. Vector3.Lerp = function (start, end, amount) {
  804. var x = start.x + ((end.x - start.x) * amount);
  805. var y = start.y + ((end.y - start.y) * amount);
  806. var z = start.z + ((end.z - start.z) * amount);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Dot = function (left, right) {
  810. return (left.x * right.x + left.y * right.y + left.z * right.z);
  811. };
  812. Vector3.Cross = function (left, right) {
  813. var result = Vector3.Zero();
  814. Vector3.CrossToRef(left, right, result);
  815. return result;
  816. };
  817. Vector3.CrossToRef = function (left, right, result) {
  818. result.x = left.y * right.z - left.z * right.y;
  819. result.y = left.z * right.x - left.x * right.z;
  820. result.z = left.x * right.y - left.y * right.x;
  821. };
  822. Vector3.Normalize = function (vector) {
  823. var result = Vector3.Zero();
  824. Vector3.NormalizeToRef(vector, result);
  825. return result;
  826. };
  827. Vector3.NormalizeToRef = function (vector, result) {
  828. result.copyFrom(vector);
  829. result.normalize();
  830. };
  831. Vector3.Project = function (vector, world, transform, viewport) {
  832. var cw = viewport.width;
  833. var ch = viewport.height;
  834. var cx = viewport.x;
  835. var cy = viewport.y;
  836. 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);
  837. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  838. return Vector3.TransformCoordinates(vector, finalMatrix);
  839. };
  840. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  841. var matrix = world.multiply(transform);
  842. matrix.invert();
  843. source.x = source.x / viewportWidth * 2 - 1;
  844. source.y = -(source.y / viewportHeight * 2 - 1);
  845. var vector = Vector3.TransformCoordinates(source, matrix);
  846. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  847. if (MathTools.WithinEpsilon(num, 1.0)) {
  848. vector = vector.scale(1.0 / num);
  849. }
  850. return vector;
  851. };
  852. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  853. var matrix = world.multiply(view).multiply(projection);
  854. matrix.invert();
  855. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  856. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  857. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  858. if (MathTools.WithinEpsilon(num, 1.0)) {
  859. vector = vector.scale(1.0 / num);
  860. }
  861. return vector;
  862. };
  863. Vector3.Minimize = function (left, right) {
  864. var min = left.clone();
  865. min.MinimizeInPlace(right);
  866. return min;
  867. };
  868. Vector3.Maximize = function (left, right) {
  869. var max = left.clone();
  870. max.MaximizeInPlace(right);
  871. return max;
  872. };
  873. Vector3.Distance = function (value1, value2) {
  874. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  875. };
  876. Vector3.DistanceSquared = function (value1, value2) {
  877. var x = value1.x - value2.x;
  878. var y = value1.y - value2.y;
  879. var z = value1.z - value2.z;
  880. return (x * x) + (y * y) + (z * z);
  881. };
  882. Vector3.Center = function (value1, value2) {
  883. var center = value1.add(value2);
  884. center.scaleInPlace(0.5);
  885. return center;
  886. };
  887. /**
  888. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  889. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  890. * to something in order to rotate it from its local system to the given target system.
  891. */
  892. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  893. var rotation = Vector3.Zero();
  894. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  895. return rotation;
  896. };
  897. /**
  898. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  899. */
  900. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  901. var u = axis1.normalize();
  902. var w = axis3.normalize();
  903. // world axis
  904. var X = Axis.X;
  905. var Y = Axis.Y;
  906. // equation unknowns and vars
  907. var yaw = 0.0;
  908. var pitch = 0.0;
  909. var roll = 0.0;
  910. var x = 0.0;
  911. var y = 0.0;
  912. var z = 0.0;
  913. var t = 0.0;
  914. var sign = -1.0;
  915. var nbRevert = 0;
  916. var cross = Tmp.Vector3[0];
  917. var dot = 0.0;
  918. // step 1 : rotation around w
  919. // Rv3(u) = u1, and u1 belongs to plane xOz
  920. // Rv3(w) = w1 = w invariant
  921. var u1 = Tmp.Vector3[1];
  922. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  923. z = 1.0;
  924. }
  925. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  926. x = 1.0;
  927. }
  928. else {
  929. t = w.z / w.x;
  930. x = -t * Math.sqrt(1 / (1 + t * t));
  931. z = Math.sqrt(1 / (1 + t * t));
  932. }
  933. u1.x = x;
  934. u1.y = y;
  935. u1.z = z;
  936. u1.normalize();
  937. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  938. cross.normalize();
  939. if (Vector3.Dot(w, cross) < 0) {
  940. sign = 1.0;
  941. }
  942. dot = Vector3.Dot(u, u1);
  943. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  944. roll = Math.acos(dot) * sign;
  945. if (Vector3.Dot(u1, X) < 0) {
  946. roll = Math.PI + roll;
  947. u1 = u1.scaleInPlace(-1);
  948. nbRevert++;
  949. }
  950. // step 2 : rotate around u1
  951. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  952. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  953. var w2 = Tmp.Vector3[2];
  954. var v2 = Tmp.Vector3[3];
  955. x = 0.0;
  956. y = 0.0;
  957. z = 0.0;
  958. sign = -1.0;
  959. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  960. x = 1.0;
  961. }
  962. else {
  963. t = u1.z / u1.x;
  964. x = -t * Math.sqrt(1 / (1 + t * t));
  965. z = Math.sqrt(1 / (1 + t * t));
  966. }
  967. w2.x = x;
  968. w2.y = y;
  969. w2.z = z;
  970. w2.normalize();
  971. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  972. v2.normalize();
  973. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  974. cross.normalize();
  975. if (Vector3.Dot(u1, cross) < 0) {
  976. sign = 1.0;
  977. }
  978. dot = Vector3.Dot(w, w2);
  979. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  980. pitch = Math.acos(dot) * sign;
  981. if (Vector3.Dot(v2, Y) < 0) {
  982. pitch = Math.PI + pitch;
  983. nbRevert++;
  984. }
  985. // step 3 : rotate around v2
  986. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  987. sign = -1.0;
  988. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  989. cross.normalize();
  990. if (Vector3.Dot(cross, Y) < 0) {
  991. sign = 1.0;
  992. }
  993. dot = Vector3.Dot(u1, X);
  994. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  995. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  996. if (dot < 0 && nbRevert < 2) {
  997. yaw = Math.PI + yaw;
  998. }
  999. ref.x = pitch;
  1000. ref.y = yaw;
  1001. ref.z = roll;
  1002. };
  1003. return Vector3;
  1004. })();
  1005. BABYLON.Vector3 = Vector3;
  1006. //Vector4 class created for EulerAngle class conversion to Quaternion
  1007. var Vector4 = (function () {
  1008. function Vector4(x, y, z, w) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. this.w = w;
  1013. }
  1014. Vector4.prototype.toString = function () {
  1015. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1016. };
  1017. // Operators
  1018. Vector4.prototype.asArray = function () {
  1019. var result = [];
  1020. this.toArray(result, 0);
  1021. return result;
  1022. };
  1023. Vector4.prototype.toArray = function (array, index) {
  1024. if (index === undefined) {
  1025. index = 0;
  1026. }
  1027. array[index] = this.x;
  1028. array[index + 1] = this.y;
  1029. array[index + 2] = this.z;
  1030. array[index + 3] = this.w;
  1031. return this;
  1032. };
  1033. Vector4.prototype.addInPlace = function (otherVector) {
  1034. this.x += otherVector.x;
  1035. this.y += otherVector.y;
  1036. this.z += otherVector.z;
  1037. this.w += otherVector.w;
  1038. return this;
  1039. };
  1040. Vector4.prototype.add = function (otherVector) {
  1041. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1042. };
  1043. Vector4.prototype.addToRef = function (otherVector, result) {
  1044. result.x = this.x + otherVector.x;
  1045. result.y = this.y + otherVector.y;
  1046. result.z = this.z + otherVector.z;
  1047. result.w = this.w + otherVector.w;
  1048. return this;
  1049. };
  1050. Vector4.prototype.subtractInPlace = function (otherVector) {
  1051. this.x -= otherVector.x;
  1052. this.y -= otherVector.y;
  1053. this.z -= otherVector.z;
  1054. this.w -= otherVector.w;
  1055. return this;
  1056. };
  1057. Vector4.prototype.subtract = function (otherVector) {
  1058. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1059. };
  1060. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1061. result.x = this.x - otherVector.x;
  1062. result.y = this.y - otherVector.y;
  1063. result.z = this.z - otherVector.z;
  1064. result.w = this.w - otherVector.w;
  1065. return this;
  1066. };
  1067. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1068. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1069. };
  1070. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1071. result.x = this.x - x;
  1072. result.y = this.y - y;
  1073. result.z = this.z - z;
  1074. result.w = this.w - w;
  1075. return this;
  1076. };
  1077. Vector4.prototype.negate = function () {
  1078. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1079. };
  1080. Vector4.prototype.scaleInPlace = function (scale) {
  1081. this.x *= scale;
  1082. this.y *= scale;
  1083. this.z *= scale;
  1084. this.w *= scale;
  1085. return this;
  1086. };
  1087. Vector4.prototype.scale = function (scale) {
  1088. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1089. };
  1090. Vector4.prototype.scaleToRef = function (scale, result) {
  1091. result.x = this.x * scale;
  1092. result.y = this.y * scale;
  1093. result.z = this.z * scale;
  1094. result.w = this.w * scale;
  1095. };
  1096. Vector4.prototype.equals = function (otherVector) {
  1097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1098. };
  1099. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1100. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1101. return otherVector
  1102. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1103. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1104. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1105. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1106. };
  1107. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1108. return this.x === x && this.y === y && this.z === z && this.w === w;
  1109. };
  1110. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1111. this.x *= otherVector.x;
  1112. this.y *= otherVector.y;
  1113. this.z *= otherVector.z;
  1114. this.w *= otherVector.w;
  1115. return this;
  1116. };
  1117. Vector4.prototype.multiply = function (otherVector) {
  1118. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1119. };
  1120. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1121. result.x = this.x * otherVector.x;
  1122. result.y = this.y * otherVector.y;
  1123. result.z = this.z * otherVector.z;
  1124. result.w = this.w * otherVector.w;
  1125. return this;
  1126. };
  1127. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1128. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1129. };
  1130. Vector4.prototype.divide = function (otherVector) {
  1131. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1132. };
  1133. Vector4.prototype.divideToRef = function (otherVector, result) {
  1134. result.x = this.x / otherVector.x;
  1135. result.y = this.y / otherVector.y;
  1136. result.z = this.z / otherVector.z;
  1137. result.w = this.w / otherVector.w;
  1138. return this;
  1139. };
  1140. Vector4.prototype.MinimizeInPlace = function (other) {
  1141. if (other.x < this.x)
  1142. this.x = other.x;
  1143. if (other.y < this.y)
  1144. this.y = other.y;
  1145. if (other.z < this.z)
  1146. this.z = other.z;
  1147. if (other.w < this.w)
  1148. this.w = other.w;
  1149. return this;
  1150. };
  1151. Vector4.prototype.MaximizeInPlace = function (other) {
  1152. if (other.x > this.x)
  1153. this.x = other.x;
  1154. if (other.y > this.y)
  1155. this.y = other.y;
  1156. if (other.z > this.z)
  1157. this.z = other.z;
  1158. if (other.w > this.w)
  1159. this.w = other.w;
  1160. return this;
  1161. };
  1162. // Properties
  1163. Vector4.prototype.length = function () {
  1164. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1165. };
  1166. Vector4.prototype.lengthSquared = function () {
  1167. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1168. };
  1169. // Methods
  1170. Vector4.prototype.normalize = function () {
  1171. var len = this.length();
  1172. if (len === 0)
  1173. return this;
  1174. var num = 1.0 / len;
  1175. this.x *= num;
  1176. this.y *= num;
  1177. this.z *= num;
  1178. this.w *= num;
  1179. return this;
  1180. };
  1181. Vector4.prototype.clone = function () {
  1182. return new Vector4(this.x, this.y, this.z, this.w);
  1183. };
  1184. Vector4.prototype.copyFrom = function (source) {
  1185. this.x = source.x;
  1186. this.y = source.y;
  1187. this.z = source.z;
  1188. this.w = source.w;
  1189. return this;
  1190. };
  1191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1192. this.x = x;
  1193. this.y = y;
  1194. this.z = z;
  1195. this.w = w;
  1196. return this;
  1197. };
  1198. // Statics
  1199. Vector4.FromArray = function (array, offset) {
  1200. if (!offset) {
  1201. offset = 0;
  1202. }
  1203. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1204. };
  1205. Vector4.FromArrayToRef = function (array, offset, result) {
  1206. result.x = array[offset];
  1207. result.y = array[offset + 1];
  1208. result.z = array[offset + 2];
  1209. result.w = array[offset + 3];
  1210. };
  1211. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1218. result.x = x;
  1219. result.y = y;
  1220. result.z = z;
  1221. result.w = w;
  1222. };
  1223. Vector4.Zero = function () {
  1224. return new Vector4(0, 0, 0, 0);
  1225. };
  1226. Vector4.Normalize = function (vector) {
  1227. var result = Vector4.Zero();
  1228. Vector4.NormalizeToRef(vector, result);
  1229. return result;
  1230. };
  1231. Vector4.NormalizeToRef = function (vector, result) {
  1232. result.copyFrom(vector);
  1233. result.normalize();
  1234. };
  1235. Vector4.Minimize = function (left, right) {
  1236. var min = left.clone();
  1237. min.MinimizeInPlace(right);
  1238. return min;
  1239. };
  1240. Vector4.Maximize = function (left, right) {
  1241. var max = left.clone();
  1242. max.MaximizeInPlace(right);
  1243. return max;
  1244. };
  1245. Vector4.Distance = function (value1, value2) {
  1246. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1247. };
  1248. Vector4.DistanceSquared = function (value1, value2) {
  1249. var x = value1.x - value2.x;
  1250. var y = value1.y - value2.y;
  1251. var z = value1.z - value2.z;
  1252. var w = value1.w - value2.w;
  1253. return (x * x) + (y * y) + (z * z) + (w * w);
  1254. };
  1255. Vector4.Center = function (value1, value2) {
  1256. var center = value1.add(value2);
  1257. center.scaleInPlace(0.5);
  1258. return center;
  1259. };
  1260. return Vector4;
  1261. })();
  1262. BABYLON.Vector4 = Vector4;
  1263. var Quaternion = (function () {
  1264. function Quaternion(x, y, z, w) {
  1265. if (x === void 0) { x = 0; }
  1266. if (y === void 0) { y = 0; }
  1267. if (z === void 0) { z = 0; }
  1268. if (w === void 0) { w = 1; }
  1269. this.x = x;
  1270. this.y = y;
  1271. this.z = z;
  1272. this.w = w;
  1273. }
  1274. Quaternion.prototype.toString = function () {
  1275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1276. };
  1277. Quaternion.prototype.asArray = function () {
  1278. return [this.x, this.y, this.z, this.w];
  1279. };
  1280. Quaternion.prototype.equals = function (otherQuaternion) {
  1281. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1282. };
  1283. Quaternion.prototype.clone = function () {
  1284. return new Quaternion(this.x, this.y, this.z, this.w);
  1285. };
  1286. Quaternion.prototype.copyFrom = function (other) {
  1287. this.x = other.x;
  1288. this.y = other.y;
  1289. this.z = other.z;
  1290. this.w = other.w;
  1291. return this;
  1292. };
  1293. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. this.w = w;
  1298. return this;
  1299. };
  1300. Quaternion.prototype.add = function (other) {
  1301. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1302. };
  1303. Quaternion.prototype.subtract = function (other) {
  1304. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1305. };
  1306. Quaternion.prototype.scale = function (value) {
  1307. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1308. };
  1309. Quaternion.prototype.multiply = function (q1) {
  1310. var result = new Quaternion(0, 0, 0, 1.0);
  1311. this.multiplyToRef(q1, result);
  1312. return result;
  1313. };
  1314. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1315. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1316. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1317. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1318. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1319. result.copyFromFloats(x, y, z, w);
  1320. return this;
  1321. };
  1322. Quaternion.prototype.multiplyInPlace = function (q1) {
  1323. this.multiplyToRef(q1, this);
  1324. return this;
  1325. };
  1326. Quaternion.prototype.conjugateToRef = function (ref) {
  1327. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1328. return this;
  1329. };
  1330. Quaternion.prototype.conjugateInPlace = function () {
  1331. this.x *= -1;
  1332. this.y *= -1;
  1333. this.z *= -1;
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugate = function () {
  1337. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1338. return result;
  1339. };
  1340. Quaternion.prototype.length = function () {
  1341. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1342. };
  1343. Quaternion.prototype.normalize = function () {
  1344. var length = 1.0 / this.length();
  1345. this.x *= length;
  1346. this.y *= length;
  1347. this.z *= length;
  1348. this.w *= length;
  1349. return this;
  1350. };
  1351. Quaternion.prototype.toEulerAngles = function (order) {
  1352. if (order === void 0) { order = "YZX"; }
  1353. var result = Vector3.Zero();
  1354. this.toEulerAnglesToRef(result, order);
  1355. return result;
  1356. };
  1357. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var heading, attitude, bank;
  1360. var x = this.x, y = this.y, z = this.z, w = this.w;
  1361. switch (order) {
  1362. case "YZX":
  1363. var test = x * y + z * w;
  1364. if (test > 0.499) {
  1365. heading = 2 * Math.atan2(x, w);
  1366. attitude = Math.PI / 2;
  1367. bank = 0;
  1368. }
  1369. if (test < -0.499) {
  1370. heading = -2 * Math.atan2(x, w);
  1371. attitude = -Math.PI / 2;
  1372. bank = 0;
  1373. }
  1374. if (isNaN(heading)) {
  1375. var sqx = x * x;
  1376. var sqy = y * y;
  1377. var sqz = z * z;
  1378. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1379. attitude = Math.asin(2 * test); // attitude
  1380. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1381. }
  1382. break;
  1383. default:
  1384. throw new Error("Euler order " + order + " not supported yet.");
  1385. }
  1386. result.y = heading;
  1387. result.z = attitude;
  1388. result.x = bank;
  1389. return this;
  1390. };
  1391. ;
  1392. Quaternion.prototype.toRotationMatrix = function (result) {
  1393. var xx = this.x * this.x;
  1394. var yy = this.y * this.y;
  1395. var zz = this.z * this.z;
  1396. var xy = this.x * this.y;
  1397. var zw = this.z * this.w;
  1398. var zx = this.z * this.x;
  1399. var yw = this.y * this.w;
  1400. var yz = this.y * this.z;
  1401. var xw = this.x * this.w;
  1402. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1403. result.m[1] = 2.0 * (xy + zw);
  1404. result.m[2] = 2.0 * (zx - yw);
  1405. result.m[3] = 0;
  1406. result.m[4] = 2.0 * (xy - zw);
  1407. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1408. result.m[6] = 2.0 * (yz + xw);
  1409. result.m[7] = 0;
  1410. result.m[8] = 2.0 * (zx + yw);
  1411. result.m[9] = 2.0 * (yz - xw);
  1412. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1413. result.m[11] = 0;
  1414. result.m[12] = 0;
  1415. result.m[13] = 0;
  1416. result.m[14] = 0;
  1417. result.m[15] = 1.0;
  1418. return this;
  1419. };
  1420. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1421. Quaternion.FromRotationMatrixToRef(matrix, this);
  1422. return this;
  1423. };
  1424. // Statics
  1425. Quaternion.FromRotationMatrix = function (matrix) {
  1426. var result = new Quaternion();
  1427. Quaternion.FromRotationMatrixToRef(matrix, result);
  1428. return result;
  1429. };
  1430. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1431. var data = matrix.m;
  1432. var m11 = data[0], m12 = data[4], m13 = data[8];
  1433. var m21 = data[1], m22 = data[5], m23 = data[9];
  1434. var m31 = data[2], m32 = data[6], m33 = data[10];
  1435. var trace = m11 + m22 + m33;
  1436. var s;
  1437. if (trace > 0) {
  1438. s = 0.5 / Math.sqrt(trace + 1.0);
  1439. result.w = 0.25 / s;
  1440. result.x = (m32 - m23) * s;
  1441. result.y = (m13 - m31) * s;
  1442. result.z = (m21 - m12) * s;
  1443. }
  1444. else if (m11 > m22 && m11 > m33) {
  1445. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1446. result.w = (m32 - m23) / s;
  1447. result.x = 0.25 * s;
  1448. result.y = (m12 + m21) / s;
  1449. result.z = (m13 + m31) / s;
  1450. }
  1451. else if (m22 > m33) {
  1452. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1453. result.w = (m13 - m31) / s;
  1454. result.x = (m12 + m21) / s;
  1455. result.y = 0.25 * s;
  1456. result.z = (m23 + m32) / s;
  1457. }
  1458. else {
  1459. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1460. result.w = (m21 - m12) / s;
  1461. result.x = (m13 + m31) / s;
  1462. result.y = (m23 + m32) / s;
  1463. result.z = 0.25 * s;
  1464. }
  1465. };
  1466. Quaternion.Inverse = function (q) {
  1467. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1468. };
  1469. Quaternion.Identity = function () {
  1470. return new Quaternion(0, 0, 0, 1);
  1471. };
  1472. Quaternion.RotationAxis = function (axis, angle) {
  1473. var result = new Quaternion();
  1474. var sin = Math.sin(angle / 2);
  1475. axis.normalize();
  1476. result.w = Math.cos(angle / 2);
  1477. result.x = axis.x * sin;
  1478. result.y = axis.y * sin;
  1479. result.z = axis.z * sin;
  1480. return result;
  1481. };
  1482. Quaternion.FromArray = function (array, offset) {
  1483. if (!offset) {
  1484. offset = 0;
  1485. }
  1486. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1487. };
  1488. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1489. var result = new Quaternion();
  1490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1491. return result;
  1492. };
  1493. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1494. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1495. var halfRoll = roll * 0.5;
  1496. var halfPitch = pitch * 0.5;
  1497. var halfYaw = yaw * 0.5;
  1498. var sinRoll = Math.sin(halfRoll);
  1499. var cosRoll = Math.cos(halfRoll);
  1500. var sinPitch = Math.sin(halfPitch);
  1501. var cosPitch = Math.cos(halfPitch);
  1502. var sinYaw = Math.sin(halfYaw);
  1503. var cosYaw = Math.cos(halfYaw);
  1504. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1505. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1506. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1507. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1508. };
  1509. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1510. var result = new Quaternion();
  1511. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1512. return result;
  1513. };
  1514. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1515. // Produces a quaternion from Euler angles in the z-x-z orientation
  1516. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1517. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1518. var halfBeta = beta * 0.5;
  1519. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1520. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1521. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1522. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1523. };
  1524. Quaternion.Slerp = function (left, right, amount) {
  1525. var num2;
  1526. var num3;
  1527. var num = amount;
  1528. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1529. var flag = false;
  1530. if (num4 < 0) {
  1531. flag = true;
  1532. num4 = -num4;
  1533. }
  1534. if (num4 > 0.999999) {
  1535. num3 = 1 - num;
  1536. num2 = flag ? -num : num;
  1537. }
  1538. else {
  1539. var num5 = Math.acos(num4);
  1540. var num6 = (1.0 / Math.sin(num5));
  1541. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1542. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1543. }
  1544. 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));
  1545. };
  1546. return Quaternion;
  1547. })();
  1548. BABYLON.Quaternion = Quaternion;
  1549. var Matrix = (function () {
  1550. function Matrix() {
  1551. this.m = new Float32Array(16);
  1552. }
  1553. // Properties
  1554. Matrix.prototype.isIdentity = function () {
  1555. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1556. return false;
  1557. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1558. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1559. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1560. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1561. return false;
  1562. return true;
  1563. };
  1564. Matrix.prototype.determinant = function () {
  1565. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1566. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1567. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1568. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1569. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1570. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1571. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1572. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1573. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1574. };
  1575. // Methods
  1576. Matrix.prototype.toArray = function () {
  1577. return this.m;
  1578. };
  1579. Matrix.prototype.asArray = function () {
  1580. return this.toArray();
  1581. };
  1582. Matrix.prototype.invert = function () {
  1583. this.invertToRef(this);
  1584. return this;
  1585. };
  1586. Matrix.prototype.reset = function () {
  1587. for (var index = 0; index < 16; index++) {
  1588. this.m[index] = 0;
  1589. }
  1590. return this;
  1591. };
  1592. Matrix.prototype.add = function (other) {
  1593. var result = new Matrix();
  1594. this.addToRef(other, result);
  1595. return result;
  1596. };
  1597. Matrix.prototype.addToRef = function (other, result) {
  1598. for (var index = 0; index < 16; index++) {
  1599. result.m[index] = this.m[index] + other.m[index];
  1600. }
  1601. return this;
  1602. };
  1603. Matrix.prototype.addToSelf = function (other) {
  1604. for (var index = 0; index < 16; index++) {
  1605. this.m[index] += other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.invertToRef = function (other) {
  1610. var l1 = this.m[0];
  1611. var l2 = this.m[1];
  1612. var l3 = this.m[2];
  1613. var l4 = this.m[3];
  1614. var l5 = this.m[4];
  1615. var l6 = this.m[5];
  1616. var l7 = this.m[6];
  1617. var l8 = this.m[7];
  1618. var l9 = this.m[8];
  1619. var l10 = this.m[9];
  1620. var l11 = this.m[10];
  1621. var l12 = this.m[11];
  1622. var l13 = this.m[12];
  1623. var l14 = this.m[13];
  1624. var l15 = this.m[14];
  1625. var l16 = this.m[15];
  1626. var l17 = (l11 * l16) - (l12 * l15);
  1627. var l18 = (l10 * l16) - (l12 * l14);
  1628. var l19 = (l10 * l15) - (l11 * l14);
  1629. var l20 = (l9 * l16) - (l12 * l13);
  1630. var l21 = (l9 * l15) - (l11 * l13);
  1631. var l22 = (l9 * l14) - (l10 * l13);
  1632. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1633. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1634. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1635. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1636. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1637. var l28 = (l7 * l16) - (l8 * l15);
  1638. var l29 = (l6 * l16) - (l8 * l14);
  1639. var l30 = (l6 * l15) - (l7 * l14);
  1640. var l31 = (l5 * l16) - (l8 * l13);
  1641. var l32 = (l5 * l15) - (l7 * l13);
  1642. var l33 = (l5 * l14) - (l6 * l13);
  1643. var l34 = (l7 * l12) - (l8 * l11);
  1644. var l35 = (l6 * l12) - (l8 * l10);
  1645. var l36 = (l6 * l11) - (l7 * l10);
  1646. var l37 = (l5 * l12) - (l8 * l9);
  1647. var l38 = (l5 * l11) - (l7 * l9);
  1648. var l39 = (l5 * l10) - (l6 * l9);
  1649. other.m[0] = l23 * l27;
  1650. other.m[4] = l24 * l27;
  1651. other.m[8] = l25 * l27;
  1652. other.m[12] = l26 * l27;
  1653. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1654. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1655. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1656. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1657. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1658. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1659. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1660. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1661. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1662. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1663. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1664. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1665. return this;
  1666. };
  1667. Matrix.prototype.setTranslation = function (vector3) {
  1668. this.m[12] = vector3.x;
  1669. this.m[13] = vector3.y;
  1670. this.m[14] = vector3.z;
  1671. return this;
  1672. };
  1673. Matrix.prototype.multiply = function (other) {
  1674. var result = new Matrix();
  1675. this.multiplyToRef(other, result);
  1676. return result;
  1677. };
  1678. Matrix.prototype.copyFrom = function (other) {
  1679. for (var index = 0; index < 16; index++) {
  1680. this.m[index] = other.m[index];
  1681. }
  1682. return this;
  1683. };
  1684. Matrix.prototype.copyToArray = function (array, offset) {
  1685. if (offset === void 0) { offset = 0; }
  1686. for (var index = 0; index < 16; index++) {
  1687. array[offset + index] = this.m[index];
  1688. }
  1689. return this;
  1690. };
  1691. Matrix.prototype.multiplyToRef = function (other, result) {
  1692. this.multiplyToArray(other, result.m, 0);
  1693. return this;
  1694. };
  1695. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1696. var tm0 = this.m[0];
  1697. var tm1 = this.m[1];
  1698. var tm2 = this.m[2];
  1699. var tm3 = this.m[3];
  1700. var tm4 = this.m[4];
  1701. var tm5 = this.m[5];
  1702. var tm6 = this.m[6];
  1703. var tm7 = this.m[7];
  1704. var tm8 = this.m[8];
  1705. var tm9 = this.m[9];
  1706. var tm10 = this.m[10];
  1707. var tm11 = this.m[11];
  1708. var tm12 = this.m[12];
  1709. var tm13 = this.m[13];
  1710. var tm14 = this.m[14];
  1711. var tm15 = this.m[15];
  1712. var om0 = other.m[0];
  1713. var om1 = other.m[1];
  1714. var om2 = other.m[2];
  1715. var om3 = other.m[3];
  1716. var om4 = other.m[4];
  1717. var om5 = other.m[5];
  1718. var om6 = other.m[6];
  1719. var om7 = other.m[7];
  1720. var om8 = other.m[8];
  1721. var om9 = other.m[9];
  1722. var om10 = other.m[10];
  1723. var om11 = other.m[11];
  1724. var om12 = other.m[12];
  1725. var om13 = other.m[13];
  1726. var om14 = other.m[14];
  1727. var om15 = other.m[15];
  1728. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1729. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1730. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1731. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1732. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1733. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1734. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1735. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1736. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1737. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1738. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1739. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1740. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1741. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1742. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1743. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1744. return this;
  1745. };
  1746. Matrix.prototype.equals = function (value) {
  1747. return value &&
  1748. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1749. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1750. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1751. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1752. };
  1753. Matrix.prototype.clone = function () {
  1754. 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]);
  1755. };
  1756. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1757. translation.x = this.m[12];
  1758. translation.y = this.m[13];
  1759. translation.z = this.m[14];
  1760. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1761. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1762. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1763. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1764. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1765. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1766. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1767. rotation.x = 0;
  1768. rotation.y = 0;
  1769. rotation.z = 0;
  1770. rotation.w = 1;
  1771. return false;
  1772. }
  1773. 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);
  1774. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1775. return true;
  1776. };
  1777. // Statics
  1778. Matrix.FromArray = function (array, offset) {
  1779. var result = new Matrix();
  1780. if (!offset) {
  1781. offset = 0;
  1782. }
  1783. Matrix.FromArrayToRef(array, offset, result);
  1784. return result;
  1785. };
  1786. Matrix.FromArrayToRef = function (array, offset, result) {
  1787. for (var index = 0; index < 16; index++) {
  1788. result.m[index] = array[index + offset];
  1789. }
  1790. };
  1791. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1792. for (var index = 0; index < 16; index++) {
  1793. result.m[index] = array[index + offset] * scale;
  1794. }
  1795. };
  1796. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1797. result.m[0] = initialM11;
  1798. result.m[1] = initialM12;
  1799. result.m[2] = initialM13;
  1800. result.m[3] = initialM14;
  1801. result.m[4] = initialM21;
  1802. result.m[5] = initialM22;
  1803. result.m[6] = initialM23;
  1804. result.m[7] = initialM24;
  1805. result.m[8] = initialM31;
  1806. result.m[9] = initialM32;
  1807. result.m[10] = initialM33;
  1808. result.m[11] = initialM34;
  1809. result.m[12] = initialM41;
  1810. result.m[13] = initialM42;
  1811. result.m[14] = initialM43;
  1812. result.m[15] = initialM44;
  1813. };
  1814. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1815. var result = new Matrix();
  1816. result.m[0] = initialM11;
  1817. result.m[1] = initialM12;
  1818. result.m[2] = initialM13;
  1819. result.m[3] = initialM14;
  1820. result.m[4] = initialM21;
  1821. result.m[5] = initialM22;
  1822. result.m[6] = initialM23;
  1823. result.m[7] = initialM24;
  1824. result.m[8] = initialM31;
  1825. result.m[9] = initialM32;
  1826. result.m[10] = initialM33;
  1827. result.m[11] = initialM34;
  1828. result.m[12] = initialM41;
  1829. result.m[13] = initialM42;
  1830. result.m[14] = initialM43;
  1831. result.m[15] = initialM44;
  1832. return result;
  1833. };
  1834. Matrix.Compose = function (scale, rotation, translation) {
  1835. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1836. var rotationMatrix = Matrix.Identity();
  1837. rotation.toRotationMatrix(rotationMatrix);
  1838. result = result.multiply(rotationMatrix);
  1839. result.setTranslation(translation);
  1840. return result;
  1841. };
  1842. Matrix.Identity = function () {
  1843. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1844. };
  1845. Matrix.IdentityToRef = function (result) {
  1846. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1847. };
  1848. Matrix.Zero = function () {
  1849. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1850. };
  1851. Matrix.RotationX = function (angle) {
  1852. var result = new Matrix();
  1853. Matrix.RotationXToRef(angle, result);
  1854. return result;
  1855. };
  1856. Matrix.Invert = function (source) {
  1857. var result = new Matrix();
  1858. source.invertToRef(result);
  1859. return result;
  1860. };
  1861. Matrix.RotationXToRef = function (angle, result) {
  1862. var s = Math.sin(angle);
  1863. var c = Math.cos(angle);
  1864. result.m[0] = 1.0;
  1865. result.m[15] = 1.0;
  1866. result.m[5] = c;
  1867. result.m[10] = c;
  1868. result.m[9] = -s;
  1869. result.m[6] = s;
  1870. result.m[1] = 0;
  1871. result.m[2] = 0;
  1872. result.m[3] = 0;
  1873. result.m[4] = 0;
  1874. result.m[7] = 0;
  1875. result.m[8] = 0;
  1876. result.m[11] = 0;
  1877. result.m[12] = 0;
  1878. result.m[13] = 0;
  1879. result.m[14] = 0;
  1880. };
  1881. Matrix.RotationY = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationYToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.RotationYToRef = function (angle, result) {
  1887. var s = Math.sin(angle);
  1888. var c = Math.cos(angle);
  1889. result.m[5] = 1.0;
  1890. result.m[15] = 1.0;
  1891. result.m[0] = c;
  1892. result.m[2] = -s;
  1893. result.m[8] = s;
  1894. result.m[10] = c;
  1895. result.m[1] = 0;
  1896. result.m[3] = 0;
  1897. result.m[4] = 0;
  1898. result.m[6] = 0;
  1899. result.m[7] = 0;
  1900. result.m[9] = 0;
  1901. result.m[11] = 0;
  1902. result.m[12] = 0;
  1903. result.m[13] = 0;
  1904. result.m[14] = 0;
  1905. };
  1906. Matrix.RotationZ = function (angle) {
  1907. var result = new Matrix();
  1908. Matrix.RotationZToRef(angle, result);
  1909. return result;
  1910. };
  1911. Matrix.RotationZToRef = function (angle, result) {
  1912. var s = Math.sin(angle);
  1913. var c = Math.cos(angle);
  1914. result.m[10] = 1.0;
  1915. result.m[15] = 1.0;
  1916. result.m[0] = c;
  1917. result.m[1] = s;
  1918. result.m[4] = -s;
  1919. result.m[5] = c;
  1920. result.m[2] = 0;
  1921. result.m[3] = 0;
  1922. result.m[6] = 0;
  1923. result.m[7] = 0;
  1924. result.m[8] = 0;
  1925. result.m[9] = 0;
  1926. result.m[11] = 0;
  1927. result.m[12] = 0;
  1928. result.m[13] = 0;
  1929. result.m[14] = 0;
  1930. };
  1931. Matrix.RotationAxis = function (axis, angle) {
  1932. var result = Matrix.Zero();
  1933. Matrix.RotationAxisToRef(axis, angle, result);
  1934. return result;
  1935. };
  1936. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1937. var s = Math.sin(-angle);
  1938. var c = Math.cos(-angle);
  1939. var c1 = 1 - c;
  1940. axis.normalize();
  1941. result.m[0] = (axis.x * axis.x) * c1 + c;
  1942. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1943. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1944. result.m[3] = 0.0;
  1945. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1946. result.m[5] = (axis.y * axis.y) * c1 + c;
  1947. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1948. result.m[7] = 0.0;
  1949. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1950. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1951. result.m[10] = (axis.z * axis.z) * c1 + c;
  1952. result.m[11] = 0.0;
  1953. result.m[15] = 1.0;
  1954. };
  1955. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1956. var result = new Matrix();
  1957. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1958. return result;
  1959. };
  1960. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1961. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1962. this._tempQuaternion.toRotationMatrix(result);
  1963. };
  1964. Matrix.Scaling = function (x, y, z) {
  1965. var result = Matrix.Zero();
  1966. Matrix.ScalingToRef(x, y, z, result);
  1967. return result;
  1968. };
  1969. Matrix.ScalingToRef = function (x, y, z, result) {
  1970. result.m[0] = x;
  1971. result.m[1] = 0;
  1972. result.m[2] = 0;
  1973. result.m[3] = 0;
  1974. result.m[4] = 0;
  1975. result.m[5] = y;
  1976. result.m[6] = 0;
  1977. result.m[7] = 0;
  1978. result.m[8] = 0;
  1979. result.m[9] = 0;
  1980. result.m[10] = z;
  1981. result.m[11] = 0;
  1982. result.m[12] = 0;
  1983. result.m[13] = 0;
  1984. result.m[14] = 0;
  1985. result.m[15] = 1.0;
  1986. };
  1987. Matrix.Translation = function (x, y, z) {
  1988. var result = Matrix.Identity();
  1989. Matrix.TranslationToRef(x, y, z, result);
  1990. return result;
  1991. };
  1992. Matrix.TranslationToRef = function (x, y, z, result) {
  1993. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1994. };
  1995. Matrix.Lerp = function (startValue, endValue, gradient) {
  1996. var startScale = new Vector3(0, 0, 0);
  1997. var startRotation = new Quaternion();
  1998. var startTranslation = new Vector3(0, 0, 0);
  1999. startValue.decompose(startScale, startRotation, startTranslation);
  2000. var endScale = new Vector3(0, 0, 0);
  2001. var endRotation = new Quaternion();
  2002. var endTranslation = new Vector3(0, 0, 0);
  2003. endValue.decompose(endScale, endRotation, endTranslation);
  2004. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2005. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2006. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2007. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2008. };
  2009. Matrix.LookAtLH = function (eye, target, up) {
  2010. var result = Matrix.Zero();
  2011. Matrix.LookAtLHToRef(eye, target, up, result);
  2012. return result;
  2013. };
  2014. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2015. // Z axis
  2016. target.subtractToRef(eye, this._zAxis);
  2017. this._zAxis.normalize();
  2018. // X axis
  2019. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2020. if (this._xAxis.lengthSquared() === 0) {
  2021. this._xAxis.x = 1.0;
  2022. }
  2023. else {
  2024. this._xAxis.normalize();
  2025. }
  2026. // Y axis
  2027. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2028. this._yAxis.normalize();
  2029. // Eye angles
  2030. var ex = -Vector3.Dot(this._xAxis, eye);
  2031. var ey = -Vector3.Dot(this._yAxis, eye);
  2032. var ez = -Vector3.Dot(this._zAxis, eye);
  2033. 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);
  2034. };
  2035. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2036. var matrix = Matrix.Zero();
  2037. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2038. return matrix;
  2039. };
  2040. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2041. var hw = 2.0 / width;
  2042. var hh = 2.0 / height;
  2043. var id = 1.0 / (zfar - znear);
  2044. var nid = znear / (znear - zfar);
  2045. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2046. };
  2047. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2048. var matrix = Matrix.Zero();
  2049. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2050. return matrix;
  2051. };
  2052. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2053. result.m[0] = 2.0 / (right - left);
  2054. result.m[1] = result.m[2] = result.m[3] = 0;
  2055. result.m[5] = 2.0 / (top - bottom);
  2056. result.m[4] = result.m[6] = result.m[7] = 0;
  2057. result.m[10] = -1.0 / (znear - zfar);
  2058. result.m[8] = result.m[9] = result.m[11] = 0;
  2059. result.m[12] = (left + right) / (left - right);
  2060. result.m[13] = (top + bottom) / (bottom - top);
  2061. result.m[14] = znear / (znear - zfar);
  2062. result.m[15] = 1.0;
  2063. };
  2064. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2065. var matrix = Matrix.Zero();
  2066. matrix.m[0] = (2.0 * znear) / width;
  2067. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2068. matrix.m[5] = (2.0 * znear) / height;
  2069. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2070. matrix.m[10] = -zfar / (znear - zfar);
  2071. matrix.m[8] = matrix.m[9] = 0.0;
  2072. matrix.m[11] = 1.0;
  2073. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2074. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2075. return matrix;
  2076. };
  2077. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2083. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2084. var tan = 1.0 / (Math.tan(fov * 0.5));
  2085. if (isVerticalFovFixed) {
  2086. result.m[0] = tan / aspect;
  2087. }
  2088. else {
  2089. result.m[0] = tan;
  2090. }
  2091. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2092. if (isVerticalFovFixed) {
  2093. result.m[5] = tan;
  2094. }
  2095. else {
  2096. result.m[5] = tan * aspect;
  2097. }
  2098. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2099. result.m[8] = result.m[9] = 0.0;
  2100. result.m[10] = -zfar / (znear - zfar);
  2101. result.m[11] = 1.0;
  2102. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2103. result.m[14] = (znear * zfar) / (znear - zfar);
  2104. };
  2105. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2106. var cw = viewport.width;
  2107. var ch = viewport.height;
  2108. var cx = viewport.x;
  2109. var cy = viewport.y;
  2110. 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);
  2111. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2112. };
  2113. Matrix.GetAsMatrix2x2 = function (matrix) {
  2114. return new Float32Array([
  2115. matrix.m[0], matrix.m[1],
  2116. matrix.m[4], matrix.m[5]
  2117. ]);
  2118. };
  2119. Matrix.GetAsMatrix3x3 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1], matrix.m[2],
  2122. matrix.m[4], matrix.m[5], matrix.m[6],
  2123. matrix.m[8], matrix.m[9], matrix.m[10]
  2124. ]);
  2125. };
  2126. Matrix.Transpose = function (matrix) {
  2127. var result = new Matrix();
  2128. result.m[0] = matrix.m[0];
  2129. result.m[1] = matrix.m[4];
  2130. result.m[2] = matrix.m[8];
  2131. result.m[3] = matrix.m[12];
  2132. result.m[4] = matrix.m[1];
  2133. result.m[5] = matrix.m[5];
  2134. result.m[6] = matrix.m[9];
  2135. result.m[7] = matrix.m[13];
  2136. result.m[8] = matrix.m[2];
  2137. result.m[9] = matrix.m[6];
  2138. result.m[10] = matrix.m[10];
  2139. result.m[11] = matrix.m[14];
  2140. result.m[12] = matrix.m[3];
  2141. result.m[13] = matrix.m[7];
  2142. result.m[14] = matrix.m[11];
  2143. result.m[15] = matrix.m[15];
  2144. return result;
  2145. };
  2146. Matrix.Reflection = function (plane) {
  2147. var matrix = new Matrix();
  2148. Matrix.ReflectionToRef(plane, matrix);
  2149. return matrix;
  2150. };
  2151. Matrix.ReflectionToRef = function (plane, result) {
  2152. plane.normalize();
  2153. var x = plane.normal.x;
  2154. var y = plane.normal.y;
  2155. var z = plane.normal.z;
  2156. var temp = -2 * x;
  2157. var temp2 = -2 * y;
  2158. var temp3 = -2 * z;
  2159. result.m[0] = (temp * x) + 1;
  2160. result.m[1] = temp2 * x;
  2161. result.m[2] = temp3 * x;
  2162. result.m[3] = 0.0;
  2163. result.m[4] = temp * y;
  2164. result.m[5] = (temp2 * y) + 1;
  2165. result.m[6] = temp3 * y;
  2166. result.m[7] = 0.0;
  2167. result.m[8] = temp * z;
  2168. result.m[9] = temp2 * z;
  2169. result.m[10] = (temp3 * z) + 1;
  2170. result.m[11] = 0.0;
  2171. result.m[12] = temp * plane.d;
  2172. result.m[13] = temp2 * plane.d;
  2173. result.m[14] = temp3 * plane.d;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix._tempQuaternion = new Quaternion();
  2177. Matrix._xAxis = Vector3.Zero();
  2178. Matrix._yAxis = Vector3.Zero();
  2179. Matrix._zAxis = Vector3.Zero();
  2180. return Matrix;
  2181. })();
  2182. BABYLON.Matrix = Matrix;
  2183. var Plane = (function () {
  2184. function Plane(a, b, c, d) {
  2185. this.normal = new Vector3(a, b, c);
  2186. this.d = d;
  2187. }
  2188. Plane.prototype.asArray = function () {
  2189. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2190. };
  2191. // Methods
  2192. Plane.prototype.clone = function () {
  2193. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2194. };
  2195. Plane.prototype.normalize = function () {
  2196. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2197. var magnitude = 0;
  2198. if (norm !== 0) {
  2199. magnitude = 1.0 / norm;
  2200. }
  2201. this.normal.x *= magnitude;
  2202. this.normal.y *= magnitude;
  2203. this.normal.z *= magnitude;
  2204. this.d *= magnitude;
  2205. return this;
  2206. };
  2207. Plane.prototype.transform = function (transformation) {
  2208. var transposedMatrix = Matrix.Transpose(transformation);
  2209. var x = this.normal.x;
  2210. var y = this.normal.y;
  2211. var z = this.normal.z;
  2212. var d = this.d;
  2213. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2214. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2215. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2216. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2217. return new Plane(normalX, normalY, normalZ, finalD);
  2218. };
  2219. Plane.prototype.dotCoordinate = function (point) {
  2220. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2221. };
  2222. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2223. var x1 = point2.x - point1.x;
  2224. var y1 = point2.y - point1.y;
  2225. var z1 = point2.z - point1.z;
  2226. var x2 = point3.x - point1.x;
  2227. var y2 = point3.y - point1.y;
  2228. var z2 = point3.z - point1.z;
  2229. var yz = (y1 * z2) - (z1 * y2);
  2230. var xz = (z1 * x2) - (x1 * z2);
  2231. var xy = (x1 * y2) - (y1 * x2);
  2232. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2233. var invPyth;
  2234. if (pyth !== 0) {
  2235. invPyth = 1.0 / pyth;
  2236. }
  2237. else {
  2238. invPyth = 0;
  2239. }
  2240. this.normal.x = yz * invPyth;
  2241. this.normal.y = xz * invPyth;
  2242. this.normal.z = xy * invPyth;
  2243. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2244. return this;
  2245. };
  2246. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2247. var dot = Vector3.Dot(this.normal, direction);
  2248. return (dot <= epsilon);
  2249. };
  2250. Plane.prototype.signedDistanceTo = function (point) {
  2251. return Vector3.Dot(point, this.normal) + this.d;
  2252. };
  2253. // Statics
  2254. Plane.FromArray = function (array) {
  2255. return new Plane(array[0], array[1], array[2], array[3]);
  2256. };
  2257. Plane.FromPoints = function (point1, point2, point3) {
  2258. var result = new Plane(0, 0, 0, 0);
  2259. result.copyFromPoints(point1, point2, point3);
  2260. return result;
  2261. };
  2262. Plane.FromPositionAndNormal = function (origin, normal) {
  2263. var result = new Plane(0, 0, 0, 0);
  2264. normal.normalize();
  2265. result.normal = normal;
  2266. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2267. return result;
  2268. };
  2269. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2270. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2271. return Vector3.Dot(point, normal) + d;
  2272. };
  2273. return Plane;
  2274. })();
  2275. BABYLON.Plane = Plane;
  2276. var Viewport = (function () {
  2277. function Viewport(x, y, width, height) {
  2278. this.x = x;
  2279. this.y = y;
  2280. this.width = width;
  2281. this.height = height;
  2282. }
  2283. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2284. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2285. };
  2286. return Viewport;
  2287. })();
  2288. BABYLON.Viewport = Viewport;
  2289. var Frustum = (function () {
  2290. function Frustum() {
  2291. }
  2292. Frustum.GetPlanes = function (transform) {
  2293. var frustumPlanes = [];
  2294. for (var index = 0; index < 6; index++) {
  2295. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2296. }
  2297. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2298. return frustumPlanes;
  2299. };
  2300. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2301. // Near
  2302. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2303. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2304. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2305. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2306. frustumPlanes[0].normalize();
  2307. // Far
  2308. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2309. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2310. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2311. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2312. frustumPlanes[1].normalize();
  2313. // Left
  2314. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2315. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2316. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2317. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2318. frustumPlanes[2].normalize();
  2319. // Right
  2320. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2321. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2322. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2323. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2324. frustumPlanes[3].normalize();
  2325. // Top
  2326. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2327. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2328. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2329. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2330. frustumPlanes[4].normalize();
  2331. // Bottom
  2332. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2333. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2334. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2335. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2336. frustumPlanes[5].normalize();
  2337. };
  2338. return Frustum;
  2339. })();
  2340. BABYLON.Frustum = Frustum;
  2341. (function (Space) {
  2342. Space[Space["LOCAL"] = 0] = "LOCAL";
  2343. Space[Space["WORLD"] = 1] = "WORLD";
  2344. })(BABYLON.Space || (BABYLON.Space = {}));
  2345. var Space = BABYLON.Space;
  2346. var Axis = (function () {
  2347. function Axis() {
  2348. }
  2349. Axis.X = new Vector3(1, 0, 0);
  2350. Axis.Y = new Vector3(0, 1, 0);
  2351. Axis.Z = new Vector3(0, 0, 1);
  2352. return Axis;
  2353. })();
  2354. BABYLON.Axis = Axis;
  2355. ;
  2356. var BezierCurve = (function () {
  2357. function BezierCurve() {
  2358. }
  2359. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2360. // Extract X (which is equal to time here)
  2361. var f0 = 1 - 3 * x2 + 3 * x1;
  2362. var f1 = 3 * x2 - 6 * x1;
  2363. var f2 = 3 * x1;
  2364. var refinedT = t;
  2365. for (var i = 0; i < 5; i++) {
  2366. var refinedT2 = refinedT * refinedT;
  2367. var refinedT3 = refinedT2 * refinedT;
  2368. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2369. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2370. refinedT -= (x - t) * slope;
  2371. refinedT = Math.min(1, Math.max(0, refinedT));
  2372. }
  2373. // Resolve cubic bezier for the given x
  2374. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2375. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2376. Math.pow(refinedT, 3);
  2377. };
  2378. return BezierCurve;
  2379. })();
  2380. BABYLON.BezierCurve = BezierCurve;
  2381. (function (Orientation) {
  2382. Orientation[Orientation["CW"] = 0] = "CW";
  2383. Orientation[Orientation["CCW"] = 1] = "CCW";
  2384. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2385. var Orientation = BABYLON.Orientation;
  2386. var Angle = (function () {
  2387. function Angle(radians) {
  2388. var _this = this;
  2389. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2390. this.radians = function () { return _this._radians; };
  2391. this._radians = radians;
  2392. if (this._radians < 0)
  2393. this._radians += (2 * Math.PI);
  2394. }
  2395. Angle.BetweenTwoPoints = function (a, b) {
  2396. var delta = b.subtract(a);
  2397. var theta = Math.atan2(delta.y, delta.x);
  2398. return new Angle(theta);
  2399. };
  2400. Angle.FromRadians = function (radians) {
  2401. return new Angle(radians);
  2402. };
  2403. Angle.FromDegrees = function (degrees) {
  2404. return new Angle(degrees * Math.PI / 180);
  2405. };
  2406. return Angle;
  2407. })();
  2408. BABYLON.Angle = Angle;
  2409. var Arc2 = (function () {
  2410. function Arc2(startPoint, midPoint, endPoint) {
  2411. this.startPoint = startPoint;
  2412. this.midPoint = midPoint;
  2413. this.endPoint = endPoint;
  2414. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2415. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2416. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2417. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2418. 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);
  2419. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2420. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2421. var a1 = this.startAngle.degrees();
  2422. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2423. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2424. // angles correction
  2425. if (a2 - a1 > +180.0)
  2426. a2 -= 360.0;
  2427. if (a2 - a1 < -180.0)
  2428. a2 += 360.0;
  2429. if (a3 - a2 > +180.0)
  2430. a3 -= 360.0;
  2431. if (a3 - a2 < -180.0)
  2432. a3 += 360.0;
  2433. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2434. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2435. }
  2436. return Arc2;
  2437. })();
  2438. BABYLON.Arc2 = Arc2;
  2439. var Path2 = (function () {
  2440. function Path2(x, y) {
  2441. this._points = new Array();
  2442. this._length = 0;
  2443. this.closed = false;
  2444. this._points.push(new Vector2(x, y));
  2445. }
  2446. Path2.prototype.addLineTo = function (x, y) {
  2447. if (closed) {
  2448. //Tools.Error("cannot add lines to closed paths");
  2449. return this;
  2450. }
  2451. var newPoint = new Vector2(x, y);
  2452. var previousPoint = this._points[this._points.length - 1];
  2453. this._points.push(newPoint);
  2454. this._length += newPoint.subtract(previousPoint).length();
  2455. return this;
  2456. };
  2457. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2458. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2459. if (closed) {
  2460. //Tools.Error("cannot add arcs to closed paths");
  2461. return this;
  2462. }
  2463. var startPoint = this._points[this._points.length - 1];
  2464. var midPoint = new Vector2(midX, midY);
  2465. var endPoint = new Vector2(endX, endY);
  2466. var arc = new Arc2(startPoint, midPoint, endPoint);
  2467. var increment = arc.angle.radians() / numberOfSegments;
  2468. if (arc.orientation === Orientation.CW)
  2469. increment *= -1;
  2470. var currentAngle = arc.startAngle.radians() + increment;
  2471. for (var i = 0; i < numberOfSegments; i++) {
  2472. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2473. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2474. this.addLineTo(x, y);
  2475. currentAngle += increment;
  2476. }
  2477. return this;
  2478. };
  2479. Path2.prototype.close = function () {
  2480. this.closed = true;
  2481. return this;
  2482. };
  2483. Path2.prototype.length = function () {
  2484. var result = this._length;
  2485. if (!this.closed) {
  2486. var lastPoint = this._points[this._points.length - 1];
  2487. var firstPoint = this._points[0];
  2488. result += (firstPoint.subtract(lastPoint).length());
  2489. }
  2490. return result;
  2491. };
  2492. Path2.prototype.getPoints = function () {
  2493. return this._points;
  2494. };
  2495. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2496. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2497. //Tools.Error("normalized length position should be between 0 and 1.");
  2498. return Vector2.Zero();
  2499. }
  2500. var lengthPosition = normalizedLengthPosition * this.length();
  2501. var previousOffset = 0;
  2502. for (var i = 0; i < this._points.length; i++) {
  2503. var j = (i + 1) % this._points.length;
  2504. var a = this._points[i];
  2505. var b = this._points[j];
  2506. var bToA = b.subtract(a);
  2507. var nextOffset = (bToA.length() + previousOffset);
  2508. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2509. var dir = bToA.normalize();
  2510. var localOffset = lengthPosition - previousOffset;
  2511. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2512. }
  2513. previousOffset = nextOffset;
  2514. }
  2515. //Tools.Error("internal error");
  2516. return Vector2.Zero();
  2517. };
  2518. Path2.StartingAt = function (x, y) {
  2519. return new Path2(x, y);
  2520. };
  2521. return Path2;
  2522. })();
  2523. BABYLON.Path2 = Path2;
  2524. var Path3D = (function () {
  2525. /**
  2526. * new Path3D(path, normal, raw)
  2527. * path : an array of Vector3, the curve axis of the Path3D
  2528. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2529. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2530. */
  2531. function Path3D(path, firstNormal, raw) {
  2532. this.path = path;
  2533. this._curve = new Array();
  2534. this._distances = new Array();
  2535. this._tangents = new Array();
  2536. this._normals = new Array();
  2537. this._binormals = new Array();
  2538. for (var p = 0; p < path.length; p++) {
  2539. this._curve[p] = path[p].clone(); // hard copy
  2540. }
  2541. this._raw = raw || false;
  2542. this._compute(firstNormal);
  2543. }
  2544. Path3D.prototype.getCurve = function () {
  2545. return this._curve;
  2546. };
  2547. Path3D.prototype.getTangents = function () {
  2548. return this._tangents;
  2549. };
  2550. Path3D.prototype.getNormals = function () {
  2551. return this._normals;
  2552. };
  2553. Path3D.prototype.getBinormals = function () {
  2554. return this._binormals;
  2555. };
  2556. Path3D.prototype.getDistances = function () {
  2557. return this._distances;
  2558. };
  2559. Path3D.prototype.update = function (path, firstNormal) {
  2560. for (var p = 0; p < path.length; p++) {
  2561. this._curve[p].x = path[p].x;
  2562. this._curve[p].y = path[p].y;
  2563. this._curve[p].z = path[p].z;
  2564. }
  2565. this._compute(firstNormal);
  2566. return this;
  2567. };
  2568. // private function compute() : computes tangents, normals and binormals
  2569. Path3D.prototype._compute = function (firstNormal) {
  2570. var l = this._curve.length;
  2571. // first and last tangents
  2572. this._tangents[0] = this._getFirstNonNullVector(0);
  2573. if (!this._raw) {
  2574. this._tangents[0].normalize();
  2575. }
  2576. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2577. if (!this._raw) {
  2578. this._tangents[l - 1].normalize();
  2579. }
  2580. // normals and binormals at first point : arbitrary vector with _normalVector()
  2581. var tg0 = this._tangents[0];
  2582. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2583. this._normals[0] = pp0;
  2584. if (!this._raw) {
  2585. this._normals[0].normalize();
  2586. }
  2587. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2588. if (!this._raw) {
  2589. this._binormals[0].normalize();
  2590. }
  2591. this._distances[0] = 0;
  2592. // normals and binormals : next points
  2593. var prev; // previous vector (segment)
  2594. var cur; // current vector (segment)
  2595. var curTang; // current tangent
  2596. // previous normal
  2597. var prevBinor; // previous binormal
  2598. for (var i = 1; i < l; i++) {
  2599. // tangents
  2600. prev = this._getLastNonNullVector(i);
  2601. if (i < l - 1) {
  2602. cur = this._getFirstNonNullVector(i);
  2603. this._tangents[i] = prev.add(cur);
  2604. this._tangents[i].normalize();
  2605. }
  2606. this._distances[i] = this._distances[i - 1] + prev.length();
  2607. // normals and binormals
  2608. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2609. curTang = this._tangents[i];
  2610. prevBinor = this._binormals[i - 1];
  2611. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2612. if (!this._raw) {
  2613. this._normals[i].normalize();
  2614. }
  2615. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2616. if (!this._raw) {
  2617. this._binormals[i].normalize();
  2618. }
  2619. }
  2620. };
  2621. // private function getFirstNonNullVector(index)
  2622. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2623. Path3D.prototype._getFirstNonNullVector = function (index) {
  2624. var i = 1;
  2625. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2626. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2627. i++;
  2628. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2629. }
  2630. return nNVector;
  2631. };
  2632. // private function getLastNonNullVector(index)
  2633. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2634. Path3D.prototype._getLastNonNullVector = function (index) {
  2635. var i = 1;
  2636. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2637. while (nLVector.length() === 0 && index > i + 1) {
  2638. i++;
  2639. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2640. }
  2641. return nLVector;
  2642. };
  2643. // private function normalVector(v0, vt, va) :
  2644. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2645. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2646. Path3D.prototype._normalVector = function (v0, vt, va) {
  2647. var normal0;
  2648. if (va === undefined || va === null) {
  2649. var point;
  2650. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2651. point = new Vector3(0, -1, 0);
  2652. }
  2653. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2654. point = new Vector3(1, 0, 0);
  2655. }
  2656. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2657. point = new Vector3(0, 0, 1);
  2658. }
  2659. normal0 = Vector3.Cross(vt, point);
  2660. }
  2661. else {
  2662. normal0 = Vector3.Cross(vt, va);
  2663. Vector3.CrossToRef(normal0, vt, normal0);
  2664. }
  2665. normal0.normalize();
  2666. return normal0;
  2667. };
  2668. return Path3D;
  2669. })();
  2670. BABYLON.Path3D = Path3D;
  2671. var Curve3 = (function () {
  2672. function Curve3(points) {
  2673. this._length = 0;
  2674. this._points = points;
  2675. this._length = this._computeLength(points);
  2676. }
  2677. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2678. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2679. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2680. var bez = new Array();
  2681. var equation = function (t, val0, val1, val2) {
  2682. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2683. return res;
  2684. };
  2685. for (var i = 0; i <= nbPoints; i++) {
  2686. 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)));
  2687. }
  2688. return new Curve3(bez);
  2689. };
  2690. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2691. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2692. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2693. var bez = new Array();
  2694. var equation = function (t, val0, val1, val2, val3) {
  2695. 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;
  2696. return res;
  2697. };
  2698. for (var i = 0; i <= nbPoints; i++) {
  2699. 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)));
  2700. }
  2701. return new Curve3(bez);
  2702. };
  2703. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2704. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2705. var hermite = new Array();
  2706. var step = 1 / nbPoints;
  2707. for (var i = 0; i <= nbPoints; i++) {
  2708. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2709. }
  2710. return new Curve3(hermite);
  2711. };
  2712. Curve3.prototype.getPoints = function () {
  2713. return this._points;
  2714. };
  2715. Curve3.prototype.length = function () {
  2716. return this._length;
  2717. };
  2718. Curve3.prototype.continue = function (curve) {
  2719. var lastPoint = this._points[this._points.length - 1];
  2720. var continuedPoints = this._points.slice();
  2721. var curvePoints = curve.getPoints();
  2722. for (var i = 1; i < curvePoints.length; i++) {
  2723. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2724. }
  2725. var continuedCurve = new Curve3(continuedPoints);
  2726. return continuedCurve;
  2727. };
  2728. Curve3.prototype._computeLength = function (path) {
  2729. var l = 0;
  2730. for (var i = 1; i < path.length; i++) {
  2731. l += (path[i].subtract(path[i - 1])).length();
  2732. }
  2733. return l;
  2734. };
  2735. return Curve3;
  2736. })();
  2737. BABYLON.Curve3 = Curve3;
  2738. // SphericalHarmonics
  2739. var SphericalHarmonics = (function () {
  2740. function SphericalHarmonics() {
  2741. this.L00 = Vector3.Zero();
  2742. this.L1_1 = Vector3.Zero();
  2743. this.L10 = Vector3.Zero();
  2744. this.L11 = Vector3.Zero();
  2745. this.L2_2 = Vector3.Zero();
  2746. this.L2_1 = Vector3.Zero();
  2747. this.L20 = Vector3.Zero();
  2748. this.L21 = Vector3.Zero();
  2749. this.L22 = Vector3.Zero();
  2750. }
  2751. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2752. var colorVector = new Vector3(color.r, color.g, color.b);
  2753. var c = colorVector.scale(deltaSolidAngle);
  2754. this.L00 = this.L00.add(c.scale(0.282095));
  2755. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2756. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2757. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2758. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2759. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2760. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2761. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2762. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2763. };
  2764. SphericalHarmonics.prototype.scale = function (scale) {
  2765. this.L00 = this.L00.scale(scale);
  2766. this.L1_1 = this.L1_1.scale(scale);
  2767. this.L10 = this.L10.scale(scale);
  2768. this.L11 = this.L11.scale(scale);
  2769. this.L2_2 = this.L2_2.scale(scale);
  2770. this.L2_1 = this.L2_1.scale(scale);
  2771. this.L20 = this.L20.scale(scale);
  2772. this.L21 = this.L21.scale(scale);
  2773. this.L22 = this.L22.scale(scale);
  2774. };
  2775. return SphericalHarmonics;
  2776. })();
  2777. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2778. // SphericalPolynomial
  2779. var SphericalPolynomial = (function () {
  2780. function SphericalPolynomial() {
  2781. this.x = Vector3.Zero();
  2782. this.y = Vector3.Zero();
  2783. this.z = Vector3.Zero();
  2784. this.xx = Vector3.Zero();
  2785. this.yy = Vector3.Zero();
  2786. this.zz = Vector3.Zero();
  2787. this.xy = Vector3.Zero();
  2788. this.yz = Vector3.Zero();
  2789. this.zx = Vector3.Zero();
  2790. }
  2791. SphericalPolynomial.prototype.addAmbient = function (color) {
  2792. var colorVector = new Vector3(color.r, color.g, color.b);
  2793. this.xx = this.xx.add(colorVector);
  2794. this.yy = this.yy.add(colorVector);
  2795. this.zz = this.zz.add(colorVector);
  2796. };
  2797. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2798. var result = new SphericalPolynomial();
  2799. result.x = harmonics.L11.scale(1.02333);
  2800. result.y = harmonics.L1_1.scale(1.02333);
  2801. result.z = harmonics.L10.scale(1.02333);
  2802. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2803. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2804. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2805. result.yz = harmonics.L2_1.scale(0.858086);
  2806. result.zx = harmonics.L21.scale(0.858086);
  2807. result.xy = harmonics.L2_2.scale(0.858086);
  2808. return result;
  2809. };
  2810. return SphericalPolynomial;
  2811. })();
  2812. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2813. // Vertex formats
  2814. var PositionNormalVertex = (function () {
  2815. function PositionNormalVertex(position, normal) {
  2816. if (position === void 0) { position = Vector3.Zero(); }
  2817. if (normal === void 0) { normal = Vector3.Up(); }
  2818. this.position = position;
  2819. this.normal = normal;
  2820. }
  2821. PositionNormalVertex.prototype.clone = function () {
  2822. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2823. };
  2824. return PositionNormalVertex;
  2825. })();
  2826. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2827. var PositionNormalTextureVertex = (function () {
  2828. function PositionNormalTextureVertex(position, normal, uv) {
  2829. if (position === void 0) { position = Vector3.Zero(); }
  2830. if (normal === void 0) { normal = Vector3.Up(); }
  2831. if (uv === void 0) { uv = Vector2.Zero(); }
  2832. this.position = position;
  2833. this.normal = normal;
  2834. this.uv = uv;
  2835. }
  2836. PositionNormalTextureVertex.prototype.clone = function () {
  2837. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2838. };
  2839. return PositionNormalTextureVertex;
  2840. })();
  2841. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2842. // Temporary pre-allocated objects for engine internal use
  2843. // usage in any internal function :
  2844. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2845. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2846. var Tmp = (function () {
  2847. function Tmp() {
  2848. }
  2849. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2850. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2851. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2852. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2853. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2854. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2855. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2856. Matrix.Zero(), Matrix.Zero(),
  2857. Matrix.Zero(), Matrix.Zero(),
  2858. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2859. return Tmp;
  2860. })();
  2861. BABYLON.Tmp = Tmp;
  2862. })(BABYLON || (BABYLON = {}));
  2863. var BABYLON;
  2864. (function (BABYLON) {
  2865. function generateSerializableMember(type, sourceName) {
  2866. return function (target, propertyKey) {
  2867. if (!target.__serializableMembers) {
  2868. target.__serializableMembers = {};
  2869. }
  2870. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2871. };
  2872. }
  2873. function serialize(sourceName) {
  2874. return generateSerializableMember(0, sourceName); // value member
  2875. }
  2876. BABYLON.serialize = serialize;
  2877. function serializeAsTexture(sourceName) {
  2878. return generateSerializableMember(1, sourceName); // texture member
  2879. }
  2880. BABYLON.serializeAsTexture = serializeAsTexture;
  2881. function serializeAsColor3(sourceName) {
  2882. return generateSerializableMember(2, sourceName); // color3 member
  2883. }
  2884. BABYLON.serializeAsColor3 = serializeAsColor3;
  2885. function serializeAsFresnelParameters(sourceName) {
  2886. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2887. }
  2888. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2889. function serializeAsVector2(sourceName) {
  2890. return generateSerializableMember(4, sourceName); // vector2 member
  2891. }
  2892. BABYLON.serializeAsVector2 = serializeAsVector2;
  2893. function serializeAsVector3(sourceName) {
  2894. return generateSerializableMember(5, sourceName); // vector3 member
  2895. }
  2896. BABYLON.serializeAsVector3 = serializeAsVector3;
  2897. function serializeAsMeshReference(sourceName) {
  2898. return generateSerializableMember(6, sourceName); // mesh reference member
  2899. }
  2900. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2901. var SerializationHelper = (function () {
  2902. function SerializationHelper() {
  2903. }
  2904. SerializationHelper.Serialize = function (entity, serializationObject) {
  2905. if (!serializationObject) {
  2906. serializationObject = {};
  2907. }
  2908. // Tags
  2909. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2910. // Properties
  2911. for (var property in entity.__serializableMembers) {
  2912. var propertyDescriptor = entity.__serializableMembers[property];
  2913. var targetPropertyName = propertyDescriptor.sourceName || property;
  2914. var propertyType = propertyDescriptor.type;
  2915. var sourceProperty = entity[property];
  2916. if (sourceProperty !== undefined && sourceProperty !== null) {
  2917. switch (propertyType) {
  2918. case 0:
  2919. serializationObject[targetPropertyName] = sourceProperty;
  2920. break;
  2921. case 1:
  2922. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2923. break;
  2924. case 2:
  2925. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2926. break;
  2927. case 3:
  2928. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2929. break;
  2930. case 4:
  2931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2932. break;
  2933. case 5:
  2934. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2935. break;
  2936. case 6:
  2937. serializationObject[targetPropertyName] = sourceProperty.id;
  2938. break;
  2939. }
  2940. }
  2941. }
  2942. return serializationObject;
  2943. };
  2944. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  2945. var destination = creationFunction();
  2946. // Tags
  2947. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2948. // Properties
  2949. for (var property in destination.__serializableMembers) {
  2950. var propertyDescriptor = destination.__serializableMembers[property];
  2951. var sourceProperty = source[propertyDescriptor.sourceName || property];
  2952. var propertyType = propertyDescriptor.type;
  2953. if (sourceProperty !== undefined && sourceProperty !== null) {
  2954. switch (propertyType) {
  2955. case 0:
  2956. destination[property] = sourceProperty;
  2957. break;
  2958. case 1:
  2959. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  2960. break;
  2961. case 2:
  2962. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  2963. break;
  2964. case 3:
  2965. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  2966. break;
  2967. case 4:
  2968. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  2969. break;
  2970. case 5:
  2971. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  2972. break;
  2973. case 6:
  2974. destination[property] = scene.getLastMeshByID(sourceProperty);
  2975. break;
  2976. }
  2977. }
  2978. }
  2979. return destination;
  2980. };
  2981. SerializationHelper.Clone = function (creationFunction, source) {
  2982. var destination = creationFunction();
  2983. // Tags
  2984. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2985. // Properties
  2986. for (var property in destination.__serializableMembers) {
  2987. var propertyDescriptor = destination.__serializableMembers[property];
  2988. var sourceProperty = source[property];
  2989. var propertyType = propertyDescriptor.type;
  2990. if (sourceProperty !== undefined && sourceProperty !== null) {
  2991. switch (propertyType) {
  2992. case 0: // Value
  2993. case 6:
  2994. destination[property] = sourceProperty;
  2995. break;
  2996. case 1: // Texture
  2997. case 2: // Color3
  2998. case 3: // FresnelParameters
  2999. case 4: // Vector2
  3000. case 5:
  3001. destination[property] = sourceProperty.clone();
  3002. break;
  3003. }
  3004. }
  3005. }
  3006. return destination;
  3007. };
  3008. return SerializationHelper;
  3009. })();
  3010. BABYLON.SerializationHelper = SerializationHelper;
  3011. })(BABYLON || (BABYLON = {}));
  3012. var BABYLON;
  3013. (function (BABYLON) {
  3014. var Database = (function () {
  3015. function Database(urlToScene, callbackManifestChecked) {
  3016. // Handling various flavors of prefixed version of IndexedDB
  3017. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3018. this.callbackManifestChecked = callbackManifestChecked;
  3019. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3020. this.db = null;
  3021. this.enableSceneOffline = false;
  3022. this.enableTexturesOffline = false;
  3023. this.manifestVersionFound = 0;
  3024. this.mustUpdateRessources = false;
  3025. this.hasReachedQuota = false;
  3026. if (!Database.IDBStorageEnabled) {
  3027. this.callbackManifestChecked(true);
  3028. }
  3029. else {
  3030. this.checkManifestFile();
  3031. }
  3032. }
  3033. Database.prototype.checkManifestFile = function () {
  3034. var _this = this;
  3035. function noManifestFile() {
  3036. that.enableSceneOffline = false;
  3037. that.enableTexturesOffline = false;
  3038. that.callbackManifestChecked(false);
  3039. }
  3040. var that = this;
  3041. var timeStampUsed = false;
  3042. var manifestURL = this.currentSceneUrl + ".manifest";
  3043. var xhr = new XMLHttpRequest();
  3044. if (navigator.onLine) {
  3045. // Adding a timestamp to by-pass browsers' cache
  3046. timeStampUsed = true;
  3047. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3048. }
  3049. xhr.open("GET", manifestURL, true);
  3050. xhr.addEventListener("load", function () {
  3051. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3052. try {
  3053. var manifestFile = JSON.parse(xhr.response);
  3054. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3055. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3056. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3057. _this.manifestVersionFound = manifestFile.version;
  3058. }
  3059. if (_this.callbackManifestChecked) {
  3060. _this.callbackManifestChecked(true);
  3061. }
  3062. }
  3063. catch (ex) {
  3064. noManifestFile();
  3065. }
  3066. }
  3067. else {
  3068. noManifestFile();
  3069. }
  3070. }, false);
  3071. xhr.addEventListener("error", function (event) {
  3072. if (timeStampUsed) {
  3073. timeStampUsed = false;
  3074. // Let's retry without the timeStamp
  3075. // It could fail when coupled with HTML5 Offline API
  3076. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3077. xhr.open("GET", retryManifestURL, true);
  3078. xhr.send();
  3079. }
  3080. else {
  3081. noManifestFile();
  3082. }
  3083. }, false);
  3084. try {
  3085. xhr.send();
  3086. }
  3087. catch (ex) {
  3088. BABYLON.Tools.Error("Error on XHR send request.");
  3089. that.callbackManifestChecked(false);
  3090. }
  3091. };
  3092. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3093. var _this = this;
  3094. function handleError() {
  3095. that.isSupported = false;
  3096. if (errorCallback)
  3097. errorCallback();
  3098. }
  3099. var that = this;
  3100. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3101. // Your browser doesn't support IndexedDB
  3102. this.isSupported = false;
  3103. if (errorCallback)
  3104. errorCallback();
  3105. }
  3106. else {
  3107. // If the DB hasn't been opened or created yet
  3108. if (!this.db) {
  3109. this.hasReachedQuota = false;
  3110. this.isSupported = true;
  3111. var request = this.idbFactory.open("babylonjs", 1);
  3112. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3113. request.onerror = function (event) {
  3114. handleError();
  3115. };
  3116. // executes when a version change transaction cannot complete due to other active transactions
  3117. request.onblocked = function (event) {
  3118. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3119. handleError();
  3120. };
  3121. // DB has been opened successfully
  3122. request.onsuccess = function (event) {
  3123. _this.db = request.result;
  3124. successCallback();
  3125. };
  3126. // Initialization of the DB. Creating Scenes & Textures stores
  3127. request.onupgradeneeded = function (event) {
  3128. _this.db = (event.target).result;
  3129. try {
  3130. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3131. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3132. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3133. }
  3134. catch (ex) {
  3135. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3136. handleError();
  3137. }
  3138. };
  3139. }
  3140. else {
  3141. if (successCallback)
  3142. successCallback();
  3143. }
  3144. }
  3145. };
  3146. Database.prototype.loadImageFromDB = function (url, image) {
  3147. var _this = this;
  3148. var completeURL = Database.ReturnFullUrlLocation(url);
  3149. var saveAndLoadImage = function () {
  3150. if (!_this.hasReachedQuota && _this.db !== null) {
  3151. // the texture is not yet in the DB, let's try to save it
  3152. _this._saveImageIntoDBAsync(completeURL, image);
  3153. }
  3154. else {
  3155. image.src = url;
  3156. }
  3157. };
  3158. if (!this.mustUpdateRessources) {
  3159. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3160. }
  3161. else {
  3162. saveAndLoadImage();
  3163. }
  3164. };
  3165. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3166. if (this.isSupported && this.db !== null) {
  3167. var texture;
  3168. var transaction = this.db.transaction(["textures"]);
  3169. transaction.onabort = function (event) {
  3170. image.src = url;
  3171. };
  3172. transaction.oncomplete = function (event) {
  3173. var blobTextureURL;
  3174. if (texture) {
  3175. var URL = window.URL || window.webkitURL;
  3176. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3177. image.onerror = function () {
  3178. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3179. image.src = url;
  3180. };
  3181. image.src = blobTextureURL;
  3182. }
  3183. else {
  3184. notInDBCallback();
  3185. }
  3186. };
  3187. var getRequest = transaction.objectStore("textures").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. texture = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3193. image.src = url;
  3194. };
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. image.src = url;
  3199. }
  3200. };
  3201. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3202. var _this = this;
  3203. if (this.isSupported) {
  3204. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3205. var generateBlobUrl = function () {
  3206. var blobTextureURL;
  3207. if (blob) {
  3208. var URL = window.URL || window.webkitURL;
  3209. try {
  3210. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3211. }
  3212. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3213. catch (ex) {
  3214. blobTextureURL = URL.createObjectURL(blob);
  3215. }
  3216. }
  3217. image.src = blobTextureURL;
  3218. };
  3219. if (Database.IsUASupportingBlobStorage) {
  3220. var xhr = new XMLHttpRequest(), blob;
  3221. xhr.open("GET", url, true);
  3222. xhr.responseType = "blob";
  3223. xhr.addEventListener("load", function () {
  3224. if (xhr.status === 200) {
  3225. // Blob as response (XHR2)
  3226. blob = xhr.response;
  3227. var transaction = _this.db.transaction(["textures"], "readwrite");
  3228. // the transaction could abort because of a QuotaExceededError error
  3229. transaction.onabort = function (event) {
  3230. try {
  3231. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3232. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3233. this.hasReachedQuota = true;
  3234. }
  3235. }
  3236. catch (ex) { }
  3237. generateBlobUrl();
  3238. };
  3239. transaction.oncomplete = function (event) {
  3240. generateBlobUrl();
  3241. };
  3242. var newTexture = { textureUrl: url, data: blob };
  3243. try {
  3244. // Put the blob into the dabase
  3245. var addRequest = transaction.objectStore("textures").put(newTexture);
  3246. addRequest.onsuccess = function (event) {
  3247. };
  3248. addRequest.onerror = function (event) {
  3249. generateBlobUrl();
  3250. };
  3251. }
  3252. catch (ex) {
  3253. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3254. if (ex.code === 25) {
  3255. Database.IsUASupportingBlobStorage = false;
  3256. }
  3257. image.src = url;
  3258. }
  3259. }
  3260. else {
  3261. image.src = url;
  3262. }
  3263. }, false);
  3264. xhr.addEventListener("error", function (event) {
  3265. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3266. image.src = url;
  3267. }, false);
  3268. xhr.send();
  3269. }
  3270. else {
  3271. image.src = url;
  3272. }
  3273. }
  3274. else {
  3275. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3276. image.src = url;
  3277. }
  3278. };
  3279. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3280. var _this = this;
  3281. var updateVersion = function (event) {
  3282. // the version is not yet in the DB or we need to update it
  3283. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3284. };
  3285. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3286. };
  3287. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3288. var _this = this;
  3289. if (this.isSupported) {
  3290. var version;
  3291. try {
  3292. var transaction = this.db.transaction(["versions"]);
  3293. transaction.oncomplete = function (event) {
  3294. if (version) {
  3295. // If the version in the JSON file is > than the version in DB
  3296. if (_this.manifestVersionFound > version.data) {
  3297. _this.mustUpdateRessources = true;
  3298. updateInDBCallback();
  3299. }
  3300. else {
  3301. callback(version.data);
  3302. }
  3303. }
  3304. else {
  3305. _this.mustUpdateRessources = true;
  3306. updateInDBCallback();
  3307. }
  3308. };
  3309. transaction.onabort = function (event) {
  3310. callback(-1);
  3311. };
  3312. var getRequest = transaction.objectStore("versions").get(url);
  3313. getRequest.onsuccess = function (event) {
  3314. version = (event.target).result;
  3315. };
  3316. getRequest.onerror = function (event) {
  3317. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3318. callback(-1);
  3319. };
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3323. callback(-1);
  3324. }
  3325. }
  3326. else {
  3327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3328. callback(-1);
  3329. }
  3330. };
  3331. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3332. var _this = this;
  3333. if (this.isSupported && !this.hasReachedQuota) {
  3334. try {
  3335. // Open a transaction to the database
  3336. var transaction = this.db.transaction(["versions"], "readwrite");
  3337. // the transaction could abort because of a QuotaExceededError error
  3338. transaction.onabort = function (event) {
  3339. try {
  3340. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3341. _this.hasReachedQuota = true;
  3342. }
  3343. }
  3344. catch (ex) { }
  3345. callback(-1);
  3346. };
  3347. transaction.oncomplete = function (event) {
  3348. callback(_this.manifestVersionFound);
  3349. };
  3350. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3351. // Put the scene into the database
  3352. var addRequest = transaction.objectStore("versions").put(newVersion);
  3353. addRequest.onsuccess = function (event) {
  3354. };
  3355. addRequest.onerror = function (event) {
  3356. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3357. };
  3358. }
  3359. catch (ex) {
  3360. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3361. callback(-1);
  3362. }
  3363. }
  3364. else {
  3365. callback(-1);
  3366. }
  3367. };
  3368. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3369. var _this = this;
  3370. var completeUrl = Database.ReturnFullUrlLocation(url);
  3371. var saveAndLoadFile = function (event) {
  3372. // the scene is not yet in the DB, let's try to save it
  3373. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3374. };
  3375. this._checkVersionFromDB(completeUrl, function (version) {
  3376. if (version !== -1) {
  3377. if (!_this.mustUpdateRessources) {
  3378. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3379. }
  3380. else {
  3381. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3382. }
  3383. }
  3384. else {
  3385. errorCallback();
  3386. }
  3387. });
  3388. };
  3389. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3390. if (this.isSupported) {
  3391. var targetStore;
  3392. if (url.indexOf(".babylon") !== -1) {
  3393. targetStore = "scenes";
  3394. }
  3395. else {
  3396. targetStore = "textures";
  3397. }
  3398. var file;
  3399. var transaction = this.db.transaction([targetStore]);
  3400. transaction.oncomplete = function (event) {
  3401. if (file) {
  3402. callback(file.data);
  3403. }
  3404. else {
  3405. notInDBCallback();
  3406. }
  3407. };
  3408. transaction.onabort = function (event) {
  3409. notInDBCallback();
  3410. };
  3411. var getRequest = transaction.objectStore(targetStore).get(url);
  3412. getRequest.onsuccess = function (event) {
  3413. file = (event.target).result;
  3414. };
  3415. getRequest.onerror = function (event) {
  3416. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3417. notInDBCallback();
  3418. };
  3419. }
  3420. else {
  3421. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3422. callback();
  3423. }
  3424. };
  3425. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3426. var _this = this;
  3427. if (this.isSupported) {
  3428. var targetStore;
  3429. if (url.indexOf(".babylon") !== -1) {
  3430. targetStore = "scenes";
  3431. }
  3432. else {
  3433. targetStore = "textures";
  3434. }
  3435. // Create XHR
  3436. var xhr = new XMLHttpRequest(), fileData;
  3437. xhr.open("GET", url, true);
  3438. if (useArrayBuffer) {
  3439. xhr.responseType = "arraybuffer";
  3440. }
  3441. xhr.onprogress = progressCallback;
  3442. xhr.addEventListener("load", function () {
  3443. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3444. // Blob as response (XHR2)
  3445. //fileData = xhr.responseText;
  3446. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3447. if (!_this.hasReachedQuota) {
  3448. // Open a transaction to the database
  3449. var transaction = _this.db.transaction([targetStore], "readwrite");
  3450. // the transaction could abort because of a QuotaExceededError error
  3451. transaction.onabort = function (event) {
  3452. try {
  3453. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3454. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3455. this.hasReachedQuota = true;
  3456. }
  3457. }
  3458. catch (ex) { }
  3459. callback(fileData);
  3460. };
  3461. transaction.oncomplete = function (event) {
  3462. callback(fileData);
  3463. };
  3464. var newFile;
  3465. if (targetStore === "scenes") {
  3466. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3467. }
  3468. else {
  3469. newFile = { textureUrl: url, data: fileData };
  3470. }
  3471. try {
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. callback(fileData);
  3482. }
  3483. }
  3484. else {
  3485. callback(fileData);
  3486. }
  3487. }
  3488. else {
  3489. callback();
  3490. }
  3491. }, false);
  3492. xhr.addEventListener("error", function (event) {
  3493. BABYLON.Tools.Error("error on XHR request.");
  3494. callback();
  3495. }, false);
  3496. xhr.send();
  3497. }
  3498. else {
  3499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3500. callback();
  3501. }
  3502. };
  3503. Database.IsUASupportingBlobStorage = true;
  3504. Database.IDBStorageEnabled = true;
  3505. Database.parseURL = function (url) {
  3506. var a = document.createElement('a');
  3507. a.href = url;
  3508. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3509. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3510. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3511. return absLocation;
  3512. };
  3513. Database.ReturnFullUrlLocation = function (url) {
  3514. if (url.indexOf("http:/") === -1) {
  3515. return (Database.parseURL(window.location.href) + url);
  3516. }
  3517. else {
  3518. return url;
  3519. }
  3520. };
  3521. return Database;
  3522. })();
  3523. BABYLON.Database = Database;
  3524. })(BABYLON || (BABYLON = {}));
  3525. var BABYLON;
  3526. (function (BABYLON) {
  3527. var Internals;
  3528. (function (Internals) {
  3529. /*
  3530. * Based on jsTGALoader - Javascript loader for TGA file
  3531. * By Vincent Thibault
  3532. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3533. */
  3534. var TGATools = (function () {
  3535. function TGATools() {
  3536. }
  3537. TGATools.GetTGAHeader = function (data) {
  3538. var offset = 0;
  3539. var header = {
  3540. id_length: data[offset++],
  3541. colormap_type: data[offset++],
  3542. image_type: data[offset++],
  3543. colormap_index: data[offset++] | data[offset++] << 8,
  3544. colormap_length: data[offset++] | data[offset++] << 8,
  3545. colormap_size: data[offset++],
  3546. origin: [
  3547. data[offset++] | data[offset++] << 8,
  3548. data[offset++] | data[offset++] << 8
  3549. ],
  3550. width: data[offset++] | data[offset++] << 8,
  3551. height: data[offset++] | data[offset++] << 8,
  3552. pixel_size: data[offset++],
  3553. flags: data[offset++]
  3554. };
  3555. return header;
  3556. };
  3557. TGATools.UploadContent = function (gl, data) {
  3558. // Not enough data to contain header ?
  3559. if (data.length < 19) {
  3560. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3561. return;
  3562. }
  3563. // Read Header
  3564. var offset = 18;
  3565. var header = TGATools.GetTGAHeader(data);
  3566. // Assume it's a valid Targa file.
  3567. if (header.id_length + offset > data.length) {
  3568. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3569. return;
  3570. }
  3571. // Skip not needed data
  3572. offset += header.id_length;
  3573. var use_rle = false;
  3574. var use_pal = false;
  3575. var use_rgb = false;
  3576. var use_grey = false;
  3577. // Get some informations.
  3578. switch (header.image_type) {
  3579. case TGATools._TYPE_RLE_INDEXED:
  3580. use_rle = true;
  3581. case TGATools._TYPE_INDEXED:
  3582. use_pal = true;
  3583. break;
  3584. case TGATools._TYPE_RLE_RGB:
  3585. use_rle = true;
  3586. case TGATools._TYPE_RGB:
  3587. use_rgb = true;
  3588. break;
  3589. case TGATools._TYPE_RLE_GREY:
  3590. use_rle = true;
  3591. case TGATools._TYPE_GREY:
  3592. use_grey = true;
  3593. break;
  3594. }
  3595. var pixel_data;
  3596. var numAlphaBits = header.flags & 0xf;
  3597. var pixel_size = header.pixel_size >> 3;
  3598. var pixel_total = header.width * header.height * pixel_size;
  3599. // Read palettes
  3600. var palettes;
  3601. if (use_pal) {
  3602. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3603. }
  3604. // Read LRE
  3605. if (use_rle) {
  3606. pixel_data = new Uint8Array(pixel_total);
  3607. var c, count, i;
  3608. var localOffset = 0;
  3609. var pixels = new Uint8Array(pixel_size);
  3610. while (offset < pixel_total && localOffset < pixel_total) {
  3611. c = data[offset++];
  3612. count = (c & 0x7f) + 1;
  3613. // RLE pixels
  3614. if (c & 0x80) {
  3615. // Bind pixel tmp array
  3616. for (i = 0; i < pixel_size; ++i) {
  3617. pixels[i] = data[offset++];
  3618. }
  3619. // Copy pixel array
  3620. for (i = 0; i < count; ++i) {
  3621. pixel_data.set(pixels, localOffset + i * pixel_size);
  3622. }
  3623. localOffset += pixel_size * count;
  3624. }
  3625. else {
  3626. count *= pixel_size;
  3627. for (i = 0; i < count; ++i) {
  3628. pixel_data[localOffset + i] = data[offset++];
  3629. }
  3630. localOffset += count;
  3631. }
  3632. }
  3633. }
  3634. else {
  3635. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3636. }
  3637. // Load to texture
  3638. var x_start, y_start, x_step, y_step, y_end, x_end;
  3639. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3640. default:
  3641. case TGATools._ORIGIN_UL:
  3642. x_start = 0;
  3643. x_step = 1;
  3644. x_end = header.width;
  3645. y_start = 0;
  3646. y_step = 1;
  3647. y_end = header.height;
  3648. break;
  3649. case TGATools._ORIGIN_BL:
  3650. x_start = 0;
  3651. x_step = 1;
  3652. x_end = header.width;
  3653. y_start = header.height - 1;
  3654. y_step = -1;
  3655. y_end = -1;
  3656. break;
  3657. case TGATools._ORIGIN_UR:
  3658. x_start = header.width - 1;
  3659. x_step = -1;
  3660. x_end = -1;
  3661. y_start = 0;
  3662. y_step = 1;
  3663. y_end = header.height;
  3664. break;
  3665. case TGATools._ORIGIN_BR:
  3666. x_start = header.width - 1;
  3667. x_step = -1;
  3668. x_end = -1;
  3669. y_start = header.height - 1;
  3670. y_step = -1;
  3671. y_end = -1;
  3672. break;
  3673. }
  3674. // Load the specify method
  3675. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3676. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3677. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3678. };
  3679. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3680. var image = pixel_data, colormap = palettes;
  3681. var width = header.width, height = header.height;
  3682. var color, i = 0, x, y;
  3683. var imageData = new Uint8Array(width * height * 4);
  3684. for (y = y_start; y !== y_end; y += y_step) {
  3685. for (x = x_start; x !== x_end; x += x_step, i++) {
  3686. color = image[i];
  3687. imageData[(x + width * y) * 4 + 3] = 255;
  3688. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3689. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3690. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3696. var image = pixel_data;
  3697. var width = header.width, height = header.height;
  3698. var color, i = 0, x, y;
  3699. var imageData = new Uint8Array(width * height * 4);
  3700. for (y = y_start; y !== y_end; y += y_step) {
  3701. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3702. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3703. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3704. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3705. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3706. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3707. }
  3708. }
  3709. return imageData;
  3710. };
  3711. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3712. var image = pixel_data;
  3713. var width = header.width, height = header.height;
  3714. var i = 0, x, y;
  3715. var imageData = new Uint8Array(width * height * 4);
  3716. for (y = y_start; y !== y_end; y += y_step) {
  3717. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3718. imageData[(x + width * y) * 4 + 3] = 255;
  3719. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3720. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3721. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3722. }
  3723. }
  3724. return imageData;
  3725. };
  3726. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3727. var image = pixel_data;
  3728. var width = header.width, height = header.height;
  3729. var i = 0, x, y;
  3730. var imageData = new Uint8Array(width * height * 4);
  3731. for (y = y_start; y !== y_end; y += y_step) {
  3732. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3733. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3734. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3735. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3736. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3737. }
  3738. }
  3739. return imageData;
  3740. };
  3741. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3742. var image = pixel_data;
  3743. var width = header.width, height = header.height;
  3744. var color, i = 0, x, y;
  3745. var imageData = new Uint8Array(width * height * 4);
  3746. for (y = y_start; y !== y_end; y += y_step) {
  3747. for (x = x_start; x !== x_end; x += x_step, i++) {
  3748. color = image[i];
  3749. imageData[(x + width * y) * 4 + 0] = color;
  3750. imageData[(x + width * y) * 4 + 1] = color;
  3751. imageData[(x + width * y) * 4 + 2] = color;
  3752. imageData[(x + width * y) * 4 + 3] = 255;
  3753. }
  3754. }
  3755. return imageData;
  3756. };
  3757. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3758. var image = pixel_data;
  3759. var width = header.width, height = header.height;
  3760. var i = 0, x, y;
  3761. var imageData = new Uint8Array(width * height * 4);
  3762. for (y = y_start; y !== y_end; y += y_step) {
  3763. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3764. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3765. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3766. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3767. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3768. }
  3769. }
  3770. return imageData;
  3771. };
  3772. TGATools._TYPE_NO_DATA = 0;
  3773. TGATools._TYPE_INDEXED = 1;
  3774. TGATools._TYPE_RGB = 2;
  3775. TGATools._TYPE_GREY = 3;
  3776. TGATools._TYPE_RLE_INDEXED = 9;
  3777. TGATools._TYPE_RLE_RGB = 10;
  3778. TGATools._TYPE_RLE_GREY = 11;
  3779. TGATools._ORIGIN_MASK = 0x30;
  3780. TGATools._ORIGIN_SHIFT = 0x04;
  3781. TGATools._ORIGIN_BL = 0x00;
  3782. TGATools._ORIGIN_BR = 0x01;
  3783. TGATools._ORIGIN_UL = 0x02;
  3784. TGATools._ORIGIN_UR = 0x03;
  3785. return TGATools;
  3786. })();
  3787. Internals.TGATools = TGATools;
  3788. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3789. })(BABYLON || (BABYLON = {}));
  3790. var BABYLON;
  3791. (function (BABYLON) {
  3792. var SmartArray = (function () {
  3793. function SmartArray(capacity) {
  3794. this.length = 0;
  3795. this._duplicateId = 0;
  3796. this.data = new Array(capacity);
  3797. this._id = SmartArray._GlobalId++;
  3798. }
  3799. SmartArray.prototype.push = function (value) {
  3800. this.data[this.length++] = value;
  3801. if (this.length > this.data.length) {
  3802. this.data.length *= 2;
  3803. }
  3804. if (!value.__smartArrayFlags) {
  3805. value.__smartArrayFlags = {};
  3806. }
  3807. value.__smartArrayFlags[this._id] = this._duplicateId;
  3808. };
  3809. SmartArray.prototype.pushNoDuplicate = function (value) {
  3810. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3811. return;
  3812. }
  3813. this.push(value);
  3814. };
  3815. SmartArray.prototype.sort = function (compareFn) {
  3816. this.data.sort(compareFn);
  3817. };
  3818. SmartArray.prototype.reset = function () {
  3819. this.length = 0;
  3820. this._duplicateId++;
  3821. };
  3822. SmartArray.prototype.concat = function (array) {
  3823. if (array.length === 0) {
  3824. return;
  3825. }
  3826. if (this.length + array.length > this.data.length) {
  3827. this.data.length = (this.length + array.length) * 2;
  3828. }
  3829. for (var index = 0; index < array.length; index++) {
  3830. this.data[this.length++] = (array.data || array)[index];
  3831. }
  3832. };
  3833. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3834. if (array.length === 0) {
  3835. return;
  3836. }
  3837. if (this.length + array.length > this.data.length) {
  3838. this.data.length = (this.length + array.length) * 2;
  3839. }
  3840. for (var index = 0; index < array.length; index++) {
  3841. var item = (array.data || array)[index];
  3842. this.pushNoDuplicate(item);
  3843. }
  3844. };
  3845. SmartArray.prototype.indexOf = function (value) {
  3846. var position = this.data.indexOf(value);
  3847. if (position >= this.length) {
  3848. return -1;
  3849. }
  3850. return position;
  3851. };
  3852. // Statics
  3853. SmartArray._GlobalId = 0;
  3854. return SmartArray;
  3855. })();
  3856. BABYLON.SmartArray = SmartArray;
  3857. })(BABYLON || (BABYLON = {}));
  3858. var BABYLON;
  3859. (function (BABYLON) {
  3860. var SmartCollection = (function () {
  3861. function SmartCollection(capacity) {
  3862. if (capacity === void 0) { capacity = 10; }
  3863. this.count = 0;
  3864. this._initialCapacity = capacity;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. SmartCollection.prototype.add = function (key, item) {
  3869. if (this.items[key] != undefined) {
  3870. return -1;
  3871. }
  3872. this.items[key] = item;
  3873. //literal keys are always strings, but we keep source type of key in _keys array
  3874. this._keys[this.count++] = key;
  3875. if (this.count > this._keys.length) {
  3876. this._keys.length *= 2;
  3877. }
  3878. return this.count;
  3879. };
  3880. SmartCollection.prototype.remove = function (key) {
  3881. if (this.items[key] == undefined) {
  3882. return -1;
  3883. }
  3884. return this.removeItemOfIndex(this.indexOf(key));
  3885. };
  3886. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3887. if (index < this.count && index > -1) {
  3888. delete this.items[this._keys[index]];
  3889. //here, shifting by hand is better optimised than .splice
  3890. while (index < this.count) {
  3891. this._keys[index] = this._keys[index + 1];
  3892. index++;
  3893. }
  3894. }
  3895. else {
  3896. return -1;
  3897. }
  3898. return --this.count;
  3899. };
  3900. SmartCollection.prototype.indexOf = function (key) {
  3901. for (var i = 0; i !== this.count; i++) {
  3902. if (this._keys[i] === key) {
  3903. return i;
  3904. }
  3905. }
  3906. return -1;
  3907. };
  3908. SmartCollection.prototype.item = function (key) {
  3909. return this.items[key];
  3910. };
  3911. SmartCollection.prototype.getAllKeys = function () {
  3912. if (this.count > 0) {
  3913. var keys = new Array(this.count);
  3914. for (var i = 0; i < this.count; i++) {
  3915. keys[i] = this._keys[i];
  3916. }
  3917. return keys;
  3918. }
  3919. else {
  3920. return undefined;
  3921. }
  3922. };
  3923. SmartCollection.prototype.getKeyByIndex = function (index) {
  3924. if (index < this.count && index > -1) {
  3925. return this._keys[index];
  3926. }
  3927. else {
  3928. return undefined;
  3929. }
  3930. };
  3931. SmartCollection.prototype.getItemByIndex = function (index) {
  3932. if (index < this.count && index > -1) {
  3933. return this.items[this._keys[index]];
  3934. }
  3935. else {
  3936. return undefined;
  3937. }
  3938. };
  3939. SmartCollection.prototype.empty = function () {
  3940. if (this.count > 0) {
  3941. this.count = 0;
  3942. this.items = {};
  3943. this._keys = new Array(this._initialCapacity);
  3944. }
  3945. };
  3946. SmartCollection.prototype.forEach = function (block) {
  3947. var key;
  3948. for (key in this.items) {
  3949. if (this.items.hasOwnProperty(key)) {
  3950. block(this.items[key]);
  3951. }
  3952. }
  3953. };
  3954. return SmartCollection;
  3955. })();
  3956. BABYLON.SmartCollection = SmartCollection;
  3957. })(BABYLON || (BABYLON = {}));
  3958. var BABYLON;
  3959. (function (BABYLON) {
  3960. // Screenshots
  3961. var screenshotCanvas;
  3962. var cloneValue = function (source, destinationObject) {
  3963. if (!source)
  3964. return null;
  3965. if (source instanceof BABYLON.Mesh) {
  3966. return null;
  3967. }
  3968. if (source instanceof BABYLON.SubMesh) {
  3969. return source.clone(destinationObject);
  3970. }
  3971. else if (source.clone) {
  3972. return source.clone();
  3973. }
  3974. return null;
  3975. };
  3976. var Tools = (function () {
  3977. function Tools() {
  3978. }
  3979. Tools.Instantiate = function (className) {
  3980. var arr = className.split(".");
  3981. var fn = (window || this);
  3982. for (var i = 0, len = arr.length; i < len; i++) {
  3983. fn = fn[arr[i]];
  3984. }
  3985. if (typeof fn !== "function") {
  3986. return null;
  3987. }
  3988. return fn;
  3989. };
  3990. Tools.SetImmediate = function (action) {
  3991. if (window.setImmediate) {
  3992. window.setImmediate(action);
  3993. }
  3994. else {
  3995. setTimeout(action, 1);
  3996. }
  3997. };
  3998. Tools.IsExponentOfTwo = function (value) {
  3999. var count = 1;
  4000. do {
  4001. count *= 2;
  4002. } while (count < value);
  4003. return count === value;
  4004. };
  4005. Tools.GetExponentOfTwo = function (value, max) {
  4006. var count = 1;
  4007. do {
  4008. count *= 2;
  4009. } while (count < value);
  4010. if (count > max)
  4011. count = max;
  4012. return count;
  4013. };
  4014. Tools.GetFilename = function (path) {
  4015. var index = path.lastIndexOf("/");
  4016. if (index < 0)
  4017. return path;
  4018. return path.substring(index + 1);
  4019. };
  4020. Tools.GetDOMTextContent = function (element) {
  4021. var result = "";
  4022. var child = element.firstChild;
  4023. while (child) {
  4024. if (child.nodeType === 3) {
  4025. result += child.textContent;
  4026. }
  4027. child = child.nextSibling;
  4028. }
  4029. return result;
  4030. };
  4031. Tools.ToDegrees = function (angle) {
  4032. return angle * 180 / Math.PI;
  4033. };
  4034. Tools.ToRadians = function (angle) {
  4035. return angle * Math.PI / 180;
  4036. };
  4037. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4038. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4039. var output = "";
  4040. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4041. var i = 0;
  4042. var bytes = new Uint8Array(buffer);
  4043. while (i < bytes.length) {
  4044. chr1 = bytes[i++];
  4045. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4046. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4047. enc1 = chr1 >> 2;
  4048. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4049. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4050. enc4 = chr3 & 63;
  4051. if (isNaN(chr2)) {
  4052. enc3 = enc4 = 64;
  4053. }
  4054. else if (isNaN(chr3)) {
  4055. enc4 = 64;
  4056. }
  4057. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4058. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4059. }
  4060. return "data:image/png;base64," + output;
  4061. };
  4062. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4063. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4064. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4065. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4066. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4067. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4068. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4069. }
  4070. return {
  4071. minimum: minimum,
  4072. maximum: maximum
  4073. };
  4074. };
  4075. Tools.ExtractMinAndMax = function (positions, start, count) {
  4076. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4077. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4078. for (var index = start; index < start + count; index++) {
  4079. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4080. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4081. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4082. }
  4083. return {
  4084. minimum: minimum,
  4085. maximum: maximum
  4086. };
  4087. };
  4088. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4089. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4090. return undefined;
  4091. return Array.isArray(obj) ? obj : [obj];
  4092. };
  4093. // Misc.
  4094. Tools.GetPointerPrefix = function () {
  4095. var eventPrefix = "pointer";
  4096. // Check if pointer events are supported
  4097. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4098. eventPrefix = "mouse";
  4099. }
  4100. return eventPrefix;
  4101. };
  4102. Tools.QueueNewFrame = function (func) {
  4103. if (window.requestAnimationFrame)
  4104. window.requestAnimationFrame(func);
  4105. else if (window.msRequestAnimationFrame)
  4106. window.msRequestAnimationFrame(func);
  4107. else if (window.webkitRequestAnimationFrame)
  4108. window.webkitRequestAnimationFrame(func);
  4109. else if (window.mozRequestAnimationFrame)
  4110. window.mozRequestAnimationFrame(func);
  4111. else if (window.oRequestAnimationFrame)
  4112. window.oRequestAnimationFrame(func);
  4113. else {
  4114. window.setTimeout(func, 16);
  4115. }
  4116. };
  4117. Tools.RequestFullscreen = function (element) {
  4118. if (element.requestFullscreen)
  4119. element.requestFullscreen();
  4120. else if (element.msRequestFullscreen)
  4121. element.msRequestFullscreen();
  4122. else if (element.webkitRequestFullscreen)
  4123. element.webkitRequestFullscreen();
  4124. else if (element.mozRequestFullScreen)
  4125. element.mozRequestFullScreen();
  4126. };
  4127. Tools.ExitFullscreen = function () {
  4128. if (document.exitFullscreen) {
  4129. document.exitFullscreen();
  4130. }
  4131. else if (document.mozCancelFullScreen) {
  4132. document.mozCancelFullScreen();
  4133. }
  4134. else if (document.webkitCancelFullScreen) {
  4135. document.webkitCancelFullScreen();
  4136. }
  4137. else if (document.msCancelFullScreen) {
  4138. document.msCancelFullScreen();
  4139. }
  4140. };
  4141. // External files
  4142. Tools.CleanUrl = function (url) {
  4143. url = url.replace(/#/mg, "%23");
  4144. return url;
  4145. };
  4146. Tools.LoadImage = function (url, onload, onerror, database) {
  4147. if (url instanceof ArrayBuffer) {
  4148. url = Tools.EncodeArrayBufferTobase64(url);
  4149. }
  4150. url = Tools.CleanUrl(url);
  4151. var img = new Image();
  4152. if (url.substr(0, 5) !== "data:") {
  4153. if (Tools.CorsBehavior) {
  4154. switch (typeof (Tools.CorsBehavior)) {
  4155. case "function":
  4156. var result = Tools.CorsBehavior(url);
  4157. if (result) {
  4158. img.crossOrigin = result;
  4159. }
  4160. break;
  4161. case "string":
  4162. default:
  4163. img.crossOrigin = Tools.CorsBehavior;
  4164. break;
  4165. }
  4166. }
  4167. }
  4168. img.onload = function () {
  4169. onload(img);
  4170. };
  4171. img.onerror = function (err) {
  4172. Tools.Error("Error while trying to load texture: " + url);
  4173. if (Tools.UseFallbackTexture) {
  4174. 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";
  4175. onload(img);
  4176. }
  4177. else {
  4178. onerror();
  4179. }
  4180. };
  4181. var noIndexedDB = function () {
  4182. img.src = url;
  4183. };
  4184. var loadFromIndexedDB = function () {
  4185. database.loadImageFromDB(url, img);
  4186. };
  4187. //ANY database to do!
  4188. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. if (url.indexOf("file:") === -1) {
  4193. noIndexedDB();
  4194. }
  4195. else {
  4196. try {
  4197. var textureName = url.substring(5);
  4198. var blobURL;
  4199. try {
  4200. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4201. }
  4202. catch (ex) {
  4203. // Chrome doesn't support oneTimeOnly parameter
  4204. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4205. }
  4206. img.src = blobURL;
  4207. }
  4208. catch (e) {
  4209. img.src = null;
  4210. }
  4211. }
  4212. }
  4213. return img;
  4214. };
  4215. //ANY
  4216. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4217. url = Tools.CleanUrl(url);
  4218. var noIndexedDB = function () {
  4219. var request = new XMLHttpRequest();
  4220. var loadUrl = Tools.BaseUrl + url;
  4221. request.open('GET', loadUrl, true);
  4222. if (useArrayBuffer) {
  4223. request.responseType = "arraybuffer";
  4224. }
  4225. request.onprogress = progressCallBack;
  4226. request.onreadystatechange = function () {
  4227. if (request.readyState === 4) {
  4228. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4229. callback(!useArrayBuffer ? request.responseText : request.response);
  4230. }
  4231. else {
  4232. if (onError) {
  4233. onError();
  4234. }
  4235. else {
  4236. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4237. }
  4238. }
  4239. }
  4240. };
  4241. request.send(null);
  4242. };
  4243. var loadFromIndexedDB = function () {
  4244. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4245. };
  4246. if (url.indexOf("file:") !== -1) {
  4247. var fileName = url.substring(5);
  4248. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4249. }
  4250. else {
  4251. // Caching all files
  4252. if (database && database.enableSceneOffline) {
  4253. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4254. }
  4255. else {
  4256. noIndexedDB();
  4257. }
  4258. }
  4259. };
  4260. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4261. var reader = new FileReader();
  4262. reader.onload = function (e) {
  4263. //target doesn't have result from ts 1.3
  4264. callback(e.target['result']);
  4265. };
  4266. reader.onprogress = progressCallback;
  4267. reader.readAsDataURL(fileToLoad);
  4268. };
  4269. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4270. var reader = new FileReader();
  4271. reader.onerror = function (e) {
  4272. Tools.Log("Error while reading file: " + fileToLoad.name);
  4273. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4274. };
  4275. reader.onload = function (e) {
  4276. //target doesn't have result from ts 1.3
  4277. callback(e.target['result']);
  4278. };
  4279. reader.onprogress = progressCallBack;
  4280. if (!useArrayBuffer) {
  4281. // Asynchronous read
  4282. reader.readAsText(fileToLoad);
  4283. }
  4284. else {
  4285. reader.readAsArrayBuffer(fileToLoad);
  4286. }
  4287. };
  4288. //returns a downloadable url to a file content.
  4289. Tools.FileAsURL = function (content) {
  4290. var fileBlob = new Blob([content]);
  4291. var url = window.URL || window.webkitURL;
  4292. var link = url.createObjectURL(fileBlob);
  4293. return link;
  4294. };
  4295. // Misc.
  4296. Tools.Format = function (value, decimals) {
  4297. if (decimals === void 0) { decimals = 2; }
  4298. return value.toFixed(decimals);
  4299. };
  4300. Tools.CheckExtends = function (v, min, max) {
  4301. if (v.x < min.x)
  4302. min.x = v.x;
  4303. if (v.y < min.y)
  4304. min.y = v.y;
  4305. if (v.z < min.z)
  4306. min.z = v.z;
  4307. if (v.x > max.x)
  4308. max.x = v.x;
  4309. if (v.y > max.y)
  4310. max.y = v.y;
  4311. if (v.z > max.z)
  4312. max.z = v.z;
  4313. };
  4314. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4315. for (var prop in source) {
  4316. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4317. continue;
  4318. }
  4319. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4320. continue;
  4321. }
  4322. var sourceValue = source[prop];
  4323. var typeOfSourceValue = typeof sourceValue;
  4324. if (typeOfSourceValue === "function") {
  4325. continue;
  4326. }
  4327. if (typeOfSourceValue === "object") {
  4328. if (sourceValue instanceof Array) {
  4329. destination[prop] = [];
  4330. if (sourceValue.length > 0) {
  4331. if (typeof sourceValue[0] == "object") {
  4332. for (var index = 0; index < sourceValue.length; index++) {
  4333. var clonedValue = cloneValue(sourceValue[index], destination);
  4334. if (destination[prop].indexOf(clonedValue) === -1) {
  4335. destination[prop].push(clonedValue);
  4336. }
  4337. }
  4338. }
  4339. else {
  4340. destination[prop] = sourceValue.slice(0);
  4341. }
  4342. }
  4343. }
  4344. else {
  4345. destination[prop] = cloneValue(sourceValue, destination);
  4346. }
  4347. }
  4348. else {
  4349. destination[prop] = sourceValue;
  4350. }
  4351. }
  4352. };
  4353. Tools.IsEmpty = function (obj) {
  4354. for (var i in obj) {
  4355. return false;
  4356. }
  4357. return true;
  4358. };
  4359. Tools.RegisterTopRootEvents = function (events) {
  4360. for (var index = 0; index < events.length; index++) {
  4361. var event = events[index];
  4362. window.addEventListener(event.name, event.handler, false);
  4363. try {
  4364. if (window.parent) {
  4365. window.parent.addEventListener(event.name, event.handler, false);
  4366. }
  4367. }
  4368. catch (e) {
  4369. }
  4370. }
  4371. };
  4372. Tools.UnregisterTopRootEvents = function (events) {
  4373. for (var index = 0; index < events.length; index++) {
  4374. var event = events[index];
  4375. window.removeEventListener(event.name, event.handler);
  4376. try {
  4377. if (window.parent) {
  4378. window.parent.removeEventListener(event.name, event.handler);
  4379. }
  4380. }
  4381. catch (e) {
  4382. }
  4383. }
  4384. };
  4385. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4386. // Read the contents of the framebuffer
  4387. var numberOfChannelsByLine = width * 4;
  4388. var halfHeight = height / 2;
  4389. //Reading datas from WebGL
  4390. var data = engine.readPixels(0, 0, width, height);
  4391. //To flip image on Y axis.
  4392. for (var i = 0; i < halfHeight; i++) {
  4393. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4394. var currentCell = j + i * numberOfChannelsByLine;
  4395. var targetLine = height - i - 1;
  4396. var targetCell = j + targetLine * numberOfChannelsByLine;
  4397. var temp = data[currentCell];
  4398. data[currentCell] = data[targetCell];
  4399. data[targetCell] = temp;
  4400. }
  4401. }
  4402. // Create a 2D canvas to store the result
  4403. if (!screenshotCanvas) {
  4404. screenshotCanvas = document.createElement('canvas');
  4405. }
  4406. screenshotCanvas.width = width;
  4407. screenshotCanvas.height = height;
  4408. var context = screenshotCanvas.getContext('2d');
  4409. // Copy the pixels to a 2D canvas
  4410. var imageData = context.createImageData(width, height);
  4411. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4412. var castData = imageData.data;
  4413. castData.set(data);
  4414. context.putImageData(imageData, 0, 0);
  4415. var base64Image = screenshotCanvas.toDataURL();
  4416. if (successCallback) {
  4417. successCallback(base64Image);
  4418. }
  4419. else {
  4420. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4421. if (("download" in document.createElement("a"))) {
  4422. var a = window.document.createElement("a");
  4423. a.href = base64Image;
  4424. var date = new Date();
  4425. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4426. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4427. window.document.body.appendChild(a);
  4428. a.addEventListener("click", function () {
  4429. a.parentElement.removeChild(a);
  4430. });
  4431. a.click();
  4432. }
  4433. else {
  4434. var newWindow = window.open("");
  4435. var img = newWindow.document.createElement("img");
  4436. img.src = base64Image;
  4437. newWindow.document.body.appendChild(img);
  4438. }
  4439. }
  4440. };
  4441. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4442. var width;
  4443. var height;
  4444. //If a precision value is specified
  4445. if (size.precision) {
  4446. width = Math.round(engine.getRenderWidth() * size.precision);
  4447. height = Math.round(width / engine.getAspectRatio(camera));
  4448. size = { width: width, height: height };
  4449. }
  4450. else if (size.width && size.height) {
  4451. width = size.width;
  4452. height = size.height;
  4453. }
  4454. else if (size.width && !size.height) {
  4455. width = size.width;
  4456. height = Math.round(width / engine.getAspectRatio(camera));
  4457. size = { width: width, height: height };
  4458. }
  4459. else if (size.height && !size.width) {
  4460. height = size.height;
  4461. width = Math.round(height * engine.getAspectRatio(camera));
  4462. size = { width: width, height: height };
  4463. }
  4464. else if (!isNaN(size)) {
  4465. height = size;
  4466. width = size;
  4467. }
  4468. else {
  4469. Tools.Error("Invalid 'size' parameter !");
  4470. return;
  4471. }
  4472. var scene = camera.getScene();
  4473. var previousCamera = null;
  4474. if (scene.activeCamera !== camera) {
  4475. previousCamera = scene.activeCamera;
  4476. scene.activeCamera = camera;
  4477. }
  4478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4480. texture.renderList = scene.meshes;
  4481. texture.onAfterRender = function () {
  4482. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4483. };
  4484. scene.incrementRenderId();
  4485. texture.render(true);
  4486. texture.dispose();
  4487. if (previousCamera) {
  4488. scene.activeCamera = previousCamera;
  4489. }
  4490. camera.getProjectionMatrix(true); // Force cache refresh;
  4491. };
  4492. // XHR response validator for local file scenario
  4493. Tools.ValidateXHRData = function (xhr, dataType) {
  4494. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4495. if (dataType === void 0) { dataType = 7; }
  4496. try {
  4497. if (dataType & 1) {
  4498. if (xhr.responseText && xhr.responseText.length > 0) {
  4499. return true;
  4500. }
  4501. else if (dataType === 1) {
  4502. return false;
  4503. }
  4504. }
  4505. if (dataType & 2) {
  4506. // Check header width and height since there is no "TGA" magic number
  4507. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4508. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4509. return true;
  4510. }
  4511. else if (dataType === 2) {
  4512. return false;
  4513. }
  4514. }
  4515. if (dataType & 4) {
  4516. // Check for the "DDS" magic number
  4517. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4518. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4519. return true;
  4520. }
  4521. else {
  4522. return false;
  4523. }
  4524. }
  4525. }
  4526. catch (e) {
  4527. }
  4528. return false;
  4529. };
  4530. Object.defineProperty(Tools, "NoneLogLevel", {
  4531. get: function () {
  4532. return Tools._NoneLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "MessageLogLevel", {
  4538. get: function () {
  4539. return Tools._MessageLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Object.defineProperty(Tools, "WarningLogLevel", {
  4545. get: function () {
  4546. return Tools._WarningLogLevel;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(Tools, "ErrorLogLevel", {
  4552. get: function () {
  4553. return Tools._ErrorLogLevel;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Object.defineProperty(Tools, "AllLogLevel", {
  4559. get: function () {
  4560. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4561. },
  4562. enumerable: true,
  4563. configurable: true
  4564. });
  4565. Tools._AddLogEntry = function (entry) {
  4566. Tools._LogCache = entry + Tools._LogCache;
  4567. if (Tools.OnNewCacheEntry) {
  4568. Tools.OnNewCacheEntry(entry);
  4569. }
  4570. };
  4571. Tools._FormatMessage = function (message) {
  4572. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4573. var date = new Date();
  4574. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4575. };
  4576. Tools._LogDisabled = function (message) {
  4577. // nothing to do
  4578. };
  4579. Tools._LogEnabled = function (message) {
  4580. var formattedMessage = Tools._FormatMessage(message);
  4581. console.log("BJS - " + formattedMessage);
  4582. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4583. Tools._AddLogEntry(entry);
  4584. };
  4585. Tools._WarnDisabled = function (message) {
  4586. // nothing to do
  4587. };
  4588. Tools._WarnEnabled = function (message) {
  4589. var formattedMessage = Tools._FormatMessage(message);
  4590. console.warn("BJS - " + formattedMessage);
  4591. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4592. Tools._AddLogEntry(entry);
  4593. };
  4594. Tools._ErrorDisabled = function (message) {
  4595. // nothing to do
  4596. };
  4597. Tools._ErrorEnabled = function (message) {
  4598. Tools.errorsCount++;
  4599. var formattedMessage = Tools._FormatMessage(message);
  4600. console.error("BJS - " + formattedMessage);
  4601. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4602. Tools._AddLogEntry(entry);
  4603. };
  4604. Object.defineProperty(Tools, "LogCache", {
  4605. get: function () {
  4606. return Tools._LogCache;
  4607. },
  4608. enumerable: true,
  4609. configurable: true
  4610. });
  4611. Tools.ClearLogCache = function () {
  4612. Tools._LogCache = "";
  4613. Tools.errorsCount = 0;
  4614. };
  4615. Object.defineProperty(Tools, "LogLevels", {
  4616. set: function (level) {
  4617. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4618. Tools.Log = Tools._LogEnabled;
  4619. }
  4620. else {
  4621. Tools.Log = Tools._LogDisabled;
  4622. }
  4623. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4624. Tools.Warn = Tools._WarnEnabled;
  4625. }
  4626. else {
  4627. Tools.Warn = Tools._WarnDisabled;
  4628. }
  4629. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4630. Tools.Error = Tools._ErrorEnabled;
  4631. }
  4632. else {
  4633. Tools.Error = Tools._ErrorDisabled;
  4634. }
  4635. },
  4636. enumerable: true,
  4637. configurable: true
  4638. });
  4639. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4640. get: function () {
  4641. return Tools._PerformanceNoneLogLevel;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4647. get: function () {
  4648. return Tools._PerformanceUserMarkLogLevel;
  4649. },
  4650. enumerable: true,
  4651. configurable: true
  4652. });
  4653. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4654. get: function () {
  4655. return Tools._PerformanceConsoleLogLevel;
  4656. },
  4657. enumerable: true,
  4658. configurable: true
  4659. });
  4660. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4661. set: function (level) {
  4662. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4663. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4664. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4665. return;
  4666. }
  4667. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4668. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4669. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4670. return;
  4671. }
  4672. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4673. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4674. },
  4675. enumerable: true,
  4676. configurable: true
  4677. });
  4678. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4679. };
  4680. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4681. };
  4682. Tools._StartUserMark = function (counterName, condition) {
  4683. if (condition === void 0) { condition = true; }
  4684. if (!condition || !Tools._performance.mark) {
  4685. return;
  4686. }
  4687. Tools._performance.mark(counterName + "-Begin");
  4688. };
  4689. Tools._EndUserMark = function (counterName, condition) {
  4690. if (condition === void 0) { condition = true; }
  4691. if (!condition || !Tools._performance.mark) {
  4692. return;
  4693. }
  4694. Tools._performance.mark(counterName + "-End");
  4695. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4696. };
  4697. Tools._StartPerformanceConsole = function (counterName, condition) {
  4698. if (condition === void 0) { condition = true; }
  4699. if (!condition) {
  4700. return;
  4701. }
  4702. Tools._StartUserMark(counterName, condition);
  4703. if (console.time) {
  4704. console.time(counterName);
  4705. }
  4706. };
  4707. Tools._EndPerformanceConsole = function (counterName, condition) {
  4708. if (condition === void 0) { condition = true; }
  4709. if (!condition) {
  4710. return;
  4711. }
  4712. Tools._EndUserMark(counterName, condition);
  4713. if (console.time) {
  4714. console.timeEnd(counterName);
  4715. }
  4716. };
  4717. Object.defineProperty(Tools, "Now", {
  4718. get: function () {
  4719. if (window.performance && window.performance.now) {
  4720. return window.performance.now();
  4721. }
  4722. return new Date().getTime();
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Tools.BaseUrl = "";
  4728. Tools.CorsBehavior = "anonymous";
  4729. Tools.UseFallbackTexture = true;
  4730. // Logs
  4731. Tools._NoneLogLevel = 0;
  4732. Tools._MessageLogLevel = 1;
  4733. Tools._WarningLogLevel = 2;
  4734. Tools._ErrorLogLevel = 4;
  4735. Tools._LogCache = "";
  4736. Tools.errorsCount = 0;
  4737. Tools.Log = Tools._LogEnabled;
  4738. Tools.Warn = Tools._WarnEnabled;
  4739. Tools.Error = Tools._ErrorEnabled;
  4740. // Performances
  4741. Tools._PerformanceNoneLogLevel = 0;
  4742. Tools._PerformanceUserMarkLogLevel = 1;
  4743. Tools._PerformanceConsoleLogLevel = 2;
  4744. Tools._performance = window.performance;
  4745. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4746. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4747. return Tools;
  4748. })();
  4749. BABYLON.Tools = Tools;
  4750. /**
  4751. * An implementation of a loop for asynchronous functions.
  4752. */
  4753. var AsyncLoop = (function () {
  4754. /**
  4755. * Constroctor.
  4756. * @param iterations the number of iterations.
  4757. * @param _fn the function to run each iteration
  4758. * @param _successCallback the callback that will be called upon succesful execution
  4759. * @param offset starting offset.
  4760. */
  4761. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4762. if (offset === void 0) { offset = 0; }
  4763. this.iterations = iterations;
  4764. this._fn = _fn;
  4765. this._successCallback = _successCallback;
  4766. this.index = offset - 1;
  4767. this._done = false;
  4768. }
  4769. /**
  4770. * Execute the next iteration. Must be called after the last iteration was finished.
  4771. */
  4772. AsyncLoop.prototype.executeNext = function () {
  4773. if (!this._done) {
  4774. if (this.index + 1 < this.iterations) {
  4775. ++this.index;
  4776. this._fn(this);
  4777. }
  4778. else {
  4779. this.breakLoop();
  4780. }
  4781. }
  4782. };
  4783. /**
  4784. * Break the loop and run the success callback.
  4785. */
  4786. AsyncLoop.prototype.breakLoop = function () {
  4787. this._done = true;
  4788. this._successCallback();
  4789. };
  4790. /**
  4791. * Helper function
  4792. */
  4793. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4794. if (offset === void 0) { offset = 0; }
  4795. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4796. loop.executeNext();
  4797. return loop;
  4798. };
  4799. /**
  4800. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4801. * @param iterations total number of iterations
  4802. * @param syncedIterations number of synchronous iterations in each async iteration.
  4803. * @param fn the function to call each iteration.
  4804. * @param callback a success call back that will be called when iterating stops.
  4805. * @param breakFunction a break condition (optional)
  4806. * @param timeout timeout settings for the setTimeout function. default - 0.
  4807. * @constructor
  4808. */
  4809. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4810. if (timeout === void 0) { timeout = 0; }
  4811. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4812. if (breakFunction && breakFunction())
  4813. loop.breakLoop();
  4814. else {
  4815. setTimeout(function () {
  4816. for (var i = 0; i < syncedIterations; ++i) {
  4817. var iteration = (loop.index * syncedIterations) + i;
  4818. if (iteration >= iterations)
  4819. break;
  4820. fn(iteration);
  4821. if (breakFunction && breakFunction()) {
  4822. loop.breakLoop();
  4823. break;
  4824. }
  4825. }
  4826. loop.executeNext();
  4827. }, timeout);
  4828. }
  4829. }, callback);
  4830. };
  4831. return AsyncLoop;
  4832. })();
  4833. BABYLON.AsyncLoop = AsyncLoop;
  4834. })(BABYLON || (BABYLON = {}));
  4835. var BABYLON;
  4836. (function (BABYLON) {
  4837. var Internals;
  4838. (function (Internals) {
  4839. var _AlphaState = (function () {
  4840. function _AlphaState() {
  4841. this._isAlphaBlendDirty = false;
  4842. this._isBlendFunctionParametersDirty = false;
  4843. this._alphaBlend = false;
  4844. this._blendFunctionParameters = new Array(4);
  4845. }
  4846. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4847. get: function () {
  4848. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4854. get: function () {
  4855. return this._alphaBlend;
  4856. },
  4857. set: function (value) {
  4858. if (this._alphaBlend === value) {
  4859. return;
  4860. }
  4861. this._alphaBlend = value;
  4862. this._isAlphaBlendDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4868. if (this._blendFunctionParameters[0] === value0 &&
  4869. this._blendFunctionParameters[1] === value1 &&
  4870. this._blendFunctionParameters[2] === value2 &&
  4871. this._blendFunctionParameters[3] === value3) {
  4872. return;
  4873. }
  4874. this._blendFunctionParameters[0] = value0;
  4875. this._blendFunctionParameters[1] = value1;
  4876. this._blendFunctionParameters[2] = value2;
  4877. this._blendFunctionParameters[3] = value3;
  4878. this._isBlendFunctionParametersDirty = true;
  4879. };
  4880. _AlphaState.prototype.reset = function () {
  4881. this._alphaBlend = false;
  4882. this._blendFunctionParameters[0] = null;
  4883. this._blendFunctionParameters[1] = null;
  4884. this._blendFunctionParameters[2] = null;
  4885. this._blendFunctionParameters[3] = null;
  4886. this._isAlphaBlendDirty = true;
  4887. this._isBlendFunctionParametersDirty = false;
  4888. };
  4889. _AlphaState.prototype.apply = function (gl) {
  4890. if (!this.isDirty) {
  4891. return;
  4892. }
  4893. // Alpha blend
  4894. if (this._isAlphaBlendDirty) {
  4895. if (this._alphaBlend) {
  4896. gl.enable(gl.BLEND);
  4897. }
  4898. else {
  4899. gl.disable(gl.BLEND);
  4900. }
  4901. this._isAlphaBlendDirty = false;
  4902. }
  4903. // Alpha function
  4904. if (this._isBlendFunctionParametersDirty) {
  4905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4906. this._isBlendFunctionParametersDirty = false;
  4907. }
  4908. };
  4909. return _AlphaState;
  4910. })();
  4911. Internals._AlphaState = _AlphaState;
  4912. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4913. })(BABYLON || (BABYLON = {}));
  4914. var BABYLON;
  4915. (function (BABYLON) {
  4916. var Internals;
  4917. (function (Internals) {
  4918. var _DepthCullingState = (function () {
  4919. function _DepthCullingState() {
  4920. this._isDepthTestDirty = false;
  4921. this._isDepthMaskDirty = false;
  4922. this._isDepthFuncDirty = false;
  4923. this._isCullFaceDirty = false;
  4924. this._isCullDirty = false;
  4925. this._isZOffsetDirty = false;
  4926. }
  4927. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4928. get: function () {
  4929. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4935. get: function () {
  4936. return this._zOffset;
  4937. },
  4938. set: function (value) {
  4939. if (this._zOffset === value) {
  4940. return;
  4941. }
  4942. this._zOffset = value;
  4943. this._isZOffsetDirty = true;
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4949. get: function () {
  4950. return this._cullFace;
  4951. },
  4952. set: function (value) {
  4953. if (this._cullFace === value) {
  4954. return;
  4955. }
  4956. this._cullFace = value;
  4957. this._isCullFaceDirty = true;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4963. get: function () {
  4964. return this._cull;
  4965. },
  4966. set: function (value) {
  4967. if (this._cull === value) {
  4968. return;
  4969. }
  4970. this._cull = value;
  4971. this._isCullDirty = true;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4977. get: function () {
  4978. return this._depthFunc;
  4979. },
  4980. set: function (value) {
  4981. if (this._depthFunc === value) {
  4982. return;
  4983. }
  4984. this._depthFunc = value;
  4985. this._isDepthFuncDirty = true;
  4986. },
  4987. enumerable: true,
  4988. configurable: true
  4989. });
  4990. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4991. get: function () {
  4992. return this._depthMask;
  4993. },
  4994. set: function (value) {
  4995. if (this._depthMask === value) {
  4996. return;
  4997. }
  4998. this._depthMask = value;
  4999. this._isDepthMaskDirty = true;
  5000. },
  5001. enumerable: true,
  5002. configurable: true
  5003. });
  5004. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5005. get: function () {
  5006. return this._depthTest;
  5007. },
  5008. set: function (value) {
  5009. if (this._depthTest === value) {
  5010. return;
  5011. }
  5012. this._depthTest = value;
  5013. this._isDepthTestDirty = true;
  5014. },
  5015. enumerable: true,
  5016. configurable: true
  5017. });
  5018. _DepthCullingState.prototype.reset = function () {
  5019. this._depthMask = true;
  5020. this._depthTest = true;
  5021. this._depthFunc = null;
  5022. this._cull = null;
  5023. this._cullFace = null;
  5024. this._zOffset = 0;
  5025. this._isDepthTestDirty = true;
  5026. this._isDepthMaskDirty = true;
  5027. this._isDepthFuncDirty = false;
  5028. this._isCullFaceDirty = false;
  5029. this._isCullDirty = false;
  5030. this._isZOffsetDirty = false;
  5031. };
  5032. _DepthCullingState.prototype.apply = function (gl) {
  5033. if (!this.isDirty) {
  5034. return;
  5035. }
  5036. // Cull
  5037. if (this._isCullDirty) {
  5038. if (this.cull) {
  5039. gl.enable(gl.CULL_FACE);
  5040. }
  5041. else {
  5042. gl.disable(gl.CULL_FACE);
  5043. }
  5044. this._isCullDirty = false;
  5045. }
  5046. // Cull face
  5047. if (this._isCullFaceDirty) {
  5048. gl.cullFace(this.cullFace);
  5049. this._isCullFaceDirty = false;
  5050. }
  5051. // Depth mask
  5052. if (this._isDepthMaskDirty) {
  5053. gl.depthMask(this.depthMask);
  5054. this._isDepthMaskDirty = false;
  5055. }
  5056. // Depth test
  5057. if (this._isDepthTestDirty) {
  5058. if (this.depthTest) {
  5059. gl.enable(gl.DEPTH_TEST);
  5060. }
  5061. else {
  5062. gl.disable(gl.DEPTH_TEST);
  5063. }
  5064. this._isDepthTestDirty = false;
  5065. }
  5066. // Depth func
  5067. if (this._isDepthFuncDirty) {
  5068. gl.depthFunc(this.depthFunc);
  5069. this._isDepthFuncDirty = false;
  5070. }
  5071. // zOffset
  5072. if (this._isZOffsetDirty) {
  5073. if (this.zOffset) {
  5074. gl.enable(gl.POLYGON_OFFSET_FILL);
  5075. gl.polygonOffset(this.zOffset, 0);
  5076. }
  5077. else {
  5078. gl.disable(gl.POLYGON_OFFSET_FILL);
  5079. }
  5080. this._isZOffsetDirty = false;
  5081. }
  5082. };
  5083. return _DepthCullingState;
  5084. })();
  5085. Internals._DepthCullingState = _DepthCullingState;
  5086. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5087. })(BABYLON || (BABYLON = {}));
  5088. var BABYLON;
  5089. (function (BABYLON) {
  5090. var compileShader = function (gl, source, type, defines) {
  5091. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5092. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5093. gl.compileShader(shader);
  5094. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5095. throw new Error(gl.getShaderInfoLog(shader));
  5096. }
  5097. return shader;
  5098. };
  5099. var getWebGLTextureType = function (gl, type) {
  5100. var textureType = gl.UNSIGNED_BYTE;
  5101. if (type === Engine.TEXTURETYPE_FLOAT)
  5102. textureType = gl.FLOAT;
  5103. return textureType;
  5104. };
  5105. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5106. var magFilter = gl.NEAREST;
  5107. var minFilter = gl.NEAREST;
  5108. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5109. magFilter = gl.LINEAR;
  5110. if (generateMipMaps) {
  5111. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5112. }
  5113. else {
  5114. minFilter = gl.LINEAR;
  5115. }
  5116. }
  5117. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5118. magFilter = gl.LINEAR;
  5119. if (generateMipMaps) {
  5120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5121. }
  5122. else {
  5123. minFilter = gl.LINEAR;
  5124. }
  5125. }
  5126. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5127. magFilter = gl.NEAREST;
  5128. if (generateMipMaps) {
  5129. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5130. }
  5131. else {
  5132. minFilter = gl.NEAREST;
  5133. }
  5134. }
  5135. return {
  5136. min: minFilter,
  5137. mag: magFilter
  5138. };
  5139. };
  5140. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5142. var engine = scene.getEngine();
  5143. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5144. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5145. gl.bindTexture(gl.TEXTURE_2D, texture);
  5146. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5147. texture._baseWidth = width;
  5148. texture._baseHeight = height;
  5149. texture._width = potWidth;
  5150. texture._height = potHeight;
  5151. texture.isReady = true;
  5152. processFunction(potWidth, potHeight);
  5153. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5156. if (!noMipmap && !isCompressed) {
  5157. gl.generateMipmap(gl.TEXTURE_2D);
  5158. }
  5159. gl.bindTexture(gl.TEXTURE_2D, null);
  5160. engine.resetTextureCache();
  5161. scene._removePendingData(texture);
  5162. if (onLoad) {
  5163. onLoad();
  5164. }
  5165. };
  5166. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5167. var img;
  5168. var onload = function () {
  5169. loadedImages[index] = img;
  5170. loadedImages._internalCount++;
  5171. scene._removePendingData(img);
  5172. if (loadedImages._internalCount === 6) {
  5173. onfinish(loadedImages);
  5174. }
  5175. };
  5176. var onerror = function () {
  5177. scene._removePendingData(img);
  5178. };
  5179. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5180. scene._addPendingData(img);
  5181. };
  5182. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5183. var loadedImages = [];
  5184. loadedImages._internalCount = 0;
  5185. for (var index = 0; index < 6; index++) {
  5186. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5187. }
  5188. };
  5189. var EngineCapabilities = (function () {
  5190. function EngineCapabilities() {
  5191. }
  5192. return EngineCapabilities;
  5193. })();
  5194. BABYLON.EngineCapabilities = EngineCapabilities;
  5195. /**
  5196. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5197. */
  5198. var Engine = (function () {
  5199. /**
  5200. * @constructor
  5201. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5202. * @param {boolean} [antialias] - enable antialias
  5203. * @param options - further options to be sent to the getContext function
  5204. */
  5205. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5206. var _this = this;
  5207. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5208. // Public members
  5209. this.isFullscreen = false;
  5210. this.isPointerLock = false;
  5211. this.cullBackFaces = true;
  5212. this.renderEvenInBackground = true;
  5213. // To enable/disable IDB support and avoid XHR on .manifest
  5214. this.enableOfflineSupport = true;
  5215. this.scenes = new Array();
  5216. this._windowIsBackground = false;
  5217. this._webGLVersion = "1.0";
  5218. this._drawCalls = 0;
  5219. this._renderingQueueLaunched = false;
  5220. this._activeRenderLoops = [];
  5221. // FPS
  5222. this.fpsRange = 60;
  5223. this.previousFramesDuration = [];
  5224. this.fps = 60;
  5225. this.deltaTime = 0;
  5226. // States
  5227. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5228. this._alphaState = new BABYLON.Internals._AlphaState();
  5229. this._alphaMode = Engine.ALPHA_DISABLE;
  5230. // Cache
  5231. this._loadedTexturesCache = new Array();
  5232. this._maxTextureChannels = 16;
  5233. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5234. this._compiledEffects = {};
  5235. this._uintIndicesCurrentlySet = false;
  5236. this._renderingCanvas = canvas;
  5237. options = options || {};
  5238. options.antialias = antialias;
  5239. if (options.preserveDrawingBuffer === undefined) {
  5240. options.preserveDrawingBuffer = false;
  5241. }
  5242. // GL
  5243. //try {
  5244. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5245. // if (this._gl) {
  5246. // this._webGLVersion = "2.0";
  5247. // }
  5248. //} catch (e) {
  5249. // // Do nothing
  5250. //}
  5251. if (!this._gl) {
  5252. try {
  5253. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5254. }
  5255. catch (e) {
  5256. throw new Error("WebGL not supported");
  5257. }
  5258. }
  5259. if (!this._gl) {
  5260. throw new Error("WebGL not supported");
  5261. }
  5262. this._onBlur = function () {
  5263. _this._windowIsBackground = true;
  5264. };
  5265. this._onFocus = function () {
  5266. _this._windowIsBackground = false;
  5267. };
  5268. window.addEventListener("blur", this._onBlur);
  5269. window.addEventListener("focus", this._onFocus);
  5270. // Viewport
  5271. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5272. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5273. this.resize();
  5274. // Caps
  5275. this._caps = new EngineCapabilities();
  5276. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5277. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5278. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5279. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5280. // Infos
  5281. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5282. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5283. if (rendererInfo != null) {
  5284. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5285. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5286. }
  5287. if (!this._glVendor) {
  5288. this._glVendor = "Unknown vendor";
  5289. }
  5290. if (!this._glRenderer) {
  5291. this._glRenderer = "Unknown renderer";
  5292. }
  5293. // Extensions
  5294. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5295. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5296. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5297. 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');
  5298. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5299. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5300. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5301. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5302. this._caps.highPrecisionShaderSupported = true;
  5303. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5304. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5305. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5306. if (this._gl.getShaderPrecisionFormat) {
  5307. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5308. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5309. }
  5310. // Depth buffer
  5311. this.setDepthBuffer(true);
  5312. this.setDepthFunctionToLessOrEqual();
  5313. this.setDepthWrite(true);
  5314. // Fullscreen
  5315. this._onFullscreenChange = function () {
  5316. if (document.fullscreen !== undefined) {
  5317. _this.isFullscreen = document.fullscreen;
  5318. }
  5319. else if (document.mozFullScreen !== undefined) {
  5320. _this.isFullscreen = document.mozFullScreen;
  5321. }
  5322. else if (document.webkitIsFullScreen !== undefined) {
  5323. _this.isFullscreen = document.webkitIsFullScreen;
  5324. }
  5325. else if (document.msIsFullScreen !== undefined) {
  5326. _this.isFullscreen = document.msIsFullScreen;
  5327. }
  5328. // Pointer lock
  5329. if (_this.isFullscreen && _this._pointerLockRequested) {
  5330. canvas.requestPointerLock = canvas.requestPointerLock ||
  5331. canvas.msRequestPointerLock ||
  5332. canvas.mozRequestPointerLock ||
  5333. canvas.webkitRequestPointerLock;
  5334. if (canvas.requestPointerLock) {
  5335. canvas.requestPointerLock();
  5336. }
  5337. }
  5338. };
  5339. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5340. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5341. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5342. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5343. // Pointer lock
  5344. this._onPointerLockChange = function () {
  5345. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5346. document.webkitPointerLockElement === canvas ||
  5347. document.msPointerLockElement === canvas ||
  5348. document.pointerLockElement === canvas);
  5349. };
  5350. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5351. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5352. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5353. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5354. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5355. Engine.audioEngine = new BABYLON.AudioEngine();
  5356. }
  5357. //default loading screen
  5358. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5359. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5360. }
  5361. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5362. get: function () {
  5363. return Engine._ALPHA_DISABLE;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5369. get: function () {
  5370. return Engine._ALPHA_ONEONE;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "ALPHA_ADD", {
  5376. get: function () {
  5377. return Engine._ALPHA_ADD;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5383. get: function () {
  5384. return Engine._ALPHA_COMBINE;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5390. get: function () {
  5391. return Engine._ALPHA_SUBTRACT;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5397. get: function () {
  5398. return Engine._ALPHA_MULTIPLY;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5404. get: function () {
  5405. return Engine._ALPHA_MAXIMIZED;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5411. get: function () {
  5412. return Engine._DELAYLOADSTATE_NONE;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5418. get: function () {
  5419. return Engine._DELAYLOADSTATE_LOADED;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5425. get: function () {
  5426. return Engine._DELAYLOADSTATE_LOADING;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5432. get: function () {
  5433. return Engine._DELAYLOADSTATE_NOTLOADED;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5439. get: function () {
  5440. return Engine._TEXTUREFORMAT_ALPHA;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5446. get: function () {
  5447. return Engine._TEXTUREFORMAT_LUMINANCE;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5453. get: function () {
  5454. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5460. get: function () {
  5461. return Engine._TEXTUREFORMAT_RGB;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5467. get: function () {
  5468. return Engine._TEXTUREFORMAT_RGBA;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5474. get: function () {
  5475. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5481. get: function () {
  5482. return Engine._TEXTURETYPE_FLOAT;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "Version", {
  5488. get: function () {
  5489. return "2.4.0-alpha";
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5495. get: function () {
  5496. return this._webGLVersion;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Engine.prototype._prepareWorkingCanvas = function () {
  5502. if (this._workingCanvas) {
  5503. return;
  5504. }
  5505. this._workingCanvas = document.createElement("canvas");
  5506. this._workingContext = this._workingCanvas.getContext("2d");
  5507. };
  5508. Engine.prototype.resetTextureCache = function () {
  5509. for (var index = 0; index < this._maxTextureChannels; index++) {
  5510. this._activeTexturesCache[index] = null;
  5511. }
  5512. };
  5513. Engine.prototype.getGlInfo = function () {
  5514. return {
  5515. vendor: this._glVendor,
  5516. renderer: this._glRenderer,
  5517. version: this._glVersion
  5518. };
  5519. };
  5520. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5521. if (useScreen === void 0) { useScreen = false; }
  5522. var viewport = camera.viewport;
  5523. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5524. };
  5525. Engine.prototype.getRenderWidth = function (useScreen) {
  5526. if (useScreen === void 0) { useScreen = false; }
  5527. if (!useScreen && this._currentRenderTarget) {
  5528. return this._currentRenderTarget._width;
  5529. }
  5530. return this._renderingCanvas.width;
  5531. };
  5532. Engine.prototype.getRenderHeight = function (useScreen) {
  5533. if (useScreen === void 0) { useScreen = false; }
  5534. if (!useScreen && this._currentRenderTarget) {
  5535. return this._currentRenderTarget._height;
  5536. }
  5537. return this._renderingCanvas.height;
  5538. };
  5539. Engine.prototype.getRenderingCanvas = function () {
  5540. return this._renderingCanvas;
  5541. };
  5542. Engine.prototype.getRenderingCanvasClientRect = function () {
  5543. return this._renderingCanvas.getBoundingClientRect();
  5544. };
  5545. Engine.prototype.setHardwareScalingLevel = function (level) {
  5546. this._hardwareScalingLevel = level;
  5547. this.resize();
  5548. };
  5549. Engine.prototype.getHardwareScalingLevel = function () {
  5550. return this._hardwareScalingLevel;
  5551. };
  5552. Engine.prototype.getLoadedTexturesCache = function () {
  5553. return this._loadedTexturesCache;
  5554. };
  5555. Engine.prototype.getCaps = function () {
  5556. return this._caps;
  5557. };
  5558. Object.defineProperty(Engine.prototype, "drawCalls", {
  5559. get: function () {
  5560. return this._drawCalls;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. // Methods
  5566. Engine.prototype.resetDrawCalls = function () {
  5567. this._drawCalls = 0;
  5568. };
  5569. Engine.prototype.setDepthFunctionToGreater = function () {
  5570. this._depthCullingState.depthFunc = this._gl.GREATER;
  5571. };
  5572. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5573. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5574. };
  5575. Engine.prototype.setDepthFunctionToLess = function () {
  5576. this._depthCullingState.depthFunc = this._gl.LESS;
  5577. };
  5578. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5579. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5580. };
  5581. /**
  5582. * stop executing a render loop function and remove it from the execution array
  5583. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5584. */
  5585. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5586. if (!renderFunction) {
  5587. this._activeRenderLoops = [];
  5588. return;
  5589. }
  5590. var index = this._activeRenderLoops.indexOf(renderFunction);
  5591. if (index >= 0) {
  5592. this._activeRenderLoops.splice(index, 1);
  5593. }
  5594. };
  5595. Engine.prototype._renderLoop = function () {
  5596. var shouldRender = true;
  5597. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5598. shouldRender = false;
  5599. }
  5600. if (shouldRender) {
  5601. // Start new frame
  5602. this.beginFrame();
  5603. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5604. var renderFunction = this._activeRenderLoops[index];
  5605. renderFunction();
  5606. }
  5607. // Present
  5608. this.endFrame();
  5609. }
  5610. if (this._activeRenderLoops.length > 0) {
  5611. // Register new frame
  5612. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5613. }
  5614. else {
  5615. this._renderingQueueLaunched = false;
  5616. }
  5617. };
  5618. /**
  5619. * Register and execute a render loop. The engine can have more than one render function.
  5620. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5621. * @example
  5622. * engine.runRenderLoop(function () {
  5623. * scene.render()
  5624. * })
  5625. */
  5626. Engine.prototype.runRenderLoop = function (renderFunction) {
  5627. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5628. return;
  5629. }
  5630. this._activeRenderLoops.push(renderFunction);
  5631. if (!this._renderingQueueLaunched) {
  5632. this._renderingQueueLaunched = true;
  5633. this._bindedRenderFunction = this._renderLoop.bind(this);
  5634. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5635. }
  5636. };
  5637. /**
  5638. * Toggle full screen mode.
  5639. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5640. */
  5641. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5642. if (this.isFullscreen) {
  5643. BABYLON.Tools.ExitFullscreen();
  5644. }
  5645. else {
  5646. this._pointerLockRequested = requestPointerLock;
  5647. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5648. }
  5649. };
  5650. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5651. this.applyStates();
  5652. if (backBuffer) {
  5653. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5654. }
  5655. if (depthStencil && this._depthCullingState.depthMask) {
  5656. this._gl.clearDepth(1.0);
  5657. }
  5658. var mode = 0;
  5659. if (backBuffer) {
  5660. mode |= this._gl.COLOR_BUFFER_BIT;
  5661. }
  5662. if (depthStencil && this._depthCullingState.depthMask) {
  5663. mode |= this._gl.DEPTH_BUFFER_BIT;
  5664. }
  5665. this._gl.clear(mode);
  5666. };
  5667. /**
  5668. * Set the WebGL's viewport
  5669. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5670. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5671. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5672. */
  5673. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5674. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5675. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5676. var x = viewport.x || 0;
  5677. var y = viewport.y || 0;
  5678. this._cachedViewport = viewport;
  5679. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5680. };
  5681. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5682. this._cachedViewport = null;
  5683. this._gl.viewport(x, y, width, height);
  5684. };
  5685. Engine.prototype.beginFrame = function () {
  5686. this._measureFps();
  5687. };
  5688. Engine.prototype.endFrame = function () {
  5689. //this.flushFramebuffer();
  5690. };
  5691. /**
  5692. * resize the view according to the canvas' size.
  5693. * @example
  5694. * window.addEventListener("resize", function () {
  5695. * engine.resize();
  5696. * });
  5697. */
  5698. Engine.prototype.resize = function () {
  5699. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5700. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5701. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5702. for (var index = 0; index < this.scenes.length; index++) {
  5703. var scene = this.scenes[index];
  5704. if (scene.debugLayer.isVisible()) {
  5705. scene.debugLayer._syncPositions();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * force a specific size of the canvas
  5711. * @param {number} width - the new canvas' width
  5712. * @param {number} height - the new canvas' height
  5713. */
  5714. Engine.prototype.setSize = function (width, height) {
  5715. this._renderingCanvas.width = width;
  5716. this._renderingCanvas.height = height;
  5717. for (var index = 0; index < this.scenes.length; index++) {
  5718. var scene = this.scenes[index];
  5719. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5720. var cam = scene.cameras[camIndex];
  5721. cam._currentRenderId = 0;
  5722. }
  5723. }
  5724. };
  5725. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5726. this._currentRenderTarget = texture;
  5727. var gl = this._gl;
  5728. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5729. if (texture.isCube) {
  5730. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5731. }
  5732. else {
  5733. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5734. }
  5735. this._gl.viewport(0, 0, texture._width, texture._height);
  5736. this.wipeCaches();
  5737. };
  5738. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5739. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5740. this._currentRenderTarget = null;
  5741. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5742. var gl = this._gl;
  5743. gl.bindTexture(gl.TEXTURE_2D, texture);
  5744. gl.generateMipmap(gl.TEXTURE_2D);
  5745. gl.bindTexture(gl.TEXTURE_2D, null);
  5746. }
  5747. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5748. };
  5749. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5750. if (texture.generateMipMaps) {
  5751. var gl = this._gl;
  5752. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5754. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5755. }
  5756. };
  5757. Engine.prototype.flushFramebuffer = function () {
  5758. this._gl.flush();
  5759. };
  5760. Engine.prototype.restoreDefaultFramebuffer = function () {
  5761. this._currentRenderTarget = null;
  5762. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5763. this.setViewport(this._cachedViewport);
  5764. this.wipeCaches();
  5765. };
  5766. // VBOs
  5767. Engine.prototype._resetVertexBufferBinding = function () {
  5768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5769. this._cachedVertexBuffers = null;
  5770. };
  5771. Engine.prototype.createVertexBuffer = function (vertices) {
  5772. var vbo = this._gl.createBuffer();
  5773. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5774. if (vertices instanceof Float32Array) {
  5775. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5776. }
  5777. else {
  5778. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5779. }
  5780. this._resetVertexBufferBinding();
  5781. vbo.references = 1;
  5782. return vbo;
  5783. };
  5784. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5785. var vbo = this._gl.createBuffer();
  5786. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5787. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5788. this._resetVertexBufferBinding();
  5789. vbo.references = 1;
  5790. return vbo;
  5791. };
  5792. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5794. if (offset === undefined) {
  5795. offset = 0;
  5796. }
  5797. if (vertices instanceof Float32Array) {
  5798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5799. }
  5800. else {
  5801. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5802. }
  5803. this._resetVertexBufferBinding();
  5804. };
  5805. Engine.prototype._resetIndexBufferBinding = function () {
  5806. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5807. this._cachedIndexBuffer = null;
  5808. };
  5809. Engine.prototype.createIndexBuffer = function (indices) {
  5810. var vbo = this._gl.createBuffer();
  5811. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5812. // Check for 32 bits indices
  5813. var arrayBuffer;
  5814. var need32Bits = false;
  5815. if (this._caps.uintIndices) {
  5816. for (var index = 0; index < indices.length; index++) {
  5817. if (indices[index] > 65535) {
  5818. need32Bits = true;
  5819. break;
  5820. }
  5821. }
  5822. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5823. }
  5824. else {
  5825. arrayBuffer = new Uint16Array(indices);
  5826. }
  5827. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5828. this._resetIndexBufferBinding();
  5829. vbo.references = 1;
  5830. vbo.is32Bits = need32Bits;
  5831. return vbo;
  5832. };
  5833. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5834. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5835. this._cachedVertexBuffers = vertexBuffer;
  5836. this._cachedEffectForVertexBuffers = effect;
  5837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5838. var offset = 0;
  5839. for (var index = 0; index < vertexDeclaration.length; index++) {
  5840. var order = effect.getAttributeLocation(index);
  5841. if (order >= 0) {
  5842. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5843. }
  5844. offset += vertexDeclaration[index] * 4;
  5845. }
  5846. }
  5847. if (this._cachedIndexBuffer !== indexBuffer) {
  5848. this._cachedIndexBuffer = indexBuffer;
  5849. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5850. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5851. }
  5852. };
  5853. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5854. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5855. this._cachedVertexBuffers = vertexBuffers;
  5856. this._cachedEffectForVertexBuffers = effect;
  5857. var attributes = effect.getAttributesNames();
  5858. for (var index = 0; index < attributes.length; index++) {
  5859. var order = effect.getAttributeLocation(index);
  5860. if (order >= 0) {
  5861. var vertexBuffer = vertexBuffers[attributes[index]];
  5862. if (!vertexBuffer) {
  5863. continue;
  5864. }
  5865. var stride = vertexBuffer.getStrideSize();
  5866. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5867. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5868. }
  5869. }
  5870. }
  5871. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5872. this._cachedIndexBuffer = indexBuffer;
  5873. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5874. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5875. }
  5876. };
  5877. Engine.prototype._releaseBuffer = function (buffer) {
  5878. buffer.references--;
  5879. if (buffer.references === 0) {
  5880. this._gl.deleteBuffer(buffer);
  5881. return true;
  5882. }
  5883. return false;
  5884. };
  5885. Engine.prototype.createInstancesBuffer = function (capacity) {
  5886. var buffer = this._gl.createBuffer();
  5887. buffer.capacity = capacity;
  5888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5889. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5890. return buffer;
  5891. };
  5892. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5893. this._gl.deleteBuffer(buffer);
  5894. };
  5895. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5897. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5898. for (var index = 0; index < 4; index++) {
  5899. var offsetLocation = offsetLocations[index];
  5900. this._gl.enableVertexAttribArray(offsetLocation);
  5901. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5902. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5903. }
  5904. };
  5905. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5906. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5907. for (var index = 0; index < 4; index++) {
  5908. var offsetLocation = offsetLocations[index];
  5909. this._gl.disableVertexAttribArray(offsetLocation);
  5910. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5911. }
  5912. };
  5913. Engine.prototype.applyStates = function () {
  5914. this._depthCullingState.apply(this._gl);
  5915. this._alphaState.apply(this._gl);
  5916. };
  5917. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5918. // Apply states
  5919. this.applyStates();
  5920. this._drawCalls++;
  5921. // Render
  5922. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5923. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5924. if (instancesCount) {
  5925. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5926. return;
  5927. }
  5928. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5929. };
  5930. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5931. // Apply states
  5932. this.applyStates();
  5933. this._drawCalls++;
  5934. if (instancesCount) {
  5935. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5936. return;
  5937. }
  5938. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5939. };
  5940. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5941. // Apply states
  5942. this.applyStates();
  5943. this._drawCalls++;
  5944. if (instancesCount) {
  5945. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5946. return;
  5947. }
  5948. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5949. };
  5950. // Shaders
  5951. Engine.prototype._releaseEffect = function (effect) {
  5952. if (this._compiledEffects[effect._key]) {
  5953. delete this._compiledEffects[effect._key];
  5954. if (effect.getProgram()) {
  5955. this._gl.deleteProgram(effect.getProgram());
  5956. }
  5957. }
  5958. };
  5959. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5960. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5961. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5962. var name = vertex + "+" + fragment + "@" + defines;
  5963. if (this._compiledEffects[name]) {
  5964. return this._compiledEffects[name];
  5965. }
  5966. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5967. effect._key = name;
  5968. this._compiledEffects[name] = effect;
  5969. return effect;
  5970. };
  5971. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5972. if (uniformsNames === void 0) { uniformsNames = []; }
  5973. if (samplers === void 0) { samplers = []; }
  5974. if (defines === void 0) { defines = ""; }
  5975. return this.createEffect({
  5976. vertex: "particles",
  5977. fragmentElement: fragmentName
  5978. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5979. };
  5980. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5981. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5982. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5983. var shaderProgram = this._gl.createProgram();
  5984. this._gl.attachShader(shaderProgram, vertexShader);
  5985. this._gl.attachShader(shaderProgram, fragmentShader);
  5986. this._gl.linkProgram(shaderProgram);
  5987. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5988. if (!linked) {
  5989. var error = this._gl.getProgramInfoLog(shaderProgram);
  5990. if (error) {
  5991. throw new Error(error);
  5992. }
  5993. }
  5994. this._gl.deleteShader(vertexShader);
  5995. this._gl.deleteShader(fragmentShader);
  5996. return shaderProgram;
  5997. };
  5998. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5999. var results = [];
  6000. for (var index = 0; index < uniformsNames.length; index++) {
  6001. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6002. }
  6003. return results;
  6004. };
  6005. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6006. var results = [];
  6007. for (var index = 0; index < attributesNames.length; index++) {
  6008. try {
  6009. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6010. }
  6011. catch (e) {
  6012. results.push(-1);
  6013. }
  6014. }
  6015. return results;
  6016. };
  6017. Engine.prototype.enableEffect = function (effect) {
  6018. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6019. if (effect && effect.onBind) {
  6020. effect.onBind(effect);
  6021. }
  6022. return;
  6023. }
  6024. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6025. // Use program
  6026. this._gl.useProgram(effect.getProgram());
  6027. for (var i in this._vertexAttribArrays) {
  6028. //make sure this is a number)
  6029. var iAsNumber = +i;
  6030. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6031. continue;
  6032. }
  6033. this._vertexAttribArrays[iAsNumber] = false;
  6034. this._gl.disableVertexAttribArray(iAsNumber);
  6035. }
  6036. var attributesCount = effect.getAttributesCount();
  6037. for (var index = 0; index < attributesCount; index++) {
  6038. // Attributes
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._vertexAttribArrays[order] = true;
  6042. this._gl.enableVertexAttribArray(order);
  6043. }
  6044. }
  6045. this._currentEffect = effect;
  6046. if (effect.onBind) {
  6047. effect.onBind(effect);
  6048. }
  6049. };
  6050. Engine.prototype.setArray = function (uniform, array) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray2 = function (uniform, array) {
  6056. if (!uniform || array.length % 2 !== 0)
  6057. return;
  6058. this._gl.uniform2fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray3 = function (uniform, array) {
  6061. if (!uniform || array.length % 3 !== 0)
  6062. return;
  6063. this._gl.uniform3fv(uniform, array);
  6064. };
  6065. Engine.prototype.setArray4 = function (uniform, array) {
  6066. if (!uniform || array.length % 4 !== 0)
  6067. return;
  6068. this._gl.uniform4fv(uniform, array);
  6069. };
  6070. Engine.prototype.setMatrices = function (uniform, matrices) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6074. };
  6075. Engine.prototype.setMatrix = function (uniform, matrix) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6079. };
  6080. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6084. };
  6085. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6089. };
  6090. Engine.prototype.setFloat = function (uniform, value) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform1f(uniform, value);
  6094. };
  6095. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform2f(uniform, x, y);
  6099. };
  6100. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform3f(uniform, x, y, z);
  6104. };
  6105. Engine.prototype.setBool = function (uniform, bool) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform1i(uniform, bool);
  6109. };
  6110. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform4f(uniform, x, y, z, w);
  6114. };
  6115. Engine.prototype.setColor3 = function (uniform, color3) {
  6116. if (!uniform)
  6117. return;
  6118. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6119. };
  6120. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6121. if (!uniform)
  6122. return;
  6123. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6124. };
  6125. // States
  6126. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6127. if (zOffset === void 0) { zOffset = 0; }
  6128. if (reverseSide === void 0) { reverseSide = false; }
  6129. // Culling
  6130. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6131. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6132. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6133. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6134. if (culling) {
  6135. this._depthCullingState.cullFace = cullFace;
  6136. this._depthCullingState.cull = true;
  6137. }
  6138. else {
  6139. this._depthCullingState.cull = false;
  6140. }
  6141. }
  6142. // Z offset
  6143. this._depthCullingState.zOffset = zOffset;
  6144. };
  6145. Engine.prototype.setDepthBuffer = function (enable) {
  6146. this._depthCullingState.depthTest = enable;
  6147. };
  6148. Engine.prototype.getDepthWrite = function () {
  6149. return this._depthCullingState.depthMask;
  6150. };
  6151. Engine.prototype.setDepthWrite = function (enable) {
  6152. this._depthCullingState.depthMask = enable;
  6153. };
  6154. Engine.prototype.setColorWrite = function (enable) {
  6155. this._gl.colorMask(enable, enable, enable, enable);
  6156. };
  6157. Engine.prototype.setAlphaMode = function (mode) {
  6158. if (this._alphaMode === mode) {
  6159. return;
  6160. }
  6161. switch (mode) {
  6162. case Engine.ALPHA_DISABLE:
  6163. this.setDepthWrite(true);
  6164. this._alphaState.alphaBlend = false;
  6165. break;
  6166. case Engine.ALPHA_COMBINE:
  6167. this.setDepthWrite(false);
  6168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6169. this._alphaState.alphaBlend = true;
  6170. break;
  6171. case Engine.ALPHA_ONEONE:
  6172. this.setDepthWrite(false);
  6173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6174. this._alphaState.alphaBlend = true;
  6175. break;
  6176. case Engine.ALPHA_ADD:
  6177. this.setDepthWrite(false);
  6178. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6179. this._alphaState.alphaBlend = true;
  6180. break;
  6181. case Engine.ALPHA_SUBTRACT:
  6182. this.setDepthWrite(false);
  6183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6184. this._alphaState.alphaBlend = true;
  6185. break;
  6186. case Engine.ALPHA_MULTIPLY:
  6187. this.setDepthWrite(false);
  6188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6189. this._alphaState.alphaBlend = true;
  6190. break;
  6191. case Engine.ALPHA_MAXIMIZED:
  6192. this.setDepthWrite(false);
  6193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6194. this._alphaState.alphaBlend = true;
  6195. break;
  6196. }
  6197. this._alphaMode = mode;
  6198. };
  6199. Engine.prototype.getAlphaMode = function () {
  6200. return this._alphaMode;
  6201. };
  6202. Engine.prototype.setAlphaTesting = function (enable) {
  6203. this._alphaTest = enable;
  6204. };
  6205. Engine.prototype.getAlphaTesting = function () {
  6206. return this._alphaTest;
  6207. };
  6208. // Textures
  6209. Engine.prototype.wipeCaches = function () {
  6210. this.resetTextureCache();
  6211. this._currentEffect = null;
  6212. this._depthCullingState.reset();
  6213. this._alphaState.reset();
  6214. this._cachedVertexBuffers = null;
  6215. this._cachedIndexBuffer = null;
  6216. this._cachedEffectForVertexBuffers = null;
  6217. };
  6218. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6219. var gl = this._gl;
  6220. gl.bindTexture(gl.TEXTURE_2D, texture);
  6221. var magFilter = gl.NEAREST;
  6222. var minFilter = gl.NEAREST;
  6223. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6224. magFilter = gl.LINEAR;
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6228. magFilter = gl.LINEAR;
  6229. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6230. }
  6231. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6233. gl.bindTexture(gl.TEXTURE_2D, null);
  6234. texture.samplingMode = samplingMode;
  6235. };
  6236. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6237. var _this = this;
  6238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6239. if (onLoad === void 0) { onLoad = null; }
  6240. if (onError === void 0) { onError = null; }
  6241. if (buffer === void 0) { buffer = null; }
  6242. var texture = this._gl.createTexture();
  6243. var extension;
  6244. var fromData = false;
  6245. if (url.substr(0, 5) === "data:") {
  6246. fromData = true;
  6247. }
  6248. if (!fromData)
  6249. extension = url.substr(url.length - 4, 4).toLowerCase();
  6250. else {
  6251. var oldUrl = url;
  6252. fromData = oldUrl.split(':');
  6253. url = oldUrl;
  6254. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6255. }
  6256. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6257. var isTGA = (extension === ".tga");
  6258. scene._addPendingData(texture);
  6259. texture.url = url;
  6260. texture.noMipmap = noMipmap;
  6261. texture.references = 1;
  6262. texture.samplingMode = samplingMode;
  6263. this._loadedTexturesCache.push(texture);
  6264. var onerror = function () {
  6265. scene._removePendingData(texture);
  6266. if (onError) {
  6267. onError();
  6268. }
  6269. };
  6270. var callback;
  6271. if (isTGA) {
  6272. callback = function (arrayBuffer) {
  6273. var data = new Uint8Array(arrayBuffer);
  6274. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6275. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6276. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6277. }, onLoad, samplingMode);
  6278. };
  6279. if (!(fromData instanceof Array))
  6280. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6281. callback(arrayBuffer);
  6282. }, onerror, scene.database, true);
  6283. else
  6284. callback(buffer);
  6285. }
  6286. else if (isDDS) {
  6287. callback = function (data) {
  6288. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6289. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6290. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6291. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6292. }, onLoad, samplingMode);
  6293. };
  6294. if (!(fromData instanceof Array))
  6295. BABYLON.Tools.LoadFile(url, function (data) {
  6296. callback(data);
  6297. }, onerror, scene.database, true);
  6298. else
  6299. callback(buffer);
  6300. }
  6301. else {
  6302. var onload = function (img) {
  6303. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6304. var isPot = (img.width === potWidth && img.height === potHeight);
  6305. if (!isPot) {
  6306. _this._prepareWorkingCanvas();
  6307. _this._workingCanvas.width = potWidth;
  6308. _this._workingCanvas.height = potHeight;
  6309. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6310. _this._workingContext.imageSmoothingEnabled = false;
  6311. _this._workingContext.mozImageSmoothingEnabled = false;
  6312. _this._workingContext.oImageSmoothingEnabled = false;
  6313. _this._workingContext.webkitImageSmoothingEnabled = false;
  6314. _this._workingContext.msImageSmoothingEnabled = false;
  6315. }
  6316. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6317. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6318. _this._workingContext.imageSmoothingEnabled = true;
  6319. _this._workingContext.mozImageSmoothingEnabled = true;
  6320. _this._workingContext.oImageSmoothingEnabled = true;
  6321. _this._workingContext.webkitImageSmoothingEnabled = true;
  6322. _this._workingContext.msImageSmoothingEnabled = true;
  6323. }
  6324. }
  6325. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6326. }, onLoad, samplingMode);
  6327. };
  6328. if (!(fromData instanceof Array))
  6329. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6330. else
  6331. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6332. }
  6333. return texture;
  6334. };
  6335. Engine.prototype._getInternalFormat = function (format) {
  6336. var internalFormat = this._gl.RGBA;
  6337. switch (format) {
  6338. case Engine.TEXTUREFORMAT_ALPHA:
  6339. internalFormat = this._gl.ALPHA;
  6340. break;
  6341. case Engine.TEXTUREFORMAT_LUMINANCE:
  6342. internalFormat = this._gl.LUMINANCE;
  6343. break;
  6344. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6345. internalFormat = this._gl.LUMINANCE_ALPHA;
  6346. break;
  6347. case Engine.TEXTUREFORMAT_RGB:
  6348. internalFormat = this._gl.RGB;
  6349. break;
  6350. case Engine.TEXTUREFORMAT_RGBA:
  6351. internalFormat = this._gl.RGBA;
  6352. break;
  6353. }
  6354. return internalFormat;
  6355. };
  6356. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6357. if (compression === void 0) { compression = null; }
  6358. var internalFormat = this._getInternalFormat(format);
  6359. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6361. if (compression) {
  6362. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6363. }
  6364. else {
  6365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6366. }
  6367. if (texture.generateMipMaps) {
  6368. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6369. }
  6370. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6371. this.resetTextureCache();
  6372. texture.isReady = true;
  6373. };
  6374. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6375. if (compression === void 0) { compression = null; }
  6376. var texture = this._gl.createTexture();
  6377. texture._baseWidth = width;
  6378. texture._baseHeight = height;
  6379. texture._width = width;
  6380. texture._height = height;
  6381. texture.references = 1;
  6382. this.updateRawTexture(texture, data, format, invertY, compression);
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6384. // Filters
  6385. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6387. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6388. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6389. texture.samplingMode = samplingMode;
  6390. this._loadedTexturesCache.push(texture);
  6391. return texture;
  6392. };
  6393. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6394. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6395. var texture = this._gl.createTexture();
  6396. texture._baseWidth = width;
  6397. texture._baseHeight = height;
  6398. if (forceExponantOfTwo) {
  6399. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6400. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6401. }
  6402. this.resetTextureCache();
  6403. texture._width = width;
  6404. texture._height = height;
  6405. texture.isReady = false;
  6406. texture.generateMipMaps = generateMipMaps;
  6407. texture.references = 1;
  6408. texture.samplingMode = samplingMode;
  6409. this.updateTextureSamplingMode(samplingMode, texture);
  6410. this._loadedTexturesCache.push(texture);
  6411. return texture;
  6412. };
  6413. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6414. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6415. if (texture.isCube) {
  6416. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6417. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6418. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6419. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6420. }
  6421. else {
  6422. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6424. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6425. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6426. }
  6427. };
  6428. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6429. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6432. if (texture.generateMipMaps) {
  6433. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6434. }
  6435. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6436. this.resetTextureCache();
  6437. texture.isReady = true;
  6438. };
  6439. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6440. if (texture._isDisabled) {
  6441. return;
  6442. }
  6443. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6444. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6445. try {
  6446. // Testing video texture support
  6447. if (this._videoTextureSupported === undefined) {
  6448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6449. if (this._gl.getError() !== 0) {
  6450. this._videoTextureSupported = false;
  6451. }
  6452. else {
  6453. this._videoTextureSupported = true;
  6454. }
  6455. }
  6456. // Copy video through the current working canvas if video texture is not supported
  6457. if (!this._videoTextureSupported) {
  6458. if (!texture._workingCanvas) {
  6459. texture._workingCanvas = document.createElement("canvas");
  6460. texture._workingContext = texture._workingCanvas.getContext("2d");
  6461. texture._workingCanvas.width = texture._width;
  6462. texture._workingCanvas.height = texture._height;
  6463. }
  6464. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6465. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6466. }
  6467. else {
  6468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6469. }
  6470. if (texture.generateMipMaps) {
  6471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6472. }
  6473. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6474. this.resetTextureCache();
  6475. texture.isReady = true;
  6476. }
  6477. catch (ex) {
  6478. // Something unexpected
  6479. // Let's disable the texture
  6480. texture._isDisabled = true;
  6481. }
  6482. };
  6483. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6484. // old version had a "generateMipMaps" arg instead of options.
  6485. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6486. // in the same way, generateDepthBuffer is defaulted to true
  6487. var generateMipMaps = false;
  6488. var generateDepthBuffer = true;
  6489. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6490. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6491. if (options !== undefined) {
  6492. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6493. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6494. type = options.type === undefined ? type : options.type;
  6495. if (options.samplingMode !== undefined) {
  6496. samplingMode = options.samplingMode;
  6497. }
  6498. if (type === Engine.TEXTURETYPE_FLOAT) {
  6499. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6500. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6501. }
  6502. }
  6503. var gl = this._gl;
  6504. var texture = gl.createTexture();
  6505. gl.bindTexture(gl.TEXTURE_2D, texture);
  6506. var width = size.width || size;
  6507. var height = size.height || size;
  6508. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6509. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6510. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6511. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6512. }
  6513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6515. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6517. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6518. var depthBuffer;
  6519. // Create the depth buffer
  6520. if (generateDepthBuffer) {
  6521. depthBuffer = gl.createRenderbuffer();
  6522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6523. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6524. }
  6525. // Create the framebuffer
  6526. var framebuffer = gl.createFramebuffer();
  6527. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6528. if (generateDepthBuffer) {
  6529. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6530. }
  6531. if (generateMipMaps) {
  6532. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6533. }
  6534. // Unbind
  6535. gl.bindTexture(gl.TEXTURE_2D, null);
  6536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6538. texture._framebuffer = framebuffer;
  6539. if (generateDepthBuffer) {
  6540. texture._depthBuffer = depthBuffer;
  6541. }
  6542. texture._width = width;
  6543. texture._height = height;
  6544. texture.isReady = true;
  6545. texture.generateMipMaps = generateMipMaps;
  6546. texture.references = 1;
  6547. texture.samplingMode = samplingMode;
  6548. this.resetTextureCache();
  6549. this._loadedTexturesCache.push(texture);
  6550. return texture;
  6551. };
  6552. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6553. var gl = this._gl;
  6554. var texture = gl.createTexture();
  6555. var generateMipMaps = true;
  6556. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6557. if (options !== undefined) {
  6558. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6559. if (options.samplingMode !== undefined) {
  6560. samplingMode = options.samplingMode;
  6561. }
  6562. }
  6563. texture.isCube = true;
  6564. texture.references = 1;
  6565. texture.generateMipMaps = generateMipMaps;
  6566. texture.references = 1;
  6567. texture.samplingMode = samplingMode;
  6568. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6570. for (var face = 0; face < 6; face++) {
  6571. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6572. }
  6573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6577. // Create the depth buffer
  6578. var depthBuffer = gl.createRenderbuffer();
  6579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6580. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6581. // Create the framebuffer
  6582. var framebuffer = gl.createFramebuffer();
  6583. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6584. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6585. // Mipmaps
  6586. if (texture.generateMipMaps) {
  6587. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6588. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6589. }
  6590. // Unbind
  6591. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6592. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6593. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6594. texture._framebuffer = framebuffer;
  6595. texture._depthBuffer = depthBuffer;
  6596. this.resetTextureCache();
  6597. texture._width = size;
  6598. texture._height = size;
  6599. texture.isReady = true;
  6600. return texture;
  6601. };
  6602. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6603. var _this = this;
  6604. var gl = this._gl;
  6605. var texture = gl.createTexture();
  6606. texture.isCube = true;
  6607. texture.url = rootUrl;
  6608. texture.references = 1;
  6609. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6610. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6611. if (isDDS) {
  6612. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6613. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6614. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6615. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6617. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6618. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6619. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6620. }
  6621. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6625. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6626. _this.resetTextureCache();
  6627. texture._width = info.width;
  6628. texture._height = info.height;
  6629. texture.isReady = true;
  6630. }, null, null, true);
  6631. }
  6632. else {
  6633. cascadeLoad(rootUrl, scene, function (imgs) {
  6634. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6635. var height = width;
  6636. _this._prepareWorkingCanvas();
  6637. _this._workingCanvas.width = width;
  6638. _this._workingCanvas.height = height;
  6639. var faces = [
  6640. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6641. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6642. ];
  6643. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6644. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6645. for (var index = 0; index < faces.length; index++) {
  6646. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6647. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6648. }
  6649. if (!noMipmap) {
  6650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6651. }
  6652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6656. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6657. _this.resetTextureCache();
  6658. texture._width = width;
  6659. texture._height = height;
  6660. texture.isReady = true;
  6661. }, files);
  6662. }
  6663. return texture;
  6664. };
  6665. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6666. var _this = this;
  6667. var gl = this._gl;
  6668. var texture = gl.createTexture();
  6669. scene._addPendingData(texture);
  6670. texture.isCube = true;
  6671. texture.references = 1;
  6672. texture.url = url;
  6673. var internalFormat = this._getInternalFormat(format);
  6674. var textureType = gl.UNSIGNED_BYTE;
  6675. if (type === Engine.TEXTURETYPE_FLOAT) {
  6676. textureType = gl.FLOAT;
  6677. }
  6678. var width = size;
  6679. var height = width;
  6680. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6681. texture._width = width;
  6682. texture._height = height;
  6683. var onerror = function () {
  6684. scene._removePendingData(texture);
  6685. };
  6686. var internalCallback = function (data) {
  6687. var rgbeDataArrays = callback(data);
  6688. var facesIndex = [
  6689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6691. ];
  6692. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6694. if (!noMipmap && isPot) {
  6695. if (mipmmapGenerator) {
  6696. var arrayTemp = [];
  6697. // Data are known to be in +X +Y +Z -X -Y -Z
  6698. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6699. arrayTemp.push(rgbeDataArrays[0]); // +X
  6700. arrayTemp.push(rgbeDataArrays[3]); // -X
  6701. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6702. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6703. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6704. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6705. var mipData = mipmmapGenerator(arrayTemp);
  6706. for (var level = 0; level < mipData.length; level++) {
  6707. var mipSize = width >> level;
  6708. // mipData is order in +X -X +Y -Y +Z -Z
  6709. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6710. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6711. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6712. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6713. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6714. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6715. }
  6716. }
  6717. else {
  6718. // Data are known to be in +X +Y +Z -X -Y -Z
  6719. for (var index = 0; index < facesIndex.length; index++) {
  6720. var faceData = rgbeDataArrays[index];
  6721. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6722. }
  6723. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6724. }
  6725. }
  6726. else {
  6727. noMipmap = true;
  6728. }
  6729. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6732. }
  6733. else {
  6734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6736. }
  6737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6739. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6740. texture.isReady = true;
  6741. _this.resetTextureCache();
  6742. scene._removePendingData(texture);
  6743. };
  6744. BABYLON.Tools.LoadFile(url, function (data) {
  6745. internalCallback(data);
  6746. }, onerror, scene.database, true);
  6747. return texture;
  6748. };
  6749. ;
  6750. Engine.prototype._releaseTexture = function (texture) {
  6751. var gl = this._gl;
  6752. if (texture._framebuffer) {
  6753. gl.deleteFramebuffer(texture._framebuffer);
  6754. }
  6755. if (texture._depthBuffer) {
  6756. gl.deleteRenderbuffer(texture._depthBuffer);
  6757. }
  6758. gl.deleteTexture(texture);
  6759. // Unbind channels
  6760. this.unbindAllTextures();
  6761. var index = this._loadedTexturesCache.indexOf(texture);
  6762. if (index !== -1) {
  6763. this._loadedTexturesCache.splice(index, 1);
  6764. }
  6765. };
  6766. Engine.prototype.bindSamplers = function (effect) {
  6767. this._gl.useProgram(effect.getProgram());
  6768. var samplers = effect.getSamplers();
  6769. for (var index = 0; index < samplers.length; index++) {
  6770. var uniform = effect.getUniform(samplers[index]);
  6771. this._gl.uniform1i(uniform, index);
  6772. }
  6773. this._currentEffect = null;
  6774. };
  6775. Engine.prototype._bindTexture = function (channel, texture) {
  6776. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6777. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6778. this._activeTexturesCache[channel] = null;
  6779. };
  6780. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6781. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6782. };
  6783. Engine.prototype.unbindAllTextures = function () {
  6784. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6788. this._activeTexturesCache[channel] = null;
  6789. }
  6790. };
  6791. Engine.prototype.setTexture = function (channel, texture) {
  6792. if (channel < 0) {
  6793. return;
  6794. }
  6795. // Not ready?
  6796. if (!texture || !texture.isReady()) {
  6797. if (this._activeTexturesCache[channel] != null) {
  6798. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6799. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6800. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6801. this._activeTexturesCache[channel] = null;
  6802. }
  6803. return;
  6804. }
  6805. // Video
  6806. var alreadyActivated = false;
  6807. if (texture instanceof BABYLON.VideoTexture) {
  6808. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6809. alreadyActivated = true;
  6810. texture.update();
  6811. }
  6812. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6813. texture.delayLoad();
  6814. return;
  6815. }
  6816. if (this._activeTexturesCache[channel] === texture) {
  6817. return;
  6818. }
  6819. this._activeTexturesCache[channel] = texture;
  6820. var internalTexture = texture.getInternalTexture();
  6821. if (!alreadyActivated) {
  6822. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6823. }
  6824. if (internalTexture.isCube) {
  6825. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6826. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6827. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6828. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6829. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6830. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6831. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6832. }
  6833. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6834. }
  6835. else {
  6836. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6837. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6838. internalTexture._cachedWrapU = texture.wrapU;
  6839. switch (texture.wrapU) {
  6840. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6842. break;
  6843. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6845. break;
  6846. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6848. break;
  6849. }
  6850. }
  6851. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6852. internalTexture._cachedWrapV = texture.wrapV;
  6853. switch (texture.wrapV) {
  6854. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6855. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6856. break;
  6857. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6859. break;
  6860. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6862. break;
  6863. }
  6864. }
  6865. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6866. }
  6867. };
  6868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6869. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6870. var value = texture.anisotropicFilteringLevel;
  6871. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6872. value = 1;
  6873. }
  6874. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6875. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6876. texture._cachedAnisotropicFilteringLevel = value;
  6877. }
  6878. };
  6879. Engine.prototype.readPixels = function (x, y, width, height) {
  6880. var data = new Uint8Array(height * width * 4);
  6881. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6882. return data;
  6883. };
  6884. Engine.prototype.releaseInternalTexture = function (texture) {
  6885. if (!texture) {
  6886. return;
  6887. }
  6888. texture.references--;
  6889. // Final reference ?
  6890. if (texture.references === 0) {
  6891. var texturesCache = this.getLoadedTexturesCache();
  6892. var index = texturesCache.indexOf(texture);
  6893. if (index > -1) {
  6894. texturesCache.splice(index, 1);
  6895. }
  6896. this._releaseTexture(texture);
  6897. }
  6898. };
  6899. // Dispose
  6900. Engine.prototype.dispose = function () {
  6901. this.hideLoadingUI();
  6902. this.stopRenderLoop();
  6903. // Release scenes
  6904. while (this.scenes.length) {
  6905. this.scenes[0].dispose();
  6906. }
  6907. // Release audio engine
  6908. Engine.audioEngine.dispose();
  6909. // Release effects
  6910. for (var name in this._compiledEffects) {
  6911. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6912. }
  6913. // Unbind
  6914. for (var i in this._vertexAttribArrays) {
  6915. //making sure this is a string
  6916. var iAsNumber = +i;
  6917. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6918. continue;
  6919. }
  6920. this._gl.disableVertexAttribArray(iAsNumber);
  6921. }
  6922. this._gl = null;
  6923. // Events
  6924. window.removeEventListener("blur", this._onBlur);
  6925. window.removeEventListener("focus", this._onFocus);
  6926. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6927. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6928. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6929. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6930. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6931. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6932. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6933. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6934. };
  6935. // Loading screen
  6936. Engine.prototype.displayLoadingUI = function () {
  6937. this._loadingScreen.displayLoadingUI();
  6938. };
  6939. Engine.prototype.hideLoadingUI = function () {
  6940. this._loadingScreen.hideLoadingUI();
  6941. };
  6942. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6943. get: function () {
  6944. return this._loadingScreen;
  6945. },
  6946. set: function (loadingScreen) {
  6947. this._loadingScreen = loadingScreen;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6953. set: function (text) {
  6954. this._loadingScreen.loadingUIText = text;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6960. set: function (color) {
  6961. this._loadingScreen.loadingUIBackgroundColor = color;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. // FPS
  6967. Engine.prototype.getFps = function () {
  6968. return this.fps;
  6969. };
  6970. Engine.prototype.getDeltaTime = function () {
  6971. return this.deltaTime;
  6972. };
  6973. Engine.prototype._measureFps = function () {
  6974. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6975. var length = this.previousFramesDuration.length;
  6976. if (length >= 2) {
  6977. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6978. }
  6979. if (length >= this.fpsRange) {
  6980. if (length > this.fpsRange) {
  6981. this.previousFramesDuration.splice(0, 1);
  6982. length = this.previousFramesDuration.length;
  6983. }
  6984. var sum = 0;
  6985. for (var id = 0; id < length - 1; id++) {
  6986. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6987. }
  6988. this.fps = 1000.0 / (sum / (length - 1));
  6989. }
  6990. };
  6991. // Statics
  6992. Engine.isSupported = function () {
  6993. try {
  6994. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6995. if (navigator.isCocoonJS) {
  6996. return true;
  6997. }
  6998. var tempcanvas = document.createElement("canvas");
  6999. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7000. return gl != null && !!window.WebGLRenderingContext;
  7001. }
  7002. catch (e) {
  7003. return false;
  7004. }
  7005. };
  7006. // Const statics
  7007. Engine._ALPHA_DISABLE = 0;
  7008. Engine._ALPHA_ADD = 1;
  7009. Engine._ALPHA_COMBINE = 2;
  7010. Engine._ALPHA_SUBTRACT = 3;
  7011. Engine._ALPHA_MULTIPLY = 4;
  7012. Engine._ALPHA_MAXIMIZED = 5;
  7013. Engine._ALPHA_ONEONE = 6;
  7014. Engine._DELAYLOADSTATE_NONE = 0;
  7015. Engine._DELAYLOADSTATE_LOADED = 1;
  7016. Engine._DELAYLOADSTATE_LOADING = 2;
  7017. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7018. Engine._TEXTUREFORMAT_ALPHA = 0;
  7019. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7020. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7021. Engine._TEXTUREFORMAT_RGB = 4;
  7022. Engine._TEXTUREFORMAT_RGBA = 5;
  7023. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7024. Engine._TEXTURETYPE_FLOAT = 1;
  7025. // Updatable statics so stick with vars here
  7026. Engine.CollisionsEpsilon = 0.001;
  7027. Engine.CodeRepository = "src/";
  7028. Engine.ShadersRepository = "src/Shaders/";
  7029. return Engine;
  7030. })();
  7031. BABYLON.Engine = Engine;
  7032. })(BABYLON || (BABYLON = {}));
  7033. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7034. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7035. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7036. 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;
  7037. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7038. };
  7039. var BABYLON;
  7040. (function (BABYLON) {
  7041. /**
  7042. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7043. */
  7044. var Node = (function () {
  7045. /**
  7046. * @constructor
  7047. * @param {string} name - the name and id to be given to this node
  7048. * @param {BABYLON.Scene} the scene this node will be added to
  7049. */
  7050. function Node(name, scene) {
  7051. this.state = "";
  7052. this.animations = new Array();
  7053. this._ranges = {};
  7054. this._childrenFlag = -1;
  7055. this._isEnabled = true;
  7056. this._isReady = true;
  7057. this._currentRenderId = -1;
  7058. this._parentRenderId = -1;
  7059. this.name = name;
  7060. this.id = name;
  7061. this._scene = scene;
  7062. this._initCache();
  7063. }
  7064. Node.prototype.getScene = function () {
  7065. return this._scene;
  7066. };
  7067. Node.prototype.getEngine = function () {
  7068. return this._scene.getEngine();
  7069. };
  7070. // override it in derived class
  7071. Node.prototype.getWorldMatrix = function () {
  7072. return BABYLON.Matrix.Identity();
  7073. };
  7074. // override it in derived class if you add new variables to the cache
  7075. // and call the parent class method
  7076. Node.prototype._initCache = function () {
  7077. this._cache = {};
  7078. this._cache.parent = undefined;
  7079. };
  7080. Node.prototype.updateCache = function (force) {
  7081. if (!force && this.isSynchronized())
  7082. return;
  7083. this._cache.parent = this.parent;
  7084. this._updateCache();
  7085. };
  7086. // override it in derived class if you add new variables to the cache
  7087. // and call the parent class method if !ignoreParentClass
  7088. Node.prototype._updateCache = function (ignoreParentClass) {
  7089. };
  7090. // override it in derived class if you add new variables to the cache
  7091. Node.prototype._isSynchronized = function () {
  7092. return true;
  7093. };
  7094. Node.prototype._markSyncedWithParent = function () {
  7095. this._parentRenderId = this.parent._currentRenderId;
  7096. };
  7097. Node.prototype.isSynchronizedWithParent = function () {
  7098. if (!this.parent) {
  7099. return true;
  7100. }
  7101. if (this._parentRenderId !== this.parent._currentRenderId) {
  7102. return false;
  7103. }
  7104. return this.parent.isSynchronized();
  7105. };
  7106. Node.prototype.isSynchronized = function (updateCache) {
  7107. var check = this.hasNewParent();
  7108. check = check || !this.isSynchronizedWithParent();
  7109. check = check || !this._isSynchronized();
  7110. if (updateCache)
  7111. this.updateCache(true);
  7112. return !check;
  7113. };
  7114. Node.prototype.hasNewParent = function (update) {
  7115. if (this._cache.parent === this.parent)
  7116. return false;
  7117. if (update)
  7118. this._cache.parent = this.parent;
  7119. return true;
  7120. };
  7121. /**
  7122. * Is this node ready to be used/rendered
  7123. * @return {boolean} is it ready
  7124. */
  7125. Node.prototype.isReady = function () {
  7126. return this._isReady;
  7127. };
  7128. /**
  7129. * Is this node enabled.
  7130. * If the node has a parent and is enabled, the parent will be inspected as well.
  7131. * @return {boolean} whether this node (and its parent) is enabled.
  7132. * @see setEnabled
  7133. */
  7134. Node.prototype.isEnabled = function () {
  7135. if (!this._isEnabled) {
  7136. return false;
  7137. }
  7138. if (this.parent) {
  7139. return this.parent.isEnabled();
  7140. }
  7141. return true;
  7142. };
  7143. /**
  7144. * Set the enabled state of this node.
  7145. * @param {boolean} value - the new enabled state
  7146. * @see isEnabled
  7147. */
  7148. Node.prototype.setEnabled = function (value) {
  7149. this._isEnabled = value;
  7150. };
  7151. /**
  7152. * Is this node a descendant of the given node.
  7153. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7154. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7155. * @see parent
  7156. */
  7157. Node.prototype.isDescendantOf = function (ancestor) {
  7158. if (this.parent) {
  7159. if (this.parent === ancestor) {
  7160. return true;
  7161. }
  7162. return this.parent.isDescendantOf(ancestor);
  7163. }
  7164. return false;
  7165. };
  7166. /**
  7167. * Evaluate a list of nodes and determine if they should be considered as descendants considering the given criterias
  7168. * @param {BABYLON.Node[]} list the input array of nodes to evaluate
  7169. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7170. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7171. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7172. */
  7173. Node.prototype._getDescendants = function (list, results, directDecendantsOnly, predicate) {
  7174. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7175. for (var index = 0; index < list.length; index++) {
  7176. var item = list[index];
  7177. if (((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) && (!predicate || predicate(item))) {
  7178. results.push(item);
  7179. }
  7180. }
  7181. };
  7182. /**
  7183. * Will return all nodes that have this node as parent.
  7184. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7185. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7186. * @return {BABYLON.Node[]} all children nodes of all types.
  7187. */
  7188. Node.prototype.getDescendants = function (directDecendantsOnly, predicate) {
  7189. var results = [];
  7190. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7191. this._getDescendants(this._scene.lights, results, directDecendantsOnly, predicate);
  7192. this._getDescendants(this._scene.cameras, results, directDecendantsOnly, predicate);
  7193. return results;
  7194. };
  7195. /**
  7196. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7197. * @Deprecated, legacy support.
  7198. * use getDecendants instead.
  7199. */
  7200. Node.prototype.getChildren = function (predicate) {
  7201. return this.getDescendants(true, predicate);
  7202. };
  7203. /**
  7204. * Get all child-meshes of this node.
  7205. */
  7206. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7207. var results = [];
  7208. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7209. return results;
  7210. };
  7211. Node.prototype._setReady = function (state) {
  7212. if (state === this._isReady) {
  7213. return;
  7214. }
  7215. if (!state) {
  7216. this._isReady = false;
  7217. return;
  7218. }
  7219. this._isReady = true;
  7220. if (this.onReady) {
  7221. this.onReady(this);
  7222. }
  7223. };
  7224. Node.prototype.getAnimationByName = function (name) {
  7225. for (var i = 0; i < this.animations.length; i++) {
  7226. var animation = this.animations[i];
  7227. if (animation.name === name) {
  7228. return animation;
  7229. }
  7230. }
  7231. return null;
  7232. };
  7233. Node.prototype.createAnimationRange = function (name, from, to) {
  7234. // check name not already in use
  7235. if (!this._ranges[name]) {
  7236. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7237. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7238. if (this.animations[i]) {
  7239. this.animations[i].createRange(name, from, to);
  7240. }
  7241. }
  7242. }
  7243. };
  7244. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7245. if (deleteFrames === void 0) { deleteFrames = true; }
  7246. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7247. if (this.animations[i]) {
  7248. this.animations[i].deleteRange(name, deleteFrames);
  7249. }
  7250. }
  7251. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7252. };
  7253. Node.prototype.getAnimationRange = function (name) {
  7254. return this._ranges[name];
  7255. };
  7256. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7257. var range = this.getAnimationRange(name);
  7258. if (!range) {
  7259. return null;
  7260. }
  7261. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7262. };
  7263. Node.prototype.serializeAnimationRanges = function () {
  7264. var serializationRanges = [];
  7265. for (var name in this._ranges) {
  7266. var range = {};
  7267. range.name = name;
  7268. range.from = this._ranges[name].from;
  7269. range.to = this._ranges[name].to;
  7270. serializationRanges.push(range);
  7271. }
  7272. return serializationRanges;
  7273. };
  7274. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7275. if (parsedNode.ranges) {
  7276. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7277. var data = parsedNode.ranges[index];
  7278. node.createAnimationRange(data.name, data.from, data.to);
  7279. }
  7280. }
  7281. };
  7282. __decorate([
  7283. BABYLON.serialize()
  7284. ], Node.prototype, "name", void 0);
  7285. __decorate([
  7286. BABYLON.serialize()
  7287. ], Node.prototype, "id", void 0);
  7288. __decorate([
  7289. BABYLON.serialize()
  7290. ], Node.prototype, "uniqueId", void 0);
  7291. __decorate([
  7292. BABYLON.serialize()
  7293. ], Node.prototype, "state", void 0);
  7294. return Node;
  7295. })();
  7296. BABYLON.Node = Node;
  7297. })(BABYLON || (BABYLON = {}));
  7298. var BABYLON;
  7299. (function (BABYLON) {
  7300. var FilesInput = (function () {
  7301. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7302. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7303. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7304. this._engine = p_engine;
  7305. this._canvas = p_canvas;
  7306. this._currentScene = p_scene;
  7307. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7308. this._progressCallback = p_progressCallback;
  7309. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7310. this._textureLoadingCallback = p_textureLoadingCallback;
  7311. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7312. }
  7313. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7314. var _this = this;
  7315. if (p_elementToMonitor) {
  7316. this._elementToMonitor = p_elementToMonitor;
  7317. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7318. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7319. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7320. }
  7321. };
  7322. FilesInput.prototype.renderFunction = function () {
  7323. if (this._additionnalRenderLoopLogicCallback) {
  7324. this._additionnalRenderLoopLogicCallback();
  7325. }
  7326. if (this._currentScene) {
  7327. if (this._textureLoadingCallback) {
  7328. var remaining = this._currentScene.getWaitingItemsCount();
  7329. if (remaining > 0) {
  7330. this._textureLoadingCallback(remaining);
  7331. }
  7332. }
  7333. this._currentScene.render();
  7334. }
  7335. };
  7336. FilesInput.prototype.drag = function (e) {
  7337. e.stopPropagation();
  7338. e.preventDefault();
  7339. };
  7340. FilesInput.prototype.drop = function (eventDrop) {
  7341. eventDrop.stopPropagation();
  7342. eventDrop.preventDefault();
  7343. this.loadFiles(eventDrop);
  7344. };
  7345. FilesInput.prototype.loadFiles = function (event) {
  7346. if (this._startingProcessingFilesCallback)
  7347. this._startingProcessingFilesCallback();
  7348. // Handling data transfer via drag'n'drop
  7349. if (event && event.dataTransfer && event.dataTransfer.files) {
  7350. this._filesToLoad = event.dataTransfer.files;
  7351. }
  7352. // Handling files from input files
  7353. if (event && event.target && event.target.files) {
  7354. this._filesToLoad = event.target.files;
  7355. }
  7356. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7357. for (var i = 0; i < this._filesToLoad.length; i++) {
  7358. switch (this._filesToLoad[i].type) {
  7359. case "image/jpeg":
  7360. case "image/png":
  7361. case "image/bmp":
  7362. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7363. break;
  7364. case "image/targa":
  7365. case "image/vnd.ms-dds":
  7366. case "audio/wav":
  7367. case "audio/x-wav":
  7368. case "audio/mp3":
  7369. case "audio/mpeg":
  7370. case "audio/mpeg3":
  7371. case "audio/x-mpeg-3":
  7372. case "audio/ogg":
  7373. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7374. break;
  7375. default:
  7376. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7377. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7378. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7379. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7380. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7381. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7382. this._sceneFileToLoad = this._filesToLoad[i];
  7383. }
  7384. break;
  7385. }
  7386. }
  7387. this.reload();
  7388. }
  7389. };
  7390. FilesInput.prototype.reload = function () {
  7391. var _this = this;
  7392. var that = this;
  7393. // If a ".babylon" file has been provided
  7394. if (this._sceneFileToLoad) {
  7395. if (this._currentScene) {
  7396. if (BABYLON.Tools.errorsCount > 0) {
  7397. BABYLON.Tools.ClearLogCache();
  7398. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7399. }
  7400. this._engine.stopRenderLoop();
  7401. this._currentScene.dispose();
  7402. }
  7403. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7404. that._currentScene = newScene;
  7405. // Wait for textures and shaders to be ready
  7406. that._currentScene.executeWhenReady(function () {
  7407. // Attach camera to canvas inputs
  7408. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7409. that._currentScene.createDefaultCameraOrLight();
  7410. }
  7411. that._currentScene.activeCamera.attachControl(that._canvas);
  7412. if (that._sceneLoadedCallback) {
  7413. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7414. }
  7415. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7416. });
  7417. }, function (progress) {
  7418. if (_this._progressCallback) {
  7419. _this._progressCallback(progress);
  7420. }
  7421. });
  7422. }
  7423. else {
  7424. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7425. }
  7426. };
  7427. FilesInput.FilesTextures = new Array();
  7428. FilesInput.FilesToLoad = new Array();
  7429. return FilesInput;
  7430. })();
  7431. BABYLON.FilesInput = FilesInput;
  7432. })(BABYLON || (BABYLON = {}));
  7433. var BABYLON;
  7434. (function (BABYLON) {
  7435. var IntersectionInfo = (function () {
  7436. function IntersectionInfo(bu, bv, distance) {
  7437. this.bu = bu;
  7438. this.bv = bv;
  7439. this.distance = distance;
  7440. this.faceId = 0;
  7441. this.subMeshId = 0;
  7442. }
  7443. return IntersectionInfo;
  7444. })();
  7445. BABYLON.IntersectionInfo = IntersectionInfo;
  7446. var PickingInfo = (function () {
  7447. function PickingInfo() {
  7448. this.hit = false;
  7449. this.distance = 0;
  7450. this.pickedPoint = null;
  7451. this.pickedMesh = null;
  7452. this.bu = 0;
  7453. this.bv = 0;
  7454. this.faceId = -1;
  7455. this.subMeshId = 0;
  7456. this.pickedSprite = null;
  7457. }
  7458. // Methods
  7459. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7460. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7461. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7462. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7463. return null;
  7464. }
  7465. var indices = this.pickedMesh.getIndices();
  7466. var result;
  7467. if (useVerticesNormals) {
  7468. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7469. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7470. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7471. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7472. normal0 = normal0.scale(this.bu);
  7473. normal1 = normal1.scale(this.bv);
  7474. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7475. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7476. }
  7477. else {
  7478. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7479. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7480. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7481. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7482. var p1p2 = vertex1.subtract(vertex2);
  7483. var p3p2 = vertex3.subtract(vertex2);
  7484. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7485. }
  7486. if (useWorldCoordinates) {
  7487. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7488. }
  7489. return BABYLON.Vector3.Normalize(result);
  7490. };
  7491. PickingInfo.prototype.getTextureCoordinates = function () {
  7492. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7493. return null;
  7494. }
  7495. var indices = this.pickedMesh.getIndices();
  7496. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7497. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7498. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7499. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7500. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7501. uv1 = uv1.scale(this.bu);
  7502. uv2 = uv2.scale(this.bv);
  7503. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7504. };
  7505. return PickingInfo;
  7506. })();
  7507. BABYLON.PickingInfo = PickingInfo;
  7508. })(BABYLON || (BABYLON = {}));
  7509. var BABYLON;
  7510. (function (BABYLON) {
  7511. var BoundingSphere = (function () {
  7512. function BoundingSphere(minimum, maximum) {
  7513. this.minimum = minimum;
  7514. this.maximum = maximum;
  7515. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7516. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7517. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7518. this.radius = distance * 0.5;
  7519. this.centerWorld = BABYLON.Vector3.Zero();
  7520. this._update(BABYLON.Matrix.Identity());
  7521. }
  7522. // Methods
  7523. BoundingSphere.prototype._update = function (world) {
  7524. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7525. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7526. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7527. };
  7528. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7529. for (var i = 0; i < 6; i++) {
  7530. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7531. return false;
  7532. }
  7533. return true;
  7534. };
  7535. BoundingSphere.prototype.intersectsPoint = function (point) {
  7536. var x = this.centerWorld.x - point.x;
  7537. var y = this.centerWorld.y - point.y;
  7538. var z = this.centerWorld.z - point.z;
  7539. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7540. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7541. return false;
  7542. return true;
  7543. };
  7544. // Statics
  7545. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7546. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7547. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7548. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7549. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7550. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7551. return false;
  7552. return true;
  7553. };
  7554. return BoundingSphere;
  7555. })();
  7556. BABYLON.BoundingSphere = BoundingSphere;
  7557. })(BABYLON || (BABYLON = {}));
  7558. var BABYLON;
  7559. (function (BABYLON) {
  7560. var BoundingBox = (function () {
  7561. function BoundingBox(minimum, maximum) {
  7562. this.minimum = minimum;
  7563. this.maximum = maximum;
  7564. this.vectors = new Array();
  7565. this.vectorsWorld = new Array();
  7566. // Bounding vectors
  7567. this.vectors.push(this.minimum.clone());
  7568. this.vectors.push(this.maximum.clone());
  7569. this.vectors.push(this.minimum.clone());
  7570. this.vectors[2].x = this.maximum.x;
  7571. this.vectors.push(this.minimum.clone());
  7572. this.vectors[3].y = this.maximum.y;
  7573. this.vectors.push(this.minimum.clone());
  7574. this.vectors[4].z = this.maximum.z;
  7575. this.vectors.push(this.maximum.clone());
  7576. this.vectors[5].z = this.minimum.z;
  7577. this.vectors.push(this.maximum.clone());
  7578. this.vectors[6].x = this.minimum.x;
  7579. this.vectors.push(this.maximum.clone());
  7580. this.vectors[7].y = this.minimum.y;
  7581. // OBB
  7582. this.center = this.maximum.add(this.minimum).scale(0.5);
  7583. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7584. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7585. // World
  7586. for (var index = 0; index < this.vectors.length; index++) {
  7587. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7588. }
  7589. this.minimumWorld = BABYLON.Vector3.Zero();
  7590. this.maximumWorld = BABYLON.Vector3.Zero();
  7591. this._update(BABYLON.Matrix.Identity());
  7592. }
  7593. // Methods
  7594. BoundingBox.prototype.getWorldMatrix = function () {
  7595. return this._worldMatrix;
  7596. };
  7597. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7598. this._worldMatrix.copyFrom(matrix);
  7599. return this;
  7600. };
  7601. BoundingBox.prototype._update = function (world) {
  7602. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7603. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7604. for (var index = 0; index < this.vectors.length; index++) {
  7605. var v = this.vectorsWorld[index];
  7606. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7607. if (v.x < this.minimumWorld.x)
  7608. this.minimumWorld.x = v.x;
  7609. if (v.y < this.minimumWorld.y)
  7610. this.minimumWorld.y = v.y;
  7611. if (v.z < this.minimumWorld.z)
  7612. this.minimumWorld.z = v.z;
  7613. if (v.x > this.maximumWorld.x)
  7614. this.maximumWorld.x = v.x;
  7615. if (v.y > this.maximumWorld.y)
  7616. this.maximumWorld.y = v.y;
  7617. if (v.z > this.maximumWorld.z)
  7618. this.maximumWorld.z = v.z;
  7619. }
  7620. // OBB
  7621. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7622. this.center.scaleInPlace(0.5);
  7623. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7624. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7625. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7626. this._worldMatrix = world;
  7627. };
  7628. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7629. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7630. };
  7631. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7632. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7633. };
  7634. BoundingBox.prototype.intersectsPoint = function (point) {
  7635. var delta = -BABYLON.Epsilon;
  7636. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7637. return false;
  7638. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7639. return false;
  7640. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7641. return false;
  7642. return true;
  7643. };
  7644. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7645. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7646. };
  7647. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7648. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7649. return false;
  7650. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7651. return false;
  7652. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7653. return false;
  7654. return true;
  7655. };
  7656. // Statics
  7657. BoundingBox.Intersects = function (box0, box1) {
  7658. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7659. return false;
  7660. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7661. return false;
  7662. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7663. return false;
  7664. return true;
  7665. };
  7666. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7667. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7668. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7669. return (num <= (sphereRadius * sphereRadius));
  7670. };
  7671. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7672. for (var p = 0; p < 6; p++) {
  7673. for (var i = 0; i < 8; i++) {
  7674. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7675. return false;
  7676. }
  7677. }
  7678. }
  7679. return true;
  7680. };
  7681. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7682. for (var p = 0; p < 6; p++) {
  7683. var inCount = 8;
  7684. for (var i = 0; i < 8; i++) {
  7685. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7686. --inCount;
  7687. }
  7688. else {
  7689. break;
  7690. }
  7691. }
  7692. if (inCount === 0)
  7693. return false;
  7694. }
  7695. return true;
  7696. };
  7697. return BoundingBox;
  7698. })();
  7699. BABYLON.BoundingBox = BoundingBox;
  7700. })(BABYLON || (BABYLON = {}));
  7701. var BABYLON;
  7702. (function (BABYLON) {
  7703. var computeBoxExtents = function (axis, box) {
  7704. var p = BABYLON.Vector3.Dot(box.center, axis);
  7705. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7706. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7707. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7708. var r = r0 + r1 + r2;
  7709. return {
  7710. min: p - r,
  7711. max: p + r
  7712. };
  7713. };
  7714. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7715. var axisOverlap = function (axis, box0, box1) {
  7716. var result0 = computeBoxExtents(axis, box0);
  7717. var result1 = computeBoxExtents(axis, box1);
  7718. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7719. };
  7720. var BoundingInfo = (function () {
  7721. function BoundingInfo(minimum, maximum) {
  7722. this.minimum = minimum;
  7723. this.maximum = maximum;
  7724. this._isLocked = false;
  7725. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7726. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7727. }
  7728. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7729. get: function () {
  7730. return this._isLocked;
  7731. },
  7732. set: function (value) {
  7733. this._isLocked = value;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. // Methods
  7739. BoundingInfo.prototype.update = function (world) {
  7740. if (this._isLocked) {
  7741. return;
  7742. }
  7743. this.boundingBox._update(world);
  7744. this.boundingSphere._update(world);
  7745. };
  7746. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7747. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7748. return false;
  7749. return this.boundingBox.isInFrustum(frustumPlanes);
  7750. };
  7751. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7752. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7753. };
  7754. BoundingInfo.prototype._checkCollision = function (collider) {
  7755. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7756. };
  7757. BoundingInfo.prototype.intersectsPoint = function (point) {
  7758. if (!this.boundingSphere.centerWorld) {
  7759. return false;
  7760. }
  7761. if (!this.boundingSphere.intersectsPoint(point)) {
  7762. return false;
  7763. }
  7764. if (!this.boundingBox.intersectsPoint(point)) {
  7765. return false;
  7766. }
  7767. return true;
  7768. };
  7769. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7770. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7771. return false;
  7772. }
  7773. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7774. return false;
  7775. }
  7776. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7777. return false;
  7778. }
  7779. if (!precise) {
  7780. return true;
  7781. }
  7782. var box0 = this.boundingBox;
  7783. var box1 = boundingInfo.boundingBox;
  7784. if (!axisOverlap(box0.directions[0], box0, box1))
  7785. return false;
  7786. if (!axisOverlap(box0.directions[1], box0, box1))
  7787. return false;
  7788. if (!axisOverlap(box0.directions[2], box0, box1))
  7789. return false;
  7790. if (!axisOverlap(box1.directions[0], box0, box1))
  7791. return false;
  7792. if (!axisOverlap(box1.directions[1], box0, box1))
  7793. return false;
  7794. if (!axisOverlap(box1.directions[2], box0, box1))
  7795. return false;
  7796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7797. return false;
  7798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7799. return false;
  7800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7801. return false;
  7802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7803. return false;
  7804. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7805. return false;
  7806. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7807. return false;
  7808. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7809. return false;
  7810. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7811. return false;
  7812. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7813. return false;
  7814. return true;
  7815. };
  7816. return BoundingInfo;
  7817. })();
  7818. BABYLON.BoundingInfo = BoundingInfo;
  7819. })(BABYLON || (BABYLON = {}));
  7820. var BABYLON;
  7821. (function (BABYLON) {
  7822. var Ray = (function () {
  7823. function Ray(origin, direction, length) {
  7824. if (length === void 0) { length = Number.MAX_VALUE; }
  7825. this.origin = origin;
  7826. this.direction = direction;
  7827. this.length = length;
  7828. }
  7829. // Methods
  7830. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7831. var d = 0.0;
  7832. var maxValue = Number.MAX_VALUE;
  7833. var inv;
  7834. var min;
  7835. var max;
  7836. var temp;
  7837. if (Math.abs(this.direction.x) < 0.0000001) {
  7838. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7839. return false;
  7840. }
  7841. }
  7842. else {
  7843. inv = 1.0 / this.direction.x;
  7844. min = (minimum.x - this.origin.x) * inv;
  7845. max = (maximum.x - this.origin.x) * inv;
  7846. if (max === -Infinity) {
  7847. max = Infinity;
  7848. }
  7849. if (min > max) {
  7850. temp = min;
  7851. min = max;
  7852. max = temp;
  7853. }
  7854. d = Math.max(min, d);
  7855. maxValue = Math.min(max, maxValue);
  7856. if (d > maxValue) {
  7857. return false;
  7858. }
  7859. }
  7860. if (Math.abs(this.direction.y) < 0.0000001) {
  7861. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7862. return false;
  7863. }
  7864. }
  7865. else {
  7866. inv = 1.0 / this.direction.y;
  7867. min = (minimum.y - this.origin.y) * inv;
  7868. max = (maximum.y - this.origin.y) * inv;
  7869. if (max === -Infinity) {
  7870. max = Infinity;
  7871. }
  7872. if (min > max) {
  7873. temp = min;
  7874. min = max;
  7875. max = temp;
  7876. }
  7877. d = Math.max(min, d);
  7878. maxValue = Math.min(max, maxValue);
  7879. if (d > maxValue) {
  7880. return false;
  7881. }
  7882. }
  7883. if (Math.abs(this.direction.z) < 0.0000001) {
  7884. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7885. return false;
  7886. }
  7887. }
  7888. else {
  7889. inv = 1.0 / this.direction.z;
  7890. min = (minimum.z - this.origin.z) * inv;
  7891. max = (maximum.z - this.origin.z) * inv;
  7892. if (max === -Infinity) {
  7893. max = Infinity;
  7894. }
  7895. if (min > max) {
  7896. temp = min;
  7897. min = max;
  7898. max = temp;
  7899. }
  7900. d = Math.max(min, d);
  7901. maxValue = Math.min(max, maxValue);
  7902. if (d > maxValue) {
  7903. return false;
  7904. }
  7905. }
  7906. return true;
  7907. };
  7908. Ray.prototype.intersectsBox = function (box) {
  7909. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  7910. };
  7911. Ray.prototype.intersectsSphere = function (sphere) {
  7912. var x = sphere.center.x - this.origin.x;
  7913. var y = sphere.center.y - this.origin.y;
  7914. var z = sphere.center.z - this.origin.z;
  7915. var pyth = (x * x) + (y * y) + (z * z);
  7916. var rr = sphere.radius * sphere.radius;
  7917. if (pyth <= rr) {
  7918. return true;
  7919. }
  7920. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  7921. if (dot < 0.0) {
  7922. return false;
  7923. }
  7924. var temp = pyth - (dot * dot);
  7925. return temp <= rr;
  7926. };
  7927. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  7928. if (!this._edge1) {
  7929. this._edge1 = BABYLON.Vector3.Zero();
  7930. this._edge2 = BABYLON.Vector3.Zero();
  7931. this._pvec = BABYLON.Vector3.Zero();
  7932. this._tvec = BABYLON.Vector3.Zero();
  7933. this._qvec = BABYLON.Vector3.Zero();
  7934. }
  7935. vertex1.subtractToRef(vertex0, this._edge1);
  7936. vertex2.subtractToRef(vertex0, this._edge2);
  7937. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  7938. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  7939. if (det === 0) {
  7940. return null;
  7941. }
  7942. var invdet = 1 / det;
  7943. this.origin.subtractToRef(vertex0, this._tvec);
  7944. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  7945. if (bu < 0 || bu > 1.0) {
  7946. return null;
  7947. }
  7948. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  7949. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  7950. if (bv < 0 || bu + bv > 1.0) {
  7951. return null;
  7952. }
  7953. //check if the distance is longer than the predefined length.
  7954. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  7955. if (distance > this.length) {
  7956. return null;
  7957. }
  7958. return new BABYLON.IntersectionInfo(bu, bv, distance);
  7959. };
  7960. // Statics
  7961. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  7962. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  7963. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  7964. var direction = end.subtract(start);
  7965. direction.normalize();
  7966. return new Ray(start, direction);
  7967. };
  7968. /**
  7969. * 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
  7970. * transformed to the given world matrix.
  7971. * @param origin The origin point
  7972. * @param end The end point
  7973. * @param world a matrix to transform the ray to. Default is the identity matrix.
  7974. */
  7975. Ray.CreateNewFromTo = function (origin, end, world) {
  7976. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  7977. var direction = end.subtract(origin);
  7978. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  7979. direction.normalize();
  7980. return Ray.Transform(new Ray(origin, direction, length), world);
  7981. };
  7982. Ray.Transform = function (ray, matrix) {
  7983. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  7984. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  7985. return new Ray(newOrigin, newDirection, ray.length);
  7986. };
  7987. return Ray;
  7988. })();
  7989. BABYLON.Ray = Ray;
  7990. })(BABYLON || (BABYLON = {}));
  7991. var BABYLON;
  7992. (function (BABYLON) {
  7993. var AbstractMesh = (function (_super) {
  7994. __extends(AbstractMesh, _super);
  7995. // Constructor
  7996. function AbstractMesh(name, scene) {
  7997. var _this = this;
  7998. _super.call(this, name, scene);
  7999. // Properties
  8000. this.definedFacingForward = true; // orientation for POV movement & rotation
  8001. this.position = new BABYLON.Vector3(0, 0, 0);
  8002. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8003. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8004. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8005. this.visibility = 1.0;
  8006. this.alphaIndex = Number.MAX_VALUE;
  8007. this.infiniteDistance = false;
  8008. this.isVisible = true;
  8009. this.isPickable = true;
  8010. this.showBoundingBox = false;
  8011. this.showSubMeshesBoundingBox = false;
  8012. this.onDispose = null;
  8013. this.isBlocker = false;
  8014. this.renderingGroupId = 0;
  8015. this.receiveShadows = false;
  8016. this.renderOutline = false;
  8017. this.outlineColor = BABYLON.Color3.Red();
  8018. this.outlineWidth = 0.02;
  8019. this.renderOverlay = false;
  8020. this.overlayColor = BABYLON.Color3.Red();
  8021. this.overlayAlpha = 0.5;
  8022. this.hasVertexAlpha = false;
  8023. this.useVertexColors = true;
  8024. this.applyFog = true;
  8025. this.computeBonesUsingShaders = true;
  8026. this.scalingDeterminant = 1;
  8027. this.numBoneInfluencers = 4;
  8028. this.useOctreeForRenderingSelection = true;
  8029. this.useOctreeForPicking = true;
  8030. this.useOctreeForCollisions = true;
  8031. this.layerMask = 0x0FFFFFFF;
  8032. this.alwaysSelectAsActiveMesh = false;
  8033. // Collisions
  8034. this._checkCollisions = false;
  8035. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8036. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8037. this._collider = new BABYLON.Collider();
  8038. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8039. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8040. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8041. // Edges
  8042. this.edgesWidth = 1;
  8043. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8044. // Cache
  8045. this._localWorld = BABYLON.Matrix.Zero();
  8046. this._worldMatrix = BABYLON.Matrix.Zero();
  8047. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8048. this._absolutePosition = BABYLON.Vector3.Zero();
  8049. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8050. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8051. this._isDirty = false;
  8052. this._pivotMatrix = BABYLON.Matrix.Identity();
  8053. this._isDisposed = false;
  8054. this._renderId = 0;
  8055. this._intersectionsInProgress = new Array();
  8056. this._onAfterWorldMatrixUpdate = new Array();
  8057. this._isWorldMatrixFrozen = false;
  8058. this._unIndexed = false;
  8059. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8060. if (collidedMesh === void 0) { collidedMesh = null; }
  8061. //TODO move this to the collision coordinator!
  8062. if (_this.getScene().workerCollisions)
  8063. newPosition.multiplyInPlace(_this._collider.radius);
  8064. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8065. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8066. _this.position.addInPlace(_this._diffPositionForCollisions);
  8067. }
  8068. if (_this.onCollide && collidedMesh) {
  8069. _this.onCollide(collidedMesh);
  8070. }
  8071. if (_this.onCollisionPositionChange) {
  8072. _this.onCollisionPositionChange(_this.position);
  8073. }
  8074. };
  8075. scene.addMesh(this);
  8076. }
  8077. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8078. get: function () {
  8079. return AbstractMesh._BILLBOARDMODE_NONE;
  8080. },
  8081. enumerable: true,
  8082. configurable: true
  8083. });
  8084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8085. get: function () {
  8086. return AbstractMesh._BILLBOARDMODE_X;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8092. get: function () {
  8093. return AbstractMesh._BILLBOARDMODE_Y;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8099. get: function () {
  8100. return AbstractMesh._BILLBOARDMODE_Z;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8106. get: function () {
  8107. return AbstractMesh._BILLBOARDMODE_ALL;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8113. get: function () {
  8114. return this._skeleton;
  8115. },
  8116. set: function (value) {
  8117. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8118. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8119. }
  8120. if (value && value.needInitialSkinMatrix) {
  8121. value._registerMeshWithPoseMatrix(this);
  8122. }
  8123. this._skeleton = value;
  8124. if (!this._skeleton) {
  8125. this._bonesTransformMatrices = null;
  8126. }
  8127. },
  8128. enumerable: true,
  8129. configurable: true
  8130. });
  8131. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8132. /**
  8133. * Getting the rotation object.
  8134. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8135. */
  8136. get: function () {
  8137. return this._rotation;
  8138. },
  8139. set: function (newRotation) {
  8140. this._rotation = newRotation;
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8146. get: function () {
  8147. return this._scaling;
  8148. },
  8149. set: function (newScaling) {
  8150. this._scaling = newScaling;
  8151. if (this.physicsImpostor) {
  8152. this.physicsImpostor.forceUpdate();
  8153. }
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8159. get: function () {
  8160. return this._rotationQuaternion;
  8161. },
  8162. set: function (quaternion) {
  8163. this._rotationQuaternion = quaternion;
  8164. //reset the rotation vector.
  8165. if (quaternion && this.rotation.length()) {
  8166. this.rotation.copyFromFloats(0, 0, 0);
  8167. }
  8168. },
  8169. enumerable: true,
  8170. configurable: true
  8171. });
  8172. // Methods
  8173. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8174. this._poseMatrix.copyFrom(matrix);
  8175. };
  8176. AbstractMesh.prototype.getPoseMatrix = function () {
  8177. return this._poseMatrix;
  8178. };
  8179. AbstractMesh.prototype.disableEdgesRendering = function () {
  8180. if (this._edgesRenderer !== undefined) {
  8181. this._edgesRenderer.dispose();
  8182. this._edgesRenderer = undefined;
  8183. }
  8184. };
  8185. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8186. if (epsilon === void 0) { epsilon = 0.95; }
  8187. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8188. this.disableEdgesRendering();
  8189. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8190. };
  8191. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8192. get: function () {
  8193. return false;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. AbstractMesh.prototype.getLOD = function (camera) {
  8199. return this;
  8200. };
  8201. AbstractMesh.prototype.getTotalVertices = function () {
  8202. return 0;
  8203. };
  8204. AbstractMesh.prototype.getIndices = function () {
  8205. return null;
  8206. };
  8207. AbstractMesh.prototype.getVerticesData = function (kind) {
  8208. return null;
  8209. };
  8210. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8211. return false;
  8212. };
  8213. AbstractMesh.prototype.getBoundingInfo = function () {
  8214. if (this._masterMesh) {
  8215. return this._masterMesh.getBoundingInfo();
  8216. }
  8217. if (!this._boundingInfo) {
  8218. this._updateBoundingInfo();
  8219. }
  8220. return this._boundingInfo;
  8221. };
  8222. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8223. get: function () {
  8224. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. AbstractMesh.prototype._preActivate = function () {
  8230. };
  8231. AbstractMesh.prototype._activate = function (renderId) {
  8232. this._renderId = renderId;
  8233. };
  8234. AbstractMesh.prototype.getWorldMatrix = function () {
  8235. if (this._masterMesh) {
  8236. return this._masterMesh.getWorldMatrix();
  8237. }
  8238. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8239. this.computeWorldMatrix();
  8240. }
  8241. return this._worldMatrix;
  8242. };
  8243. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8244. get: function () {
  8245. return this._worldMatrix;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8251. get: function () {
  8252. return this._absolutePosition;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8258. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8259. this.computeWorldMatrix(true);
  8260. this._isWorldMatrixFrozen = true;
  8261. };
  8262. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8263. this._isWorldMatrixFrozen = false;
  8264. this.computeWorldMatrix(true);
  8265. };
  8266. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8267. get: function () {
  8268. return this._isWorldMatrixFrozen;
  8269. },
  8270. enumerable: true,
  8271. configurable: true
  8272. });
  8273. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8274. axis.normalize();
  8275. if (!this.rotationQuaternion) {
  8276. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8277. this.rotation = BABYLON.Vector3.Zero();
  8278. }
  8279. var rotationQuaternion;
  8280. if (!space || space === BABYLON.Space.LOCAL) {
  8281. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8282. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8283. }
  8284. else {
  8285. if (this.parent) {
  8286. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8287. invertParentWorldMatrix.invert();
  8288. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8289. }
  8290. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8291. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8292. }
  8293. };
  8294. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8295. var displacementVector = axis.scale(distance);
  8296. if (!space || space === BABYLON.Space.LOCAL) {
  8297. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8298. this.setPositionWithLocalVector(tempV3);
  8299. }
  8300. else {
  8301. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8302. }
  8303. };
  8304. AbstractMesh.prototype.getAbsolutePosition = function () {
  8305. this.computeWorldMatrix();
  8306. return this._absolutePosition;
  8307. };
  8308. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8309. if (!absolutePosition) {
  8310. return;
  8311. }
  8312. var absolutePositionX;
  8313. var absolutePositionY;
  8314. var absolutePositionZ;
  8315. if (absolutePosition.x === undefined) {
  8316. if (arguments.length < 3) {
  8317. return;
  8318. }
  8319. absolutePositionX = arguments[0];
  8320. absolutePositionY = arguments[1];
  8321. absolutePositionZ = arguments[2];
  8322. }
  8323. else {
  8324. absolutePositionX = absolutePosition.x;
  8325. absolutePositionY = absolutePosition.y;
  8326. absolutePositionZ = absolutePosition.z;
  8327. }
  8328. if (this.parent) {
  8329. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8330. invertParentWorldMatrix.invert();
  8331. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8332. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8333. }
  8334. else {
  8335. this.position.x = absolutePositionX;
  8336. this.position.y = absolutePositionY;
  8337. this.position.z = absolutePositionZ;
  8338. }
  8339. };
  8340. // ================================== Point of View Movement =================================
  8341. /**
  8342. * Perform relative position change from the point of view of behind the front of the mesh.
  8343. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8344. * Supports definition of mesh facing forward or backward.
  8345. * @param {number} amountRight
  8346. * @param {number} amountUp
  8347. * @param {number} amountForward
  8348. */
  8349. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8350. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8351. };
  8352. /**
  8353. * Calculate relative position change from the point of view of behind the front of the mesh.
  8354. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8355. * Supports definition of mesh facing forward or backward.
  8356. * @param {number} amountRight
  8357. * @param {number} amountUp
  8358. * @param {number} amountForward
  8359. */
  8360. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8361. var rotMatrix = new BABYLON.Matrix();
  8362. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8363. rotQuaternion.toRotationMatrix(rotMatrix);
  8364. var translationDelta = BABYLON.Vector3.Zero();
  8365. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8367. return translationDelta;
  8368. };
  8369. // ================================== Point of View Rotation =================================
  8370. /**
  8371. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8372. * Supports definition of mesh facing forward or backward.
  8373. * @param {number} flipBack
  8374. * @param {number} twirlClockwise
  8375. * @param {number} tiltRight
  8376. */
  8377. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8378. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8379. };
  8380. /**
  8381. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8382. * Supports definition of mesh facing forward or backward.
  8383. * @param {number} flipBack
  8384. * @param {number} twirlClockwise
  8385. * @param {number} tiltRight
  8386. */
  8387. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8388. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8389. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8390. };
  8391. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8392. this._pivotMatrix = matrix;
  8393. this._cache.pivotMatrixUpdated = true;
  8394. };
  8395. AbstractMesh.prototype.getPivotMatrix = function () {
  8396. return this._pivotMatrix;
  8397. };
  8398. AbstractMesh.prototype._isSynchronized = function () {
  8399. if (this._isDirty) {
  8400. return false;
  8401. }
  8402. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8403. return false;
  8404. if (this._cache.pivotMatrixUpdated) {
  8405. return false;
  8406. }
  8407. if (this.infiniteDistance) {
  8408. return false;
  8409. }
  8410. if (!this._cache.position.equals(this.position))
  8411. return false;
  8412. if (!this._cache.rotation.equals(this.rotation))
  8413. return false;
  8414. if (this.rotationQuaternion) {
  8415. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8416. return false;
  8417. }
  8418. if (!this._cache.scaling.equals(this.scaling))
  8419. return false;
  8420. return true;
  8421. };
  8422. AbstractMesh.prototype._initCache = function () {
  8423. _super.prototype._initCache.call(this);
  8424. this._cache.localMatrixUpdated = false;
  8425. this._cache.position = BABYLON.Vector3.Zero();
  8426. this._cache.scaling = BABYLON.Vector3.Zero();
  8427. this._cache.rotation = BABYLON.Vector3.Zero();
  8428. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8429. this._cache.billboardMode = -1;
  8430. };
  8431. AbstractMesh.prototype.markAsDirty = function (property) {
  8432. if (property === "rotation") {
  8433. this.rotationQuaternion = null;
  8434. }
  8435. this._currentRenderId = Number.MAX_VALUE;
  8436. this._isDirty = true;
  8437. };
  8438. AbstractMesh.prototype._updateBoundingInfo = function () {
  8439. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8440. this._boundingInfo.update(this.worldMatrixFromCache);
  8441. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8442. };
  8443. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8444. if (!this.subMeshes) {
  8445. return;
  8446. }
  8447. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8448. var subMesh = this.subMeshes[subIndex];
  8449. if (!subMesh.IsGlobal) {
  8450. subMesh.updateBoundingInfo(matrix);
  8451. }
  8452. }
  8453. };
  8454. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8455. if (this._isWorldMatrixFrozen) {
  8456. return this._worldMatrix;
  8457. }
  8458. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8459. this._currentRenderId = this.getScene().getRenderId();
  8460. return this._worldMatrix;
  8461. }
  8462. this._cache.position.copyFrom(this.position);
  8463. this._cache.scaling.copyFrom(this.scaling);
  8464. this._cache.pivotMatrixUpdated = false;
  8465. this._cache.billboardMode = this.billboardMode;
  8466. this._currentRenderId = this.getScene().getRenderId();
  8467. this._isDirty = false;
  8468. // Scaling
  8469. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8470. // Rotation
  8471. //rotate, if quaternion is set and rotation was used
  8472. if (this.rotationQuaternion) {
  8473. var len = this.rotation.length();
  8474. if (len) {
  8475. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8476. this.rotation.copyFromFloats(0, 0, 0);
  8477. }
  8478. }
  8479. if (this.rotationQuaternion) {
  8480. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8481. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8482. }
  8483. else {
  8484. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8485. this._cache.rotation.copyFrom(this.rotation);
  8486. }
  8487. // Translation
  8488. if (this.infiniteDistance && !this.parent) {
  8489. var camera = this.getScene().activeCamera;
  8490. if (camera) {
  8491. var cameraWorldMatrix = camera.getWorldMatrix();
  8492. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8493. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8494. }
  8495. }
  8496. else {
  8497. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8498. }
  8499. // Composing transformations
  8500. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8501. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8502. // Billboarding
  8503. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8504. var localPosition = this.position.clone();
  8505. var zero = this.getScene().activeCamera.globalPosition.clone();
  8506. if (this.parent && this.parent.position) {
  8507. localPosition.addInPlace(this.parent.position);
  8508. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8509. }
  8510. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8511. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8512. zero.x = localPosition.x + BABYLON.Epsilon;
  8513. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8514. zero.y = localPosition.y + BABYLON.Epsilon;
  8515. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8516. zero.z = localPosition.z + BABYLON.Epsilon;
  8517. }
  8518. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8519. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8520. BABYLON.Tmp.Matrix[3].invert();
  8521. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8522. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8523. }
  8524. // Local world
  8525. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8526. // Parent
  8527. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8528. this._markSyncedWithParent();
  8529. if (this._meshToBoneReferal) {
  8530. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8531. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8532. }
  8533. else {
  8534. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8535. }
  8536. }
  8537. else {
  8538. this._worldMatrix.copyFrom(this._localWorld);
  8539. }
  8540. // Bounding info
  8541. this._updateBoundingInfo();
  8542. // Absolute position
  8543. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8544. // Callbacks
  8545. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8546. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8547. }
  8548. if (!this._poseMatrix) {
  8549. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8550. }
  8551. return this._worldMatrix;
  8552. };
  8553. /**
  8554. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8555. * @param func: callback function to add
  8556. */
  8557. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8558. this._onAfterWorldMatrixUpdate.push(func);
  8559. };
  8560. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8561. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8562. if (index > -1) {
  8563. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8564. }
  8565. };
  8566. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8567. this.computeWorldMatrix();
  8568. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8569. };
  8570. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8571. this.computeWorldMatrix();
  8572. var invLocalWorldMatrix = this._localWorld.clone();
  8573. invLocalWorldMatrix.invert();
  8574. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8575. };
  8576. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8577. this.computeWorldMatrix(true);
  8578. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8579. };
  8580. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8581. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8582. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8583. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8584. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8585. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8586. /// <returns>Mesh oriented towards targetMesh</returns>
  8587. yawCor = yawCor || 0; // default to zero if undefined
  8588. pitchCor = pitchCor || 0;
  8589. rollCor = rollCor || 0;
  8590. var dv = targetPoint.subtract(this.position);
  8591. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8592. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8593. var pitch = Math.atan2(dv.y, len);
  8594. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8595. };
  8596. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8597. this._meshToBoneReferal = affectedMesh;
  8598. this.parent = bone;
  8599. if (bone.getWorldMatrix().determinant() < 0) {
  8600. this.scalingDeterminant *= -1;
  8601. }
  8602. };
  8603. AbstractMesh.prototype.detachFromBone = function () {
  8604. if (this.parent.getWorldMatrix().determinant() < 0) {
  8605. this.scalingDeterminant *= -1;
  8606. }
  8607. this._meshToBoneReferal = null;
  8608. this.parent = null;
  8609. };
  8610. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8611. return this._boundingInfo.isInFrustum(frustumPlanes);
  8612. };
  8613. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8614. if (!camera) {
  8615. camera = this.getScene().activeCamera;
  8616. }
  8617. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8618. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8619. return false;
  8620. }
  8621. return true;
  8622. };
  8623. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8624. if (!this._boundingInfo || !mesh._boundingInfo) {
  8625. return false;
  8626. }
  8627. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8628. };
  8629. AbstractMesh.prototype.intersectsPoint = function (point) {
  8630. if (!this._boundingInfo) {
  8631. return false;
  8632. }
  8633. return this._boundingInfo.intersectsPoint(point);
  8634. };
  8635. // Physics
  8636. /**
  8637. * @Deprecated. Use new PhysicsImpostor instead.
  8638. * */
  8639. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8640. //legacy support
  8641. if (impostor.impostor) {
  8642. options = impostor;
  8643. impostor = impostor.impostor;
  8644. }
  8645. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8646. return this.physicsImpostor.physicsBody;
  8647. };
  8648. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8649. return this.physicsImpostor;
  8650. };
  8651. /**
  8652. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8653. */
  8654. AbstractMesh.prototype.getPhysicsMass = function () {
  8655. return this.physicsImpostor.getParam("mass");
  8656. };
  8657. /**
  8658. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8659. */
  8660. AbstractMesh.prototype.getPhysicsFriction = function () {
  8661. return this.physicsImpostor.getParam("friction");
  8662. };
  8663. /**
  8664. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8665. */
  8666. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8667. return this.physicsImpostor.getParam("resitution");
  8668. };
  8669. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8670. if (!camera) {
  8671. camera = this.getScene().activeCamera;
  8672. }
  8673. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8674. };
  8675. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8676. if (!camera) {
  8677. camera = this.getScene().activeCamera;
  8678. }
  8679. return this.absolutePosition.subtract(camera.position).length();
  8680. };
  8681. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8682. if (!this.physicsImpostor) {
  8683. return;
  8684. }
  8685. this.physicsImpostor.applyImpulse(force, contactPoint);
  8686. };
  8687. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8688. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8689. return;
  8690. }
  8691. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8692. mainPivot: pivot1,
  8693. connectedPivot: pivot2,
  8694. nativeParams: options
  8695. });
  8696. };
  8697. /**
  8698. * @Deprecated
  8699. */
  8700. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8701. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8702. this.updatePhysicsBody();
  8703. };
  8704. /**
  8705. * @Deprecated
  8706. * Calling this function is not needed anymore.
  8707. * The physics engine takes care of transofmration automatically.
  8708. */
  8709. AbstractMesh.prototype.updatePhysicsBody = function () {
  8710. //Unneeded
  8711. };
  8712. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8713. // Collisions
  8714. get: function () {
  8715. return this._checkCollisions;
  8716. },
  8717. set: function (collisionEnabled) {
  8718. this._checkCollisions = collisionEnabled;
  8719. if (this.getScene().workerCollisions) {
  8720. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8721. }
  8722. },
  8723. enumerable: true,
  8724. configurable: true
  8725. });
  8726. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8727. var globalPosition = this.getAbsolutePosition();
  8728. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8729. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8730. this._collider.radius = this.ellipsoid;
  8731. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8732. };
  8733. // Submeshes octree
  8734. /**
  8735. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8736. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8737. */
  8738. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8739. if (maxCapacity === void 0) { maxCapacity = 64; }
  8740. if (maxDepth === void 0) { maxDepth = 2; }
  8741. if (!this._submeshesOctree) {
  8742. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8743. }
  8744. this.computeWorldMatrix(true);
  8745. // Update octree
  8746. var bbox = this.getBoundingInfo().boundingBox;
  8747. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8748. return this._submeshesOctree;
  8749. };
  8750. // Collisions
  8751. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8752. this._generatePointsArray();
  8753. // Transformation
  8754. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8755. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8756. subMesh._lastColliderWorldVertices = [];
  8757. subMesh._trianglePlanes = [];
  8758. var start = subMesh.verticesStart;
  8759. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8760. for (var i = start; i < end; i++) {
  8761. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8762. }
  8763. }
  8764. // Collide
  8765. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8766. if (collider.collisionFound) {
  8767. collider.collidedMesh = this;
  8768. }
  8769. };
  8770. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8771. var subMeshes;
  8772. var len;
  8773. // Octrees
  8774. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8775. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8776. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8777. len = intersections.length;
  8778. subMeshes = intersections.data;
  8779. }
  8780. else {
  8781. subMeshes = this.subMeshes;
  8782. len = subMeshes.length;
  8783. }
  8784. for (var index = 0; index < len; index++) {
  8785. var subMesh = subMeshes[index];
  8786. // Bounding test
  8787. if (len > 1 && !subMesh._checkCollision(collider))
  8788. continue;
  8789. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8790. }
  8791. };
  8792. AbstractMesh.prototype._checkCollision = function (collider) {
  8793. // Bounding box test
  8794. if (!this._boundingInfo._checkCollision(collider))
  8795. return;
  8796. // Transformation matrix
  8797. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8798. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8799. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8800. };
  8801. // Picking
  8802. AbstractMesh.prototype._generatePointsArray = function () {
  8803. return false;
  8804. };
  8805. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8806. var pickingInfo = new BABYLON.PickingInfo();
  8807. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8808. return pickingInfo;
  8809. }
  8810. if (!this._generatePointsArray()) {
  8811. return pickingInfo;
  8812. }
  8813. var intersectInfo = null;
  8814. // Octrees
  8815. var subMeshes;
  8816. var len;
  8817. if (this._submeshesOctree && this.useOctreeForPicking) {
  8818. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8819. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8820. len = intersections.length;
  8821. subMeshes = intersections.data;
  8822. }
  8823. else {
  8824. subMeshes = this.subMeshes;
  8825. len = subMeshes.length;
  8826. }
  8827. for (var index = 0; index < len; index++) {
  8828. var subMesh = subMeshes[index];
  8829. // Bounding test
  8830. if (len > 1 && !subMesh.canIntersects(ray))
  8831. continue;
  8832. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8833. if (currentIntersectInfo) {
  8834. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8835. intersectInfo = currentIntersectInfo;
  8836. intersectInfo.subMeshId = index;
  8837. if (fastCheck) {
  8838. break;
  8839. }
  8840. }
  8841. }
  8842. }
  8843. if (intersectInfo) {
  8844. // Get picked point
  8845. var world = this.getWorldMatrix();
  8846. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8847. var direction = ray.direction.clone();
  8848. direction = direction.scale(intersectInfo.distance);
  8849. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8850. var pickedPoint = worldOrigin.add(worldDirection);
  8851. // Return result
  8852. pickingInfo.hit = true;
  8853. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8854. pickingInfo.pickedPoint = pickedPoint;
  8855. pickingInfo.pickedMesh = this;
  8856. pickingInfo.bu = intersectInfo.bu;
  8857. pickingInfo.bv = intersectInfo.bv;
  8858. pickingInfo.faceId = intersectInfo.faceId;
  8859. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8860. return pickingInfo;
  8861. }
  8862. return pickingInfo;
  8863. };
  8864. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8865. return null;
  8866. };
  8867. AbstractMesh.prototype.releaseSubMeshes = function () {
  8868. if (this.subMeshes) {
  8869. while (this.subMeshes.length) {
  8870. this.subMeshes[0].dispose();
  8871. }
  8872. }
  8873. else {
  8874. this.subMeshes = new Array();
  8875. }
  8876. };
  8877. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8878. var index;
  8879. // Action manager
  8880. if (this.actionManager) {
  8881. this.actionManager.dispose();
  8882. this.actionManager = null;
  8883. }
  8884. // Skeleton
  8885. this.skeleton = null;
  8886. // Animations
  8887. this.getScene().stopAnimation(this);
  8888. // Physics
  8889. if (this.physicsImpostor) {
  8890. this.physicsImpostor.dispose(!doNotRecurse);
  8891. }
  8892. // Intersections in progress
  8893. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8894. var other = this._intersectionsInProgress[index];
  8895. var pos = other._intersectionsInProgress.indexOf(this);
  8896. other._intersectionsInProgress.splice(pos, 1);
  8897. }
  8898. this._intersectionsInProgress = [];
  8899. // Edges
  8900. if (this._edgesRenderer) {
  8901. this._edgesRenderer.dispose();
  8902. this._edgesRenderer = null;
  8903. }
  8904. // SubMeshes
  8905. this.releaseSubMeshes();
  8906. // Remove from scene
  8907. this.getScene().removeMesh(this);
  8908. if (!doNotRecurse) {
  8909. // Particles
  8910. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8911. if (this.getScene().particleSystems[index].emitter === this) {
  8912. this.getScene().particleSystems[index].dispose();
  8913. index--;
  8914. }
  8915. }
  8916. // Children
  8917. var objects = this.getScene().meshes.slice(0);
  8918. for (index = 0; index < objects.length; index++) {
  8919. if (objects[index].parent === this) {
  8920. objects[index].dispose();
  8921. }
  8922. }
  8923. }
  8924. else {
  8925. for (index = 0; index < this.getScene().meshes.length; index++) {
  8926. var obj = this.getScene().meshes[index];
  8927. if (obj.parent === this) {
  8928. obj.parent = null;
  8929. obj.computeWorldMatrix(true);
  8930. }
  8931. }
  8932. }
  8933. this._onAfterWorldMatrixUpdate = [];
  8934. this._isDisposed = true;
  8935. // Callback
  8936. if (this.onDispose) {
  8937. this.onDispose();
  8938. }
  8939. };
  8940. // Statics
  8941. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8942. AbstractMesh._BILLBOARDMODE_X = 1;
  8943. AbstractMesh._BILLBOARDMODE_Y = 2;
  8944. AbstractMesh._BILLBOARDMODE_Z = 4;
  8945. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8946. return AbstractMesh;
  8947. })(BABYLON.Node);
  8948. BABYLON.AbstractMesh = AbstractMesh;
  8949. })(BABYLON || (BABYLON = {}));
  8950. var BABYLON;
  8951. (function (BABYLON) {
  8952. var Light = (function (_super) {
  8953. __extends(Light, _super);
  8954. function Light(name, scene) {
  8955. _super.call(this, name, scene);
  8956. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8957. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8958. this.intensity = 1.0;
  8959. this.range = Number.MAX_VALUE;
  8960. this.includeOnlyWithLayerMask = 0;
  8961. this.includedOnlyMeshes = new Array();
  8962. this.excludedMeshes = new Array();
  8963. this.excludeWithLayerMask = 0;
  8964. // PBR Properties.
  8965. this.radius = 0.00001;
  8966. this._excludedMeshesIds = new Array();
  8967. this._includedOnlyMeshesIds = new Array();
  8968. scene.addLight(this);
  8969. }
  8970. Light.prototype.getShadowGenerator = function () {
  8971. return this._shadowGenerator;
  8972. };
  8973. Light.prototype.getAbsolutePosition = function () {
  8974. return BABYLON.Vector3.Zero();
  8975. };
  8976. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8977. };
  8978. Light.prototype._getWorldMatrix = function () {
  8979. return BABYLON.Matrix.Identity();
  8980. };
  8981. Light.prototype.canAffectMesh = function (mesh) {
  8982. if (!mesh) {
  8983. return true;
  8984. }
  8985. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8986. return false;
  8987. }
  8988. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8989. return false;
  8990. }
  8991. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8992. return false;
  8993. }
  8994. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8995. return false;
  8996. }
  8997. return true;
  8998. };
  8999. Light.prototype.getWorldMatrix = function () {
  9000. this._currentRenderId = this.getScene().getRenderId();
  9001. var worldMatrix = this._getWorldMatrix();
  9002. if (this.parent && this.parent.getWorldMatrix) {
  9003. if (!this._parentedWorldMatrix) {
  9004. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9005. }
  9006. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9007. this._markSyncedWithParent();
  9008. return this._parentedWorldMatrix;
  9009. }
  9010. return worldMatrix;
  9011. };
  9012. Light.prototype.dispose = function () {
  9013. if (this._shadowGenerator) {
  9014. this._shadowGenerator.dispose();
  9015. this._shadowGenerator = null;
  9016. }
  9017. // Animations
  9018. this.getScene().stopAnimation(this);
  9019. // Remove from scene
  9020. this.getScene().removeLight(this);
  9021. };
  9022. Light.prototype.getTypeID = function () {
  9023. return 0;
  9024. };
  9025. Light.prototype.clone = function (name) {
  9026. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9027. };
  9028. Light.prototype.serialize = function () {
  9029. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9030. // Type
  9031. serializationObject.type = this.getTypeID();
  9032. // Parent
  9033. if (this.parent) {
  9034. serializationObject.parentId = this.parent.id;
  9035. }
  9036. // Animations
  9037. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9038. serializationObject.ranges = this.serializeAnimationRanges();
  9039. return serializationObject;
  9040. };
  9041. Light.GetConstructorFromName = function (type, name, scene) {
  9042. switch (type) {
  9043. case 0:
  9044. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9045. case 1:
  9046. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9047. case 2:
  9048. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9049. case 3:
  9050. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9051. }
  9052. };
  9053. Light.Parse = function (parsedLight, scene) {
  9054. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9055. // Inclusion / exclusions
  9056. if (parsedLight.excludedMeshesIds) {
  9057. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9058. }
  9059. if (parsedLight.includedOnlyMeshesIds) {
  9060. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9061. }
  9062. // Parent
  9063. if (parsedLight.parentId) {
  9064. light._waitingParentId = parsedLight.parentId;
  9065. }
  9066. // Animations
  9067. if (parsedLight.animations) {
  9068. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9069. var parsedAnimation = parsedLight.animations[animationIndex];
  9070. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9071. }
  9072. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9073. }
  9074. if (parsedLight.autoAnimate) {
  9075. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9076. }
  9077. return light;
  9078. };
  9079. __decorate([
  9080. BABYLON.serializeAsColor3()
  9081. ], Light.prototype, "diffuse", void 0);
  9082. __decorate([
  9083. BABYLON.serializeAsColor3()
  9084. ], Light.prototype, "specular", void 0);
  9085. __decorate([
  9086. BABYLON.serialize()
  9087. ], Light.prototype, "intensity", void 0);
  9088. __decorate([
  9089. BABYLON.serialize()
  9090. ], Light.prototype, "range", void 0);
  9091. __decorate([
  9092. BABYLON.serialize()
  9093. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9094. __decorate([
  9095. BABYLON.serialize()
  9096. ], Light.prototype, "radius", void 0);
  9097. return Light;
  9098. })(BABYLON.Node);
  9099. BABYLON.Light = Light;
  9100. })(BABYLON || (BABYLON = {}));
  9101. var BABYLON;
  9102. (function (BABYLON) {
  9103. var PointLight = (function (_super) {
  9104. __extends(PointLight, _super);
  9105. function PointLight(name, position, scene) {
  9106. _super.call(this, name, scene);
  9107. this.position = position;
  9108. }
  9109. PointLight.prototype.getAbsolutePosition = function () {
  9110. return this.transformedPosition ? this.transformedPosition : this.position;
  9111. };
  9112. PointLight.prototype.computeTransformedPosition = function () {
  9113. if (this.parent && this.parent.getWorldMatrix) {
  9114. if (!this.transformedPosition) {
  9115. this.transformedPosition = BABYLON.Vector3.Zero();
  9116. }
  9117. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9118. return true;
  9119. }
  9120. return false;
  9121. };
  9122. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9123. if (this.parent && this.parent.getWorldMatrix) {
  9124. this.computeTransformedPosition();
  9125. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9126. return;
  9127. }
  9128. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9129. };
  9130. PointLight.prototype.needCube = function () {
  9131. return true;
  9132. };
  9133. PointLight.prototype.supportsVSM = function () {
  9134. return false;
  9135. };
  9136. PointLight.prototype.needRefreshPerFrame = function () {
  9137. return false;
  9138. };
  9139. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9140. switch (faceIndex) {
  9141. case 0:
  9142. return new BABYLON.Vector3(1, 0, 0);
  9143. case 1:
  9144. return new BABYLON.Vector3(-1, 0, 0);
  9145. case 2:
  9146. return new BABYLON.Vector3(0, -1, 0);
  9147. case 3:
  9148. return new BABYLON.Vector3(0, 1, 0);
  9149. case 4:
  9150. return new BABYLON.Vector3(0, 0, 1);
  9151. case 5:
  9152. return new BABYLON.Vector3(0, 0, -1);
  9153. }
  9154. return BABYLON.Vector3.Zero();
  9155. };
  9156. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9157. var activeCamera = this.getScene().activeCamera;
  9158. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9159. };
  9160. PointLight.prototype._getWorldMatrix = function () {
  9161. if (!this._worldMatrix) {
  9162. this._worldMatrix = BABYLON.Matrix.Identity();
  9163. }
  9164. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9165. return this._worldMatrix;
  9166. };
  9167. PointLight.prototype.getTypeID = function () {
  9168. return 0;
  9169. };
  9170. __decorate([
  9171. BABYLON.serializeAsVector3()
  9172. ], PointLight.prototype, "position", void 0);
  9173. return PointLight;
  9174. })(BABYLON.Light);
  9175. BABYLON.PointLight = PointLight;
  9176. })(BABYLON || (BABYLON = {}));
  9177. var BABYLON;
  9178. (function (BABYLON) {
  9179. var SpotLight = (function (_super) {
  9180. __extends(SpotLight, _super);
  9181. function SpotLight(name, position, direction, angle, exponent, scene) {
  9182. _super.call(this, name, scene);
  9183. this.position = position;
  9184. this.direction = direction;
  9185. this.angle = angle;
  9186. this.exponent = exponent;
  9187. }
  9188. SpotLight.prototype.getAbsolutePosition = function () {
  9189. return this.transformedPosition ? this.transformedPosition : this.position;
  9190. };
  9191. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9192. var activeCamera = this.getScene().activeCamera;
  9193. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9194. };
  9195. SpotLight.prototype.needCube = function () {
  9196. return false;
  9197. };
  9198. SpotLight.prototype.supportsVSM = function () {
  9199. return true;
  9200. };
  9201. SpotLight.prototype.needRefreshPerFrame = function () {
  9202. return false;
  9203. };
  9204. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9205. return this.direction;
  9206. };
  9207. SpotLight.prototype.setDirectionToTarget = function (target) {
  9208. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9209. return this.direction;
  9210. };
  9211. SpotLight.prototype.computeTransformedPosition = function () {
  9212. if (this.parent && this.parent.getWorldMatrix) {
  9213. if (!this.transformedPosition) {
  9214. this.transformedPosition = BABYLON.Vector3.Zero();
  9215. }
  9216. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9217. return true;
  9218. }
  9219. return false;
  9220. };
  9221. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9222. var normalizeDirection;
  9223. if (this.parent && this.parent.getWorldMatrix) {
  9224. if (!this._transformedDirection) {
  9225. this._transformedDirection = BABYLON.Vector3.Zero();
  9226. }
  9227. this.computeTransformedPosition();
  9228. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9229. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9230. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9231. }
  9232. else {
  9233. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9234. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9235. }
  9236. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9237. };
  9238. SpotLight.prototype._getWorldMatrix = function () {
  9239. if (!this._worldMatrix) {
  9240. this._worldMatrix = BABYLON.Matrix.Identity();
  9241. }
  9242. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9243. return this._worldMatrix;
  9244. };
  9245. SpotLight.prototype.getTypeID = function () {
  9246. return 2;
  9247. };
  9248. __decorate([
  9249. BABYLON.serializeAsVector3()
  9250. ], SpotLight.prototype, "position", void 0);
  9251. __decorate([
  9252. BABYLON.serializeAsVector3()
  9253. ], SpotLight.prototype, "direction", void 0);
  9254. __decorate([
  9255. BABYLON.serialize()
  9256. ], SpotLight.prototype, "angle", void 0);
  9257. __decorate([
  9258. BABYLON.serialize()
  9259. ], SpotLight.prototype, "exponent", void 0);
  9260. return SpotLight;
  9261. })(BABYLON.Light);
  9262. BABYLON.SpotLight = SpotLight;
  9263. })(BABYLON || (BABYLON = {}));
  9264. var BABYLON;
  9265. (function (BABYLON) {
  9266. var HemisphericLight = (function (_super) {
  9267. __extends(HemisphericLight, _super);
  9268. function HemisphericLight(name, direction, scene) {
  9269. _super.call(this, name, scene);
  9270. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9271. this.direction = direction;
  9272. }
  9273. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9274. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9275. return this.direction;
  9276. };
  9277. HemisphericLight.prototype.getShadowGenerator = function () {
  9278. return null;
  9279. };
  9280. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9281. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9282. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9283. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9284. };
  9285. HemisphericLight.prototype._getWorldMatrix = function () {
  9286. if (!this._worldMatrix) {
  9287. this._worldMatrix = BABYLON.Matrix.Identity();
  9288. }
  9289. return this._worldMatrix;
  9290. };
  9291. HemisphericLight.prototype.getTypeID = function () {
  9292. return 3;
  9293. };
  9294. __decorate([
  9295. BABYLON.serializeAsColor3()
  9296. ], HemisphericLight.prototype, "groundColor", void 0);
  9297. __decorate([
  9298. BABYLON.serializeAsVector3()
  9299. ], HemisphericLight.prototype, "direction", void 0);
  9300. return HemisphericLight;
  9301. })(BABYLON.Light);
  9302. BABYLON.HemisphericLight = HemisphericLight;
  9303. })(BABYLON || (BABYLON = {}));
  9304. var BABYLON;
  9305. (function (BABYLON) {
  9306. var DirectionalLight = (function (_super) {
  9307. __extends(DirectionalLight, _super);
  9308. function DirectionalLight(name, direction, scene) {
  9309. _super.call(this, name, scene);
  9310. this.shadowOrthoScale = 0.5;
  9311. this.autoUpdateExtends = true;
  9312. // Cache
  9313. this._orthoLeft = Number.MAX_VALUE;
  9314. this._orthoRight = Number.MIN_VALUE;
  9315. this._orthoTop = Number.MIN_VALUE;
  9316. this._orthoBottom = Number.MAX_VALUE;
  9317. this.position = direction.scale(-1);
  9318. this.direction = direction;
  9319. }
  9320. DirectionalLight.prototype.getAbsolutePosition = function () {
  9321. return this.transformedPosition ? this.transformedPosition : this.position;
  9322. };
  9323. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9324. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9325. return this.direction;
  9326. };
  9327. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9328. var activeCamera = this.getScene().activeCamera;
  9329. // Check extends
  9330. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9331. var tempVector3 = BABYLON.Vector3.Zero();
  9332. this._orthoLeft = Number.MAX_VALUE;
  9333. this._orthoRight = Number.MIN_VALUE;
  9334. this._orthoTop = Number.MIN_VALUE;
  9335. this._orthoBottom = Number.MAX_VALUE;
  9336. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9337. var mesh = renderList[meshIndex];
  9338. if (!mesh) {
  9339. continue;
  9340. }
  9341. var boundingInfo = mesh.getBoundingInfo();
  9342. if (!boundingInfo) {
  9343. continue;
  9344. }
  9345. var boundingBox = boundingInfo.boundingBox;
  9346. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9347. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9348. if (tempVector3.x < this._orthoLeft)
  9349. this._orthoLeft = tempVector3.x;
  9350. if (tempVector3.y < this._orthoBottom)
  9351. this._orthoBottom = tempVector3.y;
  9352. if (tempVector3.x > this._orthoRight)
  9353. this._orthoRight = tempVector3.x;
  9354. if (tempVector3.y > this._orthoTop)
  9355. this._orthoTop = tempVector3.y;
  9356. }
  9357. }
  9358. }
  9359. var xOffset = this._orthoRight - this._orthoLeft;
  9360. var yOffset = this._orthoTop - this._orthoBottom;
  9361. 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);
  9362. };
  9363. DirectionalLight.prototype.supportsVSM = function () {
  9364. return true;
  9365. };
  9366. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9367. return true;
  9368. };
  9369. DirectionalLight.prototype.needCube = function () {
  9370. return false;
  9371. };
  9372. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9373. return this.direction;
  9374. };
  9375. DirectionalLight.prototype.computeTransformedPosition = function () {
  9376. if (this.parent && this.parent.getWorldMatrix) {
  9377. if (!this.transformedPosition) {
  9378. this.transformedPosition = BABYLON.Vector3.Zero();
  9379. }
  9380. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9381. return true;
  9382. }
  9383. return false;
  9384. };
  9385. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9386. if (this.parent && this.parent.getWorldMatrix) {
  9387. if (!this._transformedDirection) {
  9388. this._transformedDirection = BABYLON.Vector3.Zero();
  9389. }
  9390. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9391. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9392. return;
  9393. }
  9394. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9395. };
  9396. DirectionalLight.prototype._getWorldMatrix = function () {
  9397. if (!this._worldMatrix) {
  9398. this._worldMatrix = BABYLON.Matrix.Identity();
  9399. }
  9400. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9401. return this._worldMatrix;
  9402. };
  9403. DirectionalLight.prototype.getTypeID = function () {
  9404. return 1;
  9405. };
  9406. __decorate([
  9407. BABYLON.serializeAsVector3()
  9408. ], DirectionalLight.prototype, "position", void 0);
  9409. __decorate([
  9410. BABYLON.serializeAsVector3()
  9411. ], DirectionalLight.prototype, "direction", void 0);
  9412. __decorate([
  9413. BABYLON.serialize()
  9414. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9415. __decorate([
  9416. BABYLON.serialize()
  9417. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9418. return DirectionalLight;
  9419. })(BABYLON.Light);
  9420. BABYLON.DirectionalLight = DirectionalLight;
  9421. })(BABYLON || (BABYLON = {}));
  9422. var BABYLON;
  9423. (function (BABYLON) {
  9424. var ShadowGenerator = (function () {
  9425. function ShadowGenerator(mapSize, light) {
  9426. var _this = this;
  9427. // Members
  9428. this._filter = ShadowGenerator.FILTER_NONE;
  9429. this.blurScale = 2;
  9430. this._blurBoxOffset = 0;
  9431. this._bias = 0.00005;
  9432. this._lightDirection = BABYLON.Vector3.Zero();
  9433. this.forceBackFacesOnly = false;
  9434. this._darkness = 0;
  9435. this._transparencyShadow = false;
  9436. this._viewMatrix = BABYLON.Matrix.Zero();
  9437. this._projectionMatrix = BABYLON.Matrix.Zero();
  9438. this._transformMatrix = BABYLON.Matrix.Zero();
  9439. this._worldViewProjection = BABYLON.Matrix.Zero();
  9440. this._currentFaceIndex = 0;
  9441. this._currentFaceIndexCache = 0;
  9442. this._light = light;
  9443. this._scene = light.getScene();
  9444. this._mapSize = mapSize;
  9445. light._shadowGenerator = this;
  9446. // Render target
  9447. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9448. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9449. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9450. this._shadowMap.anisotropicFilteringLevel = 1;
  9451. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9452. this._shadowMap.renderParticles = false;
  9453. this._shadowMap.onBeforeRender = function (faceIndex) {
  9454. _this._currentFaceIndex = faceIndex;
  9455. };
  9456. this._shadowMap.onAfterUnbind = function () {
  9457. if (!_this.useBlurVarianceShadowMap) {
  9458. return;
  9459. }
  9460. if (!_this._shadowMap2) {
  9461. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9462. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9463. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9464. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9465. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9466. _this._downSamplePostprocess.onApply = function (effect) {
  9467. effect.setTexture("textureSampler", _this._shadowMap);
  9468. };
  9469. _this.blurBoxOffset = 1;
  9470. }
  9471. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9472. };
  9473. // Custom render function
  9474. var renderSubMesh = function (subMesh) {
  9475. var mesh = subMesh.getRenderingMesh();
  9476. var scene = _this._scene;
  9477. var engine = scene.getEngine();
  9478. // Culling
  9479. engine.setState(subMesh.getMaterial().backFaceCulling);
  9480. // Managing instances
  9481. var batch = mesh._getInstancesRenderList(subMesh._id);
  9482. if (batch.mustReturn) {
  9483. return;
  9484. }
  9485. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9486. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9487. engine.enableEffect(_this._effect);
  9488. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9489. var material = subMesh.getMaterial();
  9490. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9491. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9492. if (_this.getLight().needCube()) {
  9493. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9494. }
  9495. // Alpha test
  9496. if (material && material.needAlphaTesting()) {
  9497. var alphaTexture = material.getAlphaTestTexture();
  9498. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9499. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9500. }
  9501. // Bones
  9502. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9503. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9504. }
  9505. if (_this.forceBackFacesOnly) {
  9506. engine.setState(true, 0, false, true);
  9507. }
  9508. // Draw
  9509. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9510. if (_this.forceBackFacesOnly) {
  9511. engine.setState(true, 0, false, false);
  9512. }
  9513. }
  9514. else {
  9515. // Need to reset refresh rate of the shadowMap
  9516. _this._shadowMap.resetRefreshCounter();
  9517. }
  9518. };
  9519. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9520. var index;
  9521. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9522. renderSubMesh(opaqueSubMeshes.data[index]);
  9523. }
  9524. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9525. renderSubMesh(alphaTestSubMeshes.data[index]);
  9526. }
  9527. if (_this._transparencyShadow) {
  9528. for (index = 0; index < transparentSubMeshes.length; index++) {
  9529. renderSubMesh(transparentSubMeshes.data[index]);
  9530. }
  9531. }
  9532. };
  9533. this._shadowMap.onClear = function (engine) {
  9534. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9535. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9536. }
  9537. else {
  9538. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9539. }
  9540. };
  9541. }
  9542. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9543. // Static
  9544. get: function () {
  9545. return ShadowGenerator._FILTER_NONE;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9551. get: function () {
  9552. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9558. get: function () {
  9559. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9565. get: function () {
  9566. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9572. get: function () {
  9573. return this._bias;
  9574. },
  9575. set: function (bias) {
  9576. this._bias = bias;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9582. get: function () {
  9583. return this._blurBoxOffset;
  9584. },
  9585. set: function (value) {
  9586. var _this = this;
  9587. if (this._blurBoxOffset === value) {
  9588. return;
  9589. }
  9590. this._blurBoxOffset = value;
  9591. if (this._boxBlurPostprocess) {
  9592. this._boxBlurPostprocess.dispose();
  9593. }
  9594. 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);
  9595. this._boxBlurPostprocess.onApply = function (effect) {
  9596. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9597. };
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9603. get: function () {
  9604. return this._filter;
  9605. },
  9606. set: function (value) {
  9607. if (this._filter === value) {
  9608. return;
  9609. }
  9610. this._filter = value;
  9611. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9612. this._shadowMap.anisotropicFilteringLevel = 16;
  9613. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9614. }
  9615. else {
  9616. this._shadowMap.anisotropicFilteringLevel = 1;
  9617. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9618. }
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9624. get: function () {
  9625. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9626. },
  9627. set: function (value) {
  9628. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9629. },
  9630. enumerable: true,
  9631. configurable: true
  9632. });
  9633. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9634. get: function () {
  9635. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9636. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9637. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9638. },
  9639. set: function (value) {
  9640. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9646. get: function () {
  9647. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9648. },
  9649. set: function (value) {
  9650. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9656. var defines = [];
  9657. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9658. defines.push("#define VSM");
  9659. }
  9660. if (this.getLight().needCube()) {
  9661. defines.push("#define CUBEMAP");
  9662. }
  9663. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9664. var mesh = subMesh.getMesh();
  9665. var material = subMesh.getMaterial();
  9666. // Alpha test
  9667. if (material && material.needAlphaTesting()) {
  9668. defines.push("#define ALPHATEST");
  9669. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9670. attribs.push(BABYLON.VertexBuffer.UVKind);
  9671. defines.push("#define UV1");
  9672. }
  9673. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9674. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9675. defines.push("#define UV2");
  9676. }
  9677. }
  9678. // Bones
  9679. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9680. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9681. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9682. if (mesh.numBoneInfluencers > 4) {
  9683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9685. }
  9686. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9687. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9688. }
  9689. else {
  9690. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9691. }
  9692. // Instances
  9693. if (useInstances) {
  9694. defines.push("#define INSTANCES");
  9695. attribs.push("world0");
  9696. attribs.push("world1");
  9697. attribs.push("world2");
  9698. attribs.push("world3");
  9699. }
  9700. // Get correct effect
  9701. var join = defines.join("\n");
  9702. if (this._cachedDefines !== join) {
  9703. this._cachedDefines = join;
  9704. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9705. }
  9706. return this._effect.isReady();
  9707. };
  9708. ShadowGenerator.prototype.getShadowMap = function () {
  9709. return this._shadowMap;
  9710. };
  9711. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9712. if (this._shadowMap2) {
  9713. return this._shadowMap2;
  9714. }
  9715. return this._shadowMap;
  9716. };
  9717. ShadowGenerator.prototype.getLight = function () {
  9718. return this._light;
  9719. };
  9720. // Methods
  9721. ShadowGenerator.prototype.getTransformMatrix = function () {
  9722. var scene = this._scene;
  9723. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9724. return this._transformMatrix;
  9725. }
  9726. this._currentRenderID = scene.getRenderId();
  9727. this._currentFaceIndexCache = this._currentFaceIndex;
  9728. var lightPosition = this._light.position;
  9729. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9730. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9731. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9732. }
  9733. if (this._light.computeTransformedPosition()) {
  9734. lightPosition = this._light.transformedPosition;
  9735. }
  9736. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9737. this._cachedPosition = lightPosition.clone();
  9738. this._cachedDirection = this._lightDirection.clone();
  9739. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9740. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9741. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9742. }
  9743. return this._transformMatrix;
  9744. };
  9745. ShadowGenerator.prototype.getDarkness = function () {
  9746. return this._darkness;
  9747. };
  9748. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9749. if (darkness >= 1.0)
  9750. this._darkness = 1.0;
  9751. else if (darkness <= 0.0)
  9752. this._darkness = 0.0;
  9753. else
  9754. this._darkness = darkness;
  9755. };
  9756. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9757. this._transparencyShadow = hasShadow;
  9758. };
  9759. ShadowGenerator.prototype._packHalf = function (depth) {
  9760. var scale = depth * 255.0;
  9761. var fract = scale - Math.floor(scale);
  9762. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9763. };
  9764. ShadowGenerator.prototype.dispose = function () {
  9765. this._shadowMap.dispose();
  9766. if (this._shadowMap2) {
  9767. this._shadowMap2.dispose();
  9768. }
  9769. if (this._downSamplePostprocess) {
  9770. this._downSamplePostprocess.dispose();
  9771. }
  9772. if (this._boxBlurPostprocess) {
  9773. this._boxBlurPostprocess.dispose();
  9774. }
  9775. };
  9776. ShadowGenerator.prototype.serialize = function () {
  9777. var serializationObject = {};
  9778. serializationObject.lightId = this._light.id;
  9779. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9780. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9781. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9782. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9783. serializationObject.renderList = [];
  9784. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9785. var mesh = this.getShadowMap().renderList[meshIndex];
  9786. serializationObject.renderList.push(mesh.id);
  9787. }
  9788. return serializationObject;
  9789. };
  9790. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9791. //casting to point light, as light is missing the position attr and typescript complains.
  9792. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9793. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9794. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9795. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9796. shadowGenerator.getShadowMap().renderList.push(mesh);
  9797. }
  9798. if (parsedShadowGenerator.usePoissonSampling) {
  9799. shadowGenerator.usePoissonSampling = true;
  9800. }
  9801. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9802. shadowGenerator.useVarianceShadowMap = true;
  9803. }
  9804. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9805. shadowGenerator.useBlurVarianceShadowMap = true;
  9806. if (parsedShadowGenerator.blurScale) {
  9807. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9808. }
  9809. if (parsedShadowGenerator.blurBoxOffset) {
  9810. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9811. }
  9812. }
  9813. if (parsedShadowGenerator.bias !== undefined) {
  9814. shadowGenerator.bias = parsedShadowGenerator.bias;
  9815. }
  9816. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9817. return shadowGenerator;
  9818. };
  9819. ShadowGenerator._FILTER_NONE = 0;
  9820. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9821. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9822. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9823. return ShadowGenerator;
  9824. })();
  9825. BABYLON.ShadowGenerator = ShadowGenerator;
  9826. })(BABYLON || (BABYLON = {}));
  9827. var BABYLON;
  9828. (function (BABYLON) {
  9829. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9830. if (boxMin.x > sphereCenter.x + sphereRadius)
  9831. return false;
  9832. if (sphereCenter.x - sphereRadius > boxMax.x)
  9833. return false;
  9834. if (boxMin.y > sphereCenter.y + sphereRadius)
  9835. return false;
  9836. if (sphereCenter.y - sphereRadius > boxMax.y)
  9837. return false;
  9838. if (boxMin.z > sphereCenter.z + sphereRadius)
  9839. return false;
  9840. if (sphereCenter.z - sphereRadius > boxMax.z)
  9841. return false;
  9842. return true;
  9843. };
  9844. var getLowestRoot = function (a, b, c, maxR) {
  9845. var determinant = b * b - 4.0 * a * c;
  9846. var result = { root: 0, found: false };
  9847. if (determinant < 0)
  9848. return result;
  9849. var sqrtD = Math.sqrt(determinant);
  9850. var r1 = (-b - sqrtD) / (2.0 * a);
  9851. var r2 = (-b + sqrtD) / (2.0 * a);
  9852. if (r1 > r2) {
  9853. var temp = r2;
  9854. r2 = r1;
  9855. r1 = temp;
  9856. }
  9857. if (r1 > 0 && r1 < maxR) {
  9858. result.root = r1;
  9859. result.found = true;
  9860. return result;
  9861. }
  9862. if (r2 > 0 && r2 < maxR) {
  9863. result.root = r2;
  9864. result.found = true;
  9865. return result;
  9866. }
  9867. return result;
  9868. };
  9869. var Collider = (function () {
  9870. function Collider() {
  9871. this.radius = new BABYLON.Vector3(1, 1, 1);
  9872. this.retry = 0;
  9873. this.basePointWorld = BABYLON.Vector3.Zero();
  9874. this.velocityWorld = BABYLON.Vector3.Zero();
  9875. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9876. this._collisionPoint = BABYLON.Vector3.Zero();
  9877. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9878. this._tempVector = BABYLON.Vector3.Zero();
  9879. this._tempVector2 = BABYLON.Vector3.Zero();
  9880. this._tempVector3 = BABYLON.Vector3.Zero();
  9881. this._tempVector4 = BABYLON.Vector3.Zero();
  9882. this._edge = BABYLON.Vector3.Zero();
  9883. this._baseToVertex = BABYLON.Vector3.Zero();
  9884. this._destinationPoint = BABYLON.Vector3.Zero();
  9885. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9886. this._displacementVector = BABYLON.Vector3.Zero();
  9887. }
  9888. // Methods
  9889. Collider.prototype._initialize = function (source, dir, e) {
  9890. this.velocity = dir;
  9891. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9892. this.basePoint = source;
  9893. source.multiplyToRef(this.radius, this.basePointWorld);
  9894. dir.multiplyToRef(this.radius, this.velocityWorld);
  9895. this.velocityWorldLength = this.velocityWorld.length();
  9896. this.epsilon = e;
  9897. this.collisionFound = false;
  9898. };
  9899. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9900. pa.subtractToRef(point, this._tempVector);
  9901. pb.subtractToRef(point, this._tempVector2);
  9902. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9903. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9904. if (d < 0)
  9905. return false;
  9906. pc.subtractToRef(point, this._tempVector3);
  9907. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9908. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9909. if (d < 0)
  9910. return false;
  9911. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9912. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9913. return d >= 0;
  9914. };
  9915. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9916. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9917. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9918. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9919. return false;
  9920. }
  9921. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9922. return false;
  9923. return true;
  9924. };
  9925. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9926. var t0;
  9927. var embeddedInPlane = false;
  9928. //defensive programming, actually not needed.
  9929. if (!trianglePlaneArray) {
  9930. trianglePlaneArray = [];
  9931. }
  9932. if (!trianglePlaneArray[faceIndex]) {
  9933. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9934. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9935. }
  9936. var trianglePlane = trianglePlaneArray[faceIndex];
  9937. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9938. return;
  9939. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9940. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9941. if (normalDotVelocity == 0) {
  9942. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9943. return;
  9944. embeddedInPlane = true;
  9945. t0 = 0;
  9946. }
  9947. else {
  9948. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9949. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9950. if (t0 > t1) {
  9951. var temp = t1;
  9952. t1 = t0;
  9953. t0 = temp;
  9954. }
  9955. if (t0 > 1.0 || t1 < 0.0)
  9956. return;
  9957. if (t0 < 0)
  9958. t0 = 0;
  9959. if (t0 > 1.0)
  9960. t0 = 1.0;
  9961. }
  9962. this._collisionPoint.copyFromFloats(0, 0, 0);
  9963. var found = false;
  9964. var t = 1.0;
  9965. if (!embeddedInPlane) {
  9966. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9967. this.velocity.scaleToRef(t0, this._tempVector);
  9968. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9969. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9970. found = true;
  9971. t = t0;
  9972. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9973. }
  9974. }
  9975. if (!found) {
  9976. var velocitySquaredLength = this.velocity.lengthSquared();
  9977. var a = velocitySquaredLength;
  9978. this.basePoint.subtractToRef(p1, this._tempVector);
  9979. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9980. var c = this._tempVector.lengthSquared() - 1.0;
  9981. var lowestRoot = getLowestRoot(a, b, c, t);
  9982. if (lowestRoot.found) {
  9983. t = lowestRoot.root;
  9984. found = true;
  9985. this._collisionPoint.copyFrom(p1);
  9986. }
  9987. this.basePoint.subtractToRef(p2, this._tempVector);
  9988. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9989. c = this._tempVector.lengthSquared() - 1.0;
  9990. lowestRoot = getLowestRoot(a, b, c, t);
  9991. if (lowestRoot.found) {
  9992. t = lowestRoot.root;
  9993. found = true;
  9994. this._collisionPoint.copyFrom(p2);
  9995. }
  9996. this.basePoint.subtractToRef(p3, this._tempVector);
  9997. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9998. c = this._tempVector.lengthSquared() - 1.0;
  9999. lowestRoot = getLowestRoot(a, b, c, t);
  10000. if (lowestRoot.found) {
  10001. t = lowestRoot.root;
  10002. found = true;
  10003. this._collisionPoint.copyFrom(p3);
  10004. }
  10005. p2.subtractToRef(p1, this._edge);
  10006. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10007. var edgeSquaredLength = this._edge.lengthSquared();
  10008. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10009. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10010. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10011. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10012. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10013. lowestRoot = getLowestRoot(a, b, c, t);
  10014. if (lowestRoot.found) {
  10015. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10016. if (f >= 0.0 && f <= 1.0) {
  10017. t = lowestRoot.root;
  10018. found = true;
  10019. this._edge.scaleInPlace(f);
  10020. p1.addToRef(this._edge, this._collisionPoint);
  10021. }
  10022. }
  10023. p3.subtractToRef(p2, this._edge);
  10024. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10025. edgeSquaredLength = this._edge.lengthSquared();
  10026. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10027. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10028. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10029. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10030. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10031. lowestRoot = getLowestRoot(a, b, c, t);
  10032. if (lowestRoot.found) {
  10033. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10034. if (f >= 0.0 && f <= 1.0) {
  10035. t = lowestRoot.root;
  10036. found = true;
  10037. this._edge.scaleInPlace(f);
  10038. p2.addToRef(this._edge, this._collisionPoint);
  10039. }
  10040. }
  10041. p1.subtractToRef(p3, this._edge);
  10042. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10043. edgeSquaredLength = this._edge.lengthSquared();
  10044. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10045. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10046. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10047. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10048. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10049. lowestRoot = getLowestRoot(a, b, c, t);
  10050. if (lowestRoot.found) {
  10051. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10052. if (f >= 0.0 && f <= 1.0) {
  10053. t = lowestRoot.root;
  10054. found = true;
  10055. this._edge.scaleInPlace(f);
  10056. p3.addToRef(this._edge, this._collisionPoint);
  10057. }
  10058. }
  10059. }
  10060. if (found) {
  10061. var distToCollision = t * this.velocity.length();
  10062. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10063. if (!this.intersectionPoint) {
  10064. this.intersectionPoint = this._collisionPoint.clone();
  10065. }
  10066. else {
  10067. this.intersectionPoint.copyFrom(this._collisionPoint);
  10068. }
  10069. this.nearestDistance = distToCollision;
  10070. this.collisionFound = true;
  10071. }
  10072. }
  10073. };
  10074. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10075. for (var i = indexStart; i < indexEnd; i += 3) {
  10076. var p1 = pts[indices[i] - decal];
  10077. var p2 = pts[indices[i + 1] - decal];
  10078. var p3 = pts[indices[i + 2] - decal];
  10079. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10080. }
  10081. };
  10082. Collider.prototype._getResponse = function (pos, vel) {
  10083. pos.addToRef(vel, this._destinationPoint);
  10084. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10085. this.basePoint.addToRef(vel, pos);
  10086. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10087. this._slidePlaneNormal.normalize();
  10088. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10089. pos.addInPlace(this._displacementVector);
  10090. this.intersectionPoint.addInPlace(this._displacementVector);
  10091. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10092. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10093. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10094. };
  10095. return Collider;
  10096. })();
  10097. BABYLON.Collider = Collider;
  10098. })(BABYLON || (BABYLON = {}));
  10099. var BABYLON;
  10100. (function (BABYLON) {
  10101. //WebWorker code will be inserted to this variable.
  10102. BABYLON.CollisionWorker = "";
  10103. (function (WorkerTaskType) {
  10104. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10105. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10106. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10107. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10108. var WorkerTaskType = BABYLON.WorkerTaskType;
  10109. (function (WorkerReplyType) {
  10110. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10111. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10112. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10113. var WorkerReplyType = BABYLON.WorkerReplyType;
  10114. var CollisionCoordinatorWorker = (function () {
  10115. function CollisionCoordinatorWorker() {
  10116. var _this = this;
  10117. this._scaledPosition = BABYLON.Vector3.Zero();
  10118. this._scaledVelocity = BABYLON.Vector3.Zero();
  10119. this.onMeshUpdated = function (mesh) {
  10120. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10121. };
  10122. this.onGeometryUpdated = function (geometry) {
  10123. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10124. };
  10125. this._afterRender = function () {
  10126. if (!_this._init)
  10127. return;
  10128. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10129. return;
  10130. }
  10131. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10132. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10133. if (_this._runningUpdated > 4) {
  10134. return;
  10135. }
  10136. ++_this._runningUpdated;
  10137. var payload = {
  10138. updatedMeshes: _this._addUpdateMeshesList,
  10139. updatedGeometries: _this._addUpdateGeometriesList,
  10140. removedGeometries: _this._toRemoveGeometryArray,
  10141. removedMeshes: _this._toRemoveMeshesArray
  10142. };
  10143. var message = {
  10144. payload: payload,
  10145. taskType: WorkerTaskType.UPDATE
  10146. };
  10147. var serializable = [];
  10148. for (var id in payload.updatedGeometries) {
  10149. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10150. //prepare transferables
  10151. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10152. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10153. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10154. }
  10155. }
  10156. _this._worker.postMessage(message, serializable);
  10157. _this._addUpdateMeshesList = {};
  10158. _this._addUpdateGeometriesList = {};
  10159. _this._toRemoveGeometryArray = [];
  10160. _this._toRemoveMeshesArray = [];
  10161. };
  10162. this._onMessageFromWorker = function (e) {
  10163. var returnData = e.data;
  10164. if (returnData.error != WorkerReplyType.SUCCESS) {
  10165. //TODO what errors can be returned from the worker?
  10166. BABYLON.Tools.Warn("error returned from worker!");
  10167. return;
  10168. }
  10169. switch (returnData.taskType) {
  10170. case WorkerTaskType.INIT:
  10171. _this._init = true;
  10172. //Update the worked with ALL of the scene's current state
  10173. _this._scene.meshes.forEach(function (mesh) {
  10174. _this.onMeshAdded(mesh);
  10175. });
  10176. _this._scene.getGeometries().forEach(function (geometry) {
  10177. _this.onGeometryAdded(geometry);
  10178. });
  10179. break;
  10180. case WorkerTaskType.UPDATE:
  10181. _this._runningUpdated--;
  10182. break;
  10183. case WorkerTaskType.COLLIDE:
  10184. _this._runningCollisionTask = false;
  10185. var returnPayload = returnData.payload;
  10186. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10187. return;
  10188. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10189. //cleanup
  10190. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10191. break;
  10192. }
  10193. };
  10194. this._collisionsCallbackArray = [];
  10195. this._init = false;
  10196. this._runningUpdated = 0;
  10197. this._runningCollisionTask = false;
  10198. this._addUpdateMeshesList = {};
  10199. this._addUpdateGeometriesList = {};
  10200. this._toRemoveGeometryArray = [];
  10201. this._toRemoveMeshesArray = [];
  10202. }
  10203. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10204. if (!this._init)
  10205. return;
  10206. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10207. return;
  10208. position.divideToRef(collider.radius, this._scaledPosition);
  10209. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10210. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10211. var payload = {
  10212. collider: {
  10213. position: this._scaledPosition.asArray(),
  10214. velocity: this._scaledVelocity.asArray(),
  10215. radius: collider.radius.asArray()
  10216. },
  10217. collisionId: collisionIndex,
  10218. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10219. maximumRetry: maximumRetry
  10220. };
  10221. var message = {
  10222. payload: payload,
  10223. taskType: WorkerTaskType.COLLIDE
  10224. };
  10225. this._worker.postMessage(message);
  10226. };
  10227. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10228. this._scene = scene;
  10229. this._scene.registerAfterRender(this._afterRender);
  10230. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10231. this._worker = new Worker(workerUrl);
  10232. this._worker.onmessage = this._onMessageFromWorker;
  10233. var message = {
  10234. payload: {},
  10235. taskType: WorkerTaskType.INIT
  10236. };
  10237. this._worker.postMessage(message);
  10238. };
  10239. CollisionCoordinatorWorker.prototype.destroy = function () {
  10240. this._scene.unregisterAfterRender(this._afterRender);
  10241. this._worker.terminate();
  10242. };
  10243. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10244. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10245. this.onMeshUpdated(mesh);
  10246. };
  10247. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10248. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10249. };
  10250. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10251. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10252. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10253. this.onGeometryUpdated(geometry);
  10254. };
  10255. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10256. this._toRemoveGeometryArray.push(geometry.id);
  10257. };
  10258. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10259. var submeshes = [];
  10260. if (mesh.subMeshes) {
  10261. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10262. return {
  10263. position: idx,
  10264. verticesStart: sm.verticesStart,
  10265. verticesCount: sm.verticesCount,
  10266. indexStart: sm.indexStart,
  10267. indexCount: sm.indexCount,
  10268. hasMaterial: !!sm.getMaterial(),
  10269. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10270. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10271. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10272. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10273. };
  10274. });
  10275. }
  10276. var geometryId = null;
  10277. if (mesh instanceof BABYLON.Mesh) {
  10278. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10279. }
  10280. else if (mesh instanceof BABYLON.InstancedMesh) {
  10281. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10282. }
  10283. return {
  10284. uniqueId: mesh.uniqueId,
  10285. id: mesh.id,
  10286. name: mesh.name,
  10287. geometryId: geometryId,
  10288. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10289. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10290. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10291. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10292. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10293. subMeshes: submeshes,
  10294. checkCollisions: mesh.checkCollisions
  10295. };
  10296. };
  10297. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10298. return {
  10299. id: geometry.id,
  10300. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10301. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10302. indices: new Int32Array(geometry.getIndices() || []),
  10303. };
  10304. };
  10305. return CollisionCoordinatorWorker;
  10306. })();
  10307. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10308. var CollisionCoordinatorLegacy = (function () {
  10309. function CollisionCoordinatorLegacy() {
  10310. this._scaledPosition = BABYLON.Vector3.Zero();
  10311. this._scaledVelocity = BABYLON.Vector3.Zero();
  10312. this._finalPosition = BABYLON.Vector3.Zero();
  10313. }
  10314. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10315. position.divideToRef(collider.radius, this._scaledPosition);
  10316. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10317. collider.collidedMesh = null;
  10318. collider.retry = 0;
  10319. collider.initialVelocity = this._scaledVelocity;
  10320. collider.initialPosition = this._scaledPosition;
  10321. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10322. this._finalPosition.multiplyInPlace(collider.radius);
  10323. //run the callback
  10324. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10325. };
  10326. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10327. this._scene = scene;
  10328. };
  10329. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10330. //Legacy need no destruction method.
  10331. };
  10332. //No update in legacy mode
  10333. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10334. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10335. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10336. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10337. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10338. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10339. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10340. if (excludedMesh === void 0) { excludedMesh = null; }
  10341. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10342. if (collider.retry >= maximumRetry) {
  10343. finalPosition.copyFrom(position);
  10344. return;
  10345. }
  10346. collider._initialize(position, velocity, closeDistance);
  10347. // Check all meshes
  10348. for (var index = 0; index < this._scene.meshes.length; index++) {
  10349. var mesh = this._scene.meshes[index];
  10350. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10351. mesh._checkCollision(collider);
  10352. }
  10353. }
  10354. if (!collider.collisionFound) {
  10355. position.addToRef(velocity, finalPosition);
  10356. return;
  10357. }
  10358. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10359. collider._getResponse(position, velocity);
  10360. }
  10361. if (velocity.length() <= closeDistance) {
  10362. finalPosition.copyFrom(position);
  10363. return;
  10364. }
  10365. collider.retry++;
  10366. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10367. };
  10368. return CollisionCoordinatorLegacy;
  10369. })();
  10370. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10371. })(BABYLON || (BABYLON = {}));
  10372. var BABYLON;
  10373. (function (BABYLON) {
  10374. var Camera = (function (_super) {
  10375. __extends(Camera, _super);
  10376. function Camera(name, position, scene) {
  10377. _super.call(this, name, scene);
  10378. this.upVector = BABYLON.Vector3.Up();
  10379. this.orthoLeft = null;
  10380. this.orthoRight = null;
  10381. this.orthoBottom = null;
  10382. this.orthoTop = null;
  10383. this.fov = 0.8;
  10384. this.minZ = 1.0;
  10385. this.maxZ = 10000.0;
  10386. this.inertia = 0.9;
  10387. this.mode = Camera.PERSPECTIVE_CAMERA;
  10388. this.isIntermediate = false;
  10389. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10390. this.layerMask = 0x0FFFFFFF;
  10391. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10392. // Camera rig members
  10393. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10394. this._rigCameras = new Array();
  10395. // Cache
  10396. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10397. this._projectionMatrix = new BABYLON.Matrix();
  10398. this._postProcesses = new Array();
  10399. this._postProcessesTakenIndices = [];
  10400. this._activeMeshes = new BABYLON.SmartArray(256);
  10401. this._globalPosition = BABYLON.Vector3.Zero();
  10402. scene.addCamera(this);
  10403. if (!scene.activeCamera) {
  10404. scene.activeCamera = this;
  10405. }
  10406. this.position = position;
  10407. }
  10408. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10409. get: function () {
  10410. return Camera._PERSPECTIVE_CAMERA;
  10411. },
  10412. enumerable: true,
  10413. configurable: true
  10414. });
  10415. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10416. get: function () {
  10417. return Camera._ORTHOGRAPHIC_CAMERA;
  10418. },
  10419. enumerable: true,
  10420. configurable: true
  10421. });
  10422. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10423. get: function () {
  10424. return Camera._FOVMODE_VERTICAL_FIXED;
  10425. },
  10426. enumerable: true,
  10427. configurable: true
  10428. });
  10429. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10430. get: function () {
  10431. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10432. },
  10433. enumerable: true,
  10434. configurable: true
  10435. });
  10436. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10437. get: function () {
  10438. return Camera._RIG_MODE_NONE;
  10439. },
  10440. enumerable: true,
  10441. configurable: true
  10442. });
  10443. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10444. get: function () {
  10445. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10446. },
  10447. enumerable: true,
  10448. configurable: true
  10449. });
  10450. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10451. get: function () {
  10452. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10453. },
  10454. enumerable: true,
  10455. configurable: true
  10456. });
  10457. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10458. get: function () {
  10459. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10460. },
  10461. enumerable: true,
  10462. configurable: true
  10463. });
  10464. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10465. get: function () {
  10466. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10467. },
  10468. enumerable: true,
  10469. configurable: true
  10470. });
  10471. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10472. get: function () {
  10473. return Camera._RIG_MODE_VR;
  10474. },
  10475. enumerable: true,
  10476. configurable: true
  10477. });
  10478. Object.defineProperty(Camera.prototype, "globalPosition", {
  10479. get: function () {
  10480. return this._globalPosition;
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. Camera.prototype.getActiveMeshes = function () {
  10486. return this._activeMeshes;
  10487. };
  10488. Camera.prototype.isActiveMesh = function (mesh) {
  10489. return (this._activeMeshes.indexOf(mesh) !== -1);
  10490. };
  10491. //Cache
  10492. Camera.prototype._initCache = function () {
  10493. _super.prototype._initCache.call(this);
  10494. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10495. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10496. this._cache.mode = undefined;
  10497. this._cache.minZ = undefined;
  10498. this._cache.maxZ = undefined;
  10499. this._cache.fov = undefined;
  10500. this._cache.aspectRatio = undefined;
  10501. this._cache.orthoLeft = undefined;
  10502. this._cache.orthoRight = undefined;
  10503. this._cache.orthoBottom = undefined;
  10504. this._cache.orthoTop = undefined;
  10505. this._cache.renderWidth = undefined;
  10506. this._cache.renderHeight = undefined;
  10507. };
  10508. Camera.prototype._updateCache = function (ignoreParentClass) {
  10509. if (!ignoreParentClass) {
  10510. _super.prototype._updateCache.call(this);
  10511. }
  10512. var engine = this.getEngine();
  10513. this._cache.position.copyFrom(this.position);
  10514. this._cache.upVector.copyFrom(this.upVector);
  10515. this._cache.mode = this.mode;
  10516. this._cache.minZ = this.minZ;
  10517. this._cache.maxZ = this.maxZ;
  10518. this._cache.fov = this.fov;
  10519. this._cache.aspectRatio = engine.getAspectRatio(this);
  10520. this._cache.orthoLeft = this.orthoLeft;
  10521. this._cache.orthoRight = this.orthoRight;
  10522. this._cache.orthoBottom = this.orthoBottom;
  10523. this._cache.orthoTop = this.orthoTop;
  10524. this._cache.renderWidth = engine.getRenderWidth();
  10525. this._cache.renderHeight = engine.getRenderHeight();
  10526. };
  10527. Camera.prototype._updateFromScene = function () {
  10528. this.updateCache();
  10529. this._update();
  10530. };
  10531. // Synchronized
  10532. Camera.prototype._isSynchronized = function () {
  10533. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10534. };
  10535. Camera.prototype._isSynchronizedViewMatrix = function () {
  10536. if (!_super.prototype._isSynchronized.call(this))
  10537. return false;
  10538. return this._cache.position.equals(this.position)
  10539. && this._cache.upVector.equals(this.upVector)
  10540. && this.isSynchronizedWithParent();
  10541. };
  10542. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10543. var check = this._cache.mode === this.mode
  10544. && this._cache.minZ === this.minZ
  10545. && this._cache.maxZ === this.maxZ;
  10546. if (!check) {
  10547. return false;
  10548. }
  10549. var engine = this.getEngine();
  10550. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10551. check = this._cache.fov === this.fov
  10552. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10553. }
  10554. else {
  10555. check = this._cache.orthoLeft === this.orthoLeft
  10556. && this._cache.orthoRight === this.orthoRight
  10557. && this._cache.orthoBottom === this.orthoBottom
  10558. && this._cache.orthoTop === this.orthoTop
  10559. && this._cache.renderWidth === engine.getRenderWidth()
  10560. && this._cache.renderHeight === engine.getRenderHeight();
  10561. }
  10562. return check;
  10563. };
  10564. // Controls
  10565. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10566. };
  10567. Camera.prototype.detachControl = function (element) {
  10568. };
  10569. Camera.prototype._update = function () {
  10570. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10571. this._updateRigCameras();
  10572. }
  10573. this._checkInputs();
  10574. };
  10575. Camera.prototype._checkInputs = function () {
  10576. };
  10577. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10578. if (insertAt === void 0) { insertAt = null; }
  10579. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10580. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10581. return 0;
  10582. }
  10583. if (insertAt == null || insertAt < 0) {
  10584. this._postProcesses.push(postProcess);
  10585. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10586. return this._postProcesses.length - 1;
  10587. }
  10588. var add = 0;
  10589. var i;
  10590. var start;
  10591. if (this._postProcesses[insertAt]) {
  10592. start = this._postProcesses.length - 1;
  10593. for (i = start; i >= insertAt + 1; --i) {
  10594. this._postProcesses[i + 1] = this._postProcesses[i];
  10595. }
  10596. add = 1;
  10597. }
  10598. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10599. if (this._postProcessesTakenIndices[i] < insertAt) {
  10600. continue;
  10601. }
  10602. start = this._postProcessesTakenIndices.length - 1;
  10603. for (var j = start; j >= i; --j) {
  10604. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10605. }
  10606. this._postProcessesTakenIndices[i] = insertAt;
  10607. break;
  10608. }
  10609. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10610. this._postProcessesTakenIndices.push(insertAt);
  10611. }
  10612. var result = insertAt + add;
  10613. this._postProcesses[result] = postProcess;
  10614. return result;
  10615. };
  10616. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10617. if (atIndices === void 0) { atIndices = null; }
  10618. var result = [];
  10619. var i;
  10620. var index;
  10621. if (!atIndices) {
  10622. var length = this._postProcesses.length;
  10623. for (i = 0; i < length; i++) {
  10624. if (this._postProcesses[i] !== postProcess) {
  10625. continue;
  10626. }
  10627. delete this._postProcesses[i];
  10628. index = this._postProcessesTakenIndices.indexOf(i);
  10629. this._postProcessesTakenIndices.splice(index, 1);
  10630. }
  10631. }
  10632. else {
  10633. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10634. for (i = 0; i < atIndices.length; i++) {
  10635. var foundPostProcess = this._postProcesses[atIndices[i]];
  10636. if (foundPostProcess !== postProcess) {
  10637. result.push(i);
  10638. continue;
  10639. }
  10640. delete this._postProcesses[atIndices[i]];
  10641. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10642. this._postProcessesTakenIndices.splice(index, 1);
  10643. }
  10644. }
  10645. return result;
  10646. };
  10647. Camera.prototype.getWorldMatrix = function () {
  10648. if (!this._worldMatrix) {
  10649. this._worldMatrix = BABYLON.Matrix.Identity();
  10650. }
  10651. var viewMatrix = this.getViewMatrix();
  10652. viewMatrix.invertToRef(this._worldMatrix);
  10653. return this._worldMatrix;
  10654. };
  10655. Camera.prototype._getViewMatrix = function () {
  10656. return BABYLON.Matrix.Identity();
  10657. };
  10658. Camera.prototype.getViewMatrix = function (force) {
  10659. this._computedViewMatrix = this._computeViewMatrix(force);
  10660. if (!force && this._isSynchronizedViewMatrix()) {
  10661. return this._computedViewMatrix;
  10662. }
  10663. if (!this.parent || !this.parent.getWorldMatrix) {
  10664. this._globalPosition.copyFrom(this.position);
  10665. }
  10666. else {
  10667. if (!this._worldMatrix) {
  10668. this._worldMatrix = BABYLON.Matrix.Identity();
  10669. }
  10670. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10671. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10672. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10673. this._computedViewMatrix.invert();
  10674. this._markSyncedWithParent();
  10675. }
  10676. this._currentRenderId = this.getScene().getRenderId();
  10677. return this._computedViewMatrix;
  10678. };
  10679. Camera.prototype._computeViewMatrix = function (force) {
  10680. if (!force && this._isSynchronizedViewMatrix()) {
  10681. return this._computedViewMatrix;
  10682. }
  10683. this._computedViewMatrix = this._getViewMatrix();
  10684. this._currentRenderId = this.getScene().getRenderId();
  10685. return this._computedViewMatrix;
  10686. };
  10687. Camera.prototype.getProjectionMatrix = function (force) {
  10688. if (!force && this._isSynchronizedProjectionMatrix()) {
  10689. return this._projectionMatrix;
  10690. }
  10691. var engine = this.getEngine();
  10692. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10693. if (this.minZ <= 0) {
  10694. this.minZ = 0.1;
  10695. }
  10696. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10697. return this._projectionMatrix;
  10698. }
  10699. var halfWidth = engine.getRenderWidth() / 2.0;
  10700. var halfHeight = engine.getRenderHeight() / 2.0;
  10701. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10702. return this._projectionMatrix;
  10703. };
  10704. Camera.prototype.dispose = function () {
  10705. // Animations
  10706. this.getScene().stopAnimation(this);
  10707. // Remove from scene
  10708. this.getScene().removeCamera(this);
  10709. while (this._rigCameras.length > 0) {
  10710. this._rigCameras.pop().dispose();
  10711. }
  10712. // Postprocesses
  10713. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10714. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10715. }
  10716. };
  10717. // ---- Camera rigs section ----
  10718. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10719. while (this._rigCameras.length > 0) {
  10720. this._rigCameras.pop().dispose();
  10721. }
  10722. this.cameraRigMode = mode;
  10723. this._cameraRigParams = {};
  10724. switch (this.cameraRigMode) {
  10725. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10726. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10727. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10728. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10729. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10730. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10731. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10732. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10733. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10734. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10735. break;
  10736. }
  10737. var postProcesses = new Array();
  10738. switch (this.cameraRigMode) {
  10739. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10740. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10741. this._rigCameras[0].isIntermediate = true;
  10742. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10743. postProcesses[1].onApply = function (effect) {
  10744. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10745. };
  10746. break;
  10747. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10748. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10749. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10750. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10751. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10752. var secondCamIndex = 1 - firstCamIndex;
  10753. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10754. this._rigCameras[firstCamIndex].isIntermediate = true;
  10755. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10756. break;
  10757. case Camera.RIG_MODE_VR:
  10758. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10759. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10760. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10761. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10762. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10763. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10764. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10765. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10766. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10767. if (metrics.compensateDistortion) {
  10768. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10769. }
  10770. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10771. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10772. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10773. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10774. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10775. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10776. if (metrics.compensateDistortion) {
  10777. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10778. }
  10779. break;
  10780. }
  10781. this._update();
  10782. };
  10783. Camera.prototype._getVRProjectionMatrix = function () {
  10784. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10785. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10786. return this._projectionMatrix;
  10787. };
  10788. Camera.prototype.setCameraRigParameter = function (name, value) {
  10789. this._cameraRigParams[name] = value;
  10790. //provisionnally:
  10791. if (name === "interaxialDistance") {
  10792. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10793. }
  10794. };
  10795. /**
  10796. * May needs to be overridden by children so sub has required properties to be copied
  10797. */
  10798. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10799. return null;
  10800. };
  10801. /**
  10802. * May needs to be overridden by children
  10803. */
  10804. Camera.prototype._updateRigCameras = function () {
  10805. for (var i = 0; i < this._rigCameras.length; i++) {
  10806. this._rigCameras[i].minZ = this.minZ;
  10807. this._rigCameras[i].maxZ = this.maxZ;
  10808. this._rigCameras[i].fov = this.fov;
  10809. }
  10810. // only update viewport when ANAGLYPH
  10811. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10812. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10813. }
  10814. };
  10815. Camera.prototype.serialize = function () {
  10816. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10817. // Type
  10818. serializationObject.type = this.getTypeName();
  10819. // Parent
  10820. if (this.parent) {
  10821. serializationObject.parentId = this.parent.id;
  10822. }
  10823. // Animations
  10824. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10825. serializationObject.ranges = this.serializeAnimationRanges();
  10826. return serializationObject;
  10827. };
  10828. Camera.prototype.getTypeName = function () {
  10829. return "Camera";
  10830. };
  10831. Camera.prototype.clone = function (name) {
  10832. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10833. };
  10834. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10835. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10836. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10837. switch (type) {
  10838. case "ArcRotateCamera":
  10839. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10840. case "DeviceOrientationCamera":
  10841. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10842. case "FollowCamera":
  10843. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10844. case "ArcFollowCamera":
  10845. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10846. case "GamepadCamera":
  10847. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10848. case "TouchCamera":
  10849. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10850. case "VirtualJoysticksCamera":
  10851. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10852. case "WebVRFreeCamera":
  10853. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10854. case "VRDeviceOrientationFreeCamera":
  10855. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10856. case "AnaglyphArcRotateCamera":
  10857. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10858. case "AnaglyphFreeCamera":
  10859. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10860. case "AnaglyphGamepadCamera":
  10861. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10862. case "AnaglyphUniversalCamera":
  10863. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10864. case "StereoscopicArcRotateCamera":
  10865. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10866. case "StereoscopicFreeCamera":
  10867. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10868. case "StereoscopicGamepadCamera":
  10869. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10870. case "StereoscopicUniversalCamera":
  10871. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10872. case "FreeCamera":
  10873. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10874. default:
  10875. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10876. }
  10877. };
  10878. Camera.Parse = function (parsedCamera, scene) {
  10879. var type = parsedCamera.type;
  10880. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10881. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10882. // Parent
  10883. if (parsedCamera.parentId) {
  10884. camera._waitingParentId = parsedCamera.parentId;
  10885. }
  10886. // Target
  10887. if (parsedCamera.target) {
  10888. if (camera.setTarget) {
  10889. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10890. }
  10891. }
  10892. // Apply 3d rig, when found
  10893. if (parsedCamera.cameraRigMode) {
  10894. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10895. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10896. }
  10897. // Animations
  10898. if (parsedCamera.animations) {
  10899. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10900. var parsedAnimation = parsedCamera.animations[animationIndex];
  10901. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10902. }
  10903. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10904. }
  10905. if (parsedCamera.autoAnimate) {
  10906. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  10907. }
  10908. return camera;
  10909. };
  10910. // Statics
  10911. Camera._PERSPECTIVE_CAMERA = 0;
  10912. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10913. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10914. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10915. Camera._RIG_MODE_NONE = 0;
  10916. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10917. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10918. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10919. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10920. Camera._RIG_MODE_VR = 20;
  10921. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  10922. __decorate([
  10923. BABYLON.serializeAsVector3()
  10924. ], Camera.prototype, "position", void 0);
  10925. __decorate([
  10926. BABYLON.serialize()
  10927. ], Camera.prototype, "upVector", void 0);
  10928. __decorate([
  10929. BABYLON.serialize()
  10930. ], Camera.prototype, "orthoLeft", void 0);
  10931. __decorate([
  10932. BABYLON.serialize()
  10933. ], Camera.prototype, "orthoRight", void 0);
  10934. __decorate([
  10935. BABYLON.serialize()
  10936. ], Camera.prototype, "orthoBottom", void 0);
  10937. __decorate([
  10938. BABYLON.serialize()
  10939. ], Camera.prototype, "orthoTop", void 0);
  10940. __decorate([
  10941. BABYLON.serialize()
  10942. ], Camera.prototype, "fov", void 0);
  10943. __decorate([
  10944. BABYLON.serialize()
  10945. ], Camera.prototype, "minZ", void 0);
  10946. __decorate([
  10947. BABYLON.serialize()
  10948. ], Camera.prototype, "maxZ", void 0);
  10949. __decorate([
  10950. BABYLON.serialize()
  10951. ], Camera.prototype, "inertia", void 0);
  10952. __decorate([
  10953. BABYLON.serialize()
  10954. ], Camera.prototype, "mode", void 0);
  10955. __decorate([
  10956. BABYLON.serialize()
  10957. ], Camera.prototype, "layerMask", void 0);
  10958. __decorate([
  10959. BABYLON.serialize()
  10960. ], Camera.prototype, "fovMode", void 0);
  10961. __decorate([
  10962. BABYLON.serialize()
  10963. ], Camera.prototype, "cameraRigMode", void 0);
  10964. __decorate([
  10965. BABYLON.serialize()
  10966. ], Camera.prototype, "interaxialDistance", void 0);
  10967. __decorate([
  10968. BABYLON.serialize()
  10969. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10970. return Camera;
  10971. })(BABYLON.Node);
  10972. BABYLON.Camera = Camera;
  10973. })(BABYLON || (BABYLON = {}));
  10974. var BABYLON;
  10975. (function (BABYLON) {
  10976. var TargetCamera = (function (_super) {
  10977. __extends(TargetCamera, _super);
  10978. function TargetCamera(name, position, scene) {
  10979. _super.call(this, name, position, scene);
  10980. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10981. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10982. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10983. this.speed = 2.0;
  10984. this.noRotationConstraint = false;
  10985. this.lockedTarget = null;
  10986. this._currentTarget = BABYLON.Vector3.Zero();
  10987. this._viewMatrix = BABYLON.Matrix.Zero();
  10988. this._camMatrix = BABYLON.Matrix.Zero();
  10989. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10990. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10991. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10992. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10993. this._lookAtTemp = BABYLON.Matrix.Zero();
  10994. this._tempMatrix = BABYLON.Matrix.Zero();
  10995. }
  10996. TargetCamera.prototype.getFrontPosition = function (distance) {
  10997. var direction = this.getTarget().subtract(this.position);
  10998. direction.normalize();
  10999. direction.scaleInPlace(distance);
  11000. return this.globalPosition.add(direction);
  11001. };
  11002. TargetCamera.prototype._getLockedTargetPosition = function () {
  11003. if (!this.lockedTarget) {
  11004. return null;
  11005. }
  11006. return this.lockedTarget.position || this.lockedTarget;
  11007. };
  11008. // Cache
  11009. TargetCamera.prototype._initCache = function () {
  11010. _super.prototype._initCache.call(this);
  11011. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11012. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11013. };
  11014. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11015. if (!ignoreParentClass) {
  11016. _super.prototype._updateCache.call(this);
  11017. }
  11018. var lockedTargetPosition = this._getLockedTargetPosition();
  11019. if (!lockedTargetPosition) {
  11020. this._cache.lockedTarget = null;
  11021. }
  11022. else {
  11023. if (!this._cache.lockedTarget) {
  11024. this._cache.lockedTarget = lockedTargetPosition.clone();
  11025. }
  11026. else {
  11027. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11028. }
  11029. }
  11030. this._cache.rotation.copyFrom(this.rotation);
  11031. };
  11032. // Synchronized
  11033. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11034. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11035. return false;
  11036. }
  11037. var lockedTargetPosition = this._getLockedTargetPosition();
  11038. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11039. && this._cache.rotation.equals(this.rotation);
  11040. };
  11041. // Methods
  11042. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11043. var engine = this.getEngine();
  11044. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11045. };
  11046. // Target
  11047. TargetCamera.prototype.setTarget = function (target) {
  11048. this.upVector.normalize();
  11049. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11050. this._camMatrix.invert();
  11051. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11052. var vDir = target.subtract(this.position);
  11053. if (vDir.x >= 0.0) {
  11054. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11055. }
  11056. else {
  11057. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11058. }
  11059. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11060. if (isNaN(this.rotation.x)) {
  11061. this.rotation.x = 0;
  11062. }
  11063. if (isNaN(this.rotation.y)) {
  11064. this.rotation.y = 0;
  11065. }
  11066. if (isNaN(this.rotation.z)) {
  11067. this.rotation.z = 0;
  11068. }
  11069. };
  11070. TargetCamera.prototype.getTarget = function () {
  11071. return this._currentTarget;
  11072. };
  11073. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11074. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11075. };
  11076. TargetCamera.prototype._updatePosition = function () {
  11077. this.position.addInPlace(this.cameraDirection);
  11078. };
  11079. TargetCamera.prototype._checkInputs = function () {
  11080. var needToMove = this._decideIfNeedsToMove();
  11081. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11082. // Move
  11083. if (needToMove) {
  11084. this._updatePosition();
  11085. }
  11086. // Rotate
  11087. if (needToRotate) {
  11088. this.rotation.x += this.cameraRotation.x;
  11089. this.rotation.y += this.cameraRotation.y;
  11090. if (!this.noRotationConstraint) {
  11091. var limit = (Math.PI / 2) * 0.95;
  11092. if (this.rotation.x > limit)
  11093. this.rotation.x = limit;
  11094. if (this.rotation.x < -limit)
  11095. this.rotation.x = -limit;
  11096. }
  11097. }
  11098. // Inertia
  11099. if (needToMove) {
  11100. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  11101. this.cameraDirection.x = 0;
  11102. }
  11103. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  11104. this.cameraDirection.y = 0;
  11105. }
  11106. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  11107. this.cameraDirection.z = 0;
  11108. }
  11109. this.cameraDirection.scaleInPlace(this.inertia);
  11110. }
  11111. if (needToRotate) {
  11112. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  11113. this.cameraRotation.x = 0;
  11114. }
  11115. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  11116. this.cameraRotation.y = 0;
  11117. }
  11118. this.cameraRotation.scaleInPlace(this.inertia);
  11119. }
  11120. _super.prototype._checkInputs.call(this);
  11121. };
  11122. TargetCamera.prototype._getViewMatrix = function () {
  11123. if (!this.lockedTarget) {
  11124. // Compute
  11125. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11126. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11127. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11128. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11129. this._lookAtTemp.invert();
  11130. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11131. }
  11132. else {
  11133. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11134. }
  11135. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11136. // Computing target and final matrix
  11137. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11138. }
  11139. else {
  11140. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11141. }
  11142. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11143. return this._viewMatrix;
  11144. };
  11145. TargetCamera.prototype._getVRViewMatrix = function () {
  11146. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11147. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11148. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11149. // Computing target and final matrix
  11150. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11151. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11152. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11153. return this._viewMatrix;
  11154. };
  11155. /**
  11156. * @override
  11157. * Override Camera.createRigCamera
  11158. */
  11159. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11160. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11161. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11162. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11163. rigCamera._cameraRigParams = {};
  11164. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11165. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11166. }
  11167. return rigCamera;
  11168. }
  11169. return null;
  11170. };
  11171. /**
  11172. * @override
  11173. * Override Camera._updateRigCameras
  11174. */
  11175. TargetCamera.prototype._updateRigCameras = function () {
  11176. switch (this.cameraRigMode) {
  11177. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11181. case BABYLON.Camera.RIG_MODE_VR:
  11182. var camLeft = this._rigCameras[0];
  11183. var camRight = this._rigCameras[1];
  11184. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11185. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11186. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11187. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11188. camLeft.position.copyFrom(this.position);
  11189. camRight.position.copyFrom(this.position);
  11190. }
  11191. else {
  11192. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11193. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11194. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11195. camLeft.setTarget(this.getTarget());
  11196. camRight.setTarget(this.getTarget());
  11197. }
  11198. break;
  11199. }
  11200. _super.prototype._updateRigCameras.call(this);
  11201. };
  11202. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11203. if (!this._rigCamTransformMatrix) {
  11204. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11205. }
  11206. var target = this.getTarget();
  11207. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11208. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11209. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11210. };
  11211. TargetCamera.prototype.getTypeName = function () {
  11212. return "TargetCamera";
  11213. };
  11214. __decorate([
  11215. BABYLON.serializeAsVector3()
  11216. ], TargetCamera.prototype, "rotation", void 0);
  11217. __decorate([
  11218. BABYLON.serialize()
  11219. ], TargetCamera.prototype, "speed", void 0);
  11220. __decorate([
  11221. BABYLON.serializeAsMeshReference("lockedTargetId")
  11222. ], TargetCamera.prototype, "lockedTarget", void 0);
  11223. return TargetCamera;
  11224. })(BABYLON.Camera);
  11225. BABYLON.TargetCamera = TargetCamera;
  11226. })(BABYLON || (BABYLON = {}));
  11227. var BABYLON;
  11228. (function (BABYLON) {
  11229. var FreeCamera = (function (_super) {
  11230. __extends(FreeCamera, _super);
  11231. function FreeCamera(name, position, scene) {
  11232. var _this = this;
  11233. _super.call(this, name, position, scene);
  11234. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11235. this.keysUp = [38];
  11236. this.keysDown = [40];
  11237. this.keysLeft = [37];
  11238. this.keysRight = [39];
  11239. this.checkCollisions = false;
  11240. this.applyGravity = false;
  11241. this.angularSensibility = 2000.0;
  11242. this._keys = [];
  11243. this._collider = new BABYLON.Collider();
  11244. this._needMoveForGravity = false;
  11245. this._oldPosition = BABYLON.Vector3.Zero();
  11246. this._diffPosition = BABYLON.Vector3.Zero();
  11247. this._newPosition = BABYLON.Vector3.Zero();
  11248. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11249. if (collidedMesh === void 0) { collidedMesh = null; }
  11250. //TODO move this to the collision coordinator!
  11251. if (_this.getScene().workerCollisions)
  11252. newPosition.multiplyInPlace(_this._collider.radius);
  11253. var updatePosition = function (newPos) {
  11254. _this._newPosition.copyFrom(newPos);
  11255. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11256. var oldPosition = _this.position.clone();
  11257. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11258. _this.position.addInPlace(_this._diffPosition);
  11259. if (_this.onCollide && collidedMesh) {
  11260. _this.onCollide(collidedMesh);
  11261. }
  11262. }
  11263. };
  11264. updatePosition(newPosition);
  11265. };
  11266. }
  11267. FreeCamera.prototype._onLostFocus = function (e) {
  11268. this._keys = [];
  11269. };
  11270. // Controls
  11271. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11272. var _this = this;
  11273. var previousPosition;
  11274. var engine = this.getEngine();
  11275. if (this._attachedElement) {
  11276. return;
  11277. }
  11278. this._attachedElement = element;
  11279. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11280. if (this._onMouseDown === undefined) {
  11281. this._onMouseDown = function (evt) {
  11282. previousPosition = {
  11283. x: evt.clientX,
  11284. y: evt.clientY
  11285. };
  11286. if (!noPreventDefault) {
  11287. evt.preventDefault();
  11288. }
  11289. };
  11290. this._onMouseUp = function (evt) {
  11291. previousPosition = null;
  11292. if (!noPreventDefault) {
  11293. evt.preventDefault();
  11294. }
  11295. };
  11296. this._onMouseOut = function (evt) {
  11297. previousPosition = null;
  11298. _this._keys = [];
  11299. if (!noPreventDefault) {
  11300. evt.preventDefault();
  11301. }
  11302. };
  11303. this._onMouseMove = function (evt) {
  11304. if (!previousPosition && !engine.isPointerLock) {
  11305. return;
  11306. }
  11307. var offsetX;
  11308. var offsetY;
  11309. if (!engine.isPointerLock) {
  11310. offsetX = evt.clientX - previousPosition.x;
  11311. offsetY = evt.clientY - previousPosition.y;
  11312. }
  11313. else {
  11314. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11315. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11316. }
  11317. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11318. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11319. previousPosition = {
  11320. x: evt.clientX,
  11321. y: evt.clientY
  11322. };
  11323. if (!noPreventDefault) {
  11324. evt.preventDefault();
  11325. }
  11326. };
  11327. this._onKeyDown = function (evt) {
  11328. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11329. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11330. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11331. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11332. var index = _this._keys.indexOf(evt.keyCode);
  11333. if (index === -1) {
  11334. _this._keys.push(evt.keyCode);
  11335. }
  11336. if (!noPreventDefault) {
  11337. evt.preventDefault();
  11338. }
  11339. }
  11340. };
  11341. this._onKeyUp = function (evt) {
  11342. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11343. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11344. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11345. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11346. var index = _this._keys.indexOf(evt.keyCode);
  11347. if (index >= 0) {
  11348. _this._keys.splice(index, 1);
  11349. }
  11350. if (!noPreventDefault) {
  11351. evt.preventDefault();
  11352. }
  11353. }
  11354. };
  11355. this._reset = function () {
  11356. _this._keys = [];
  11357. previousPosition = null;
  11358. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11359. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11360. };
  11361. }
  11362. element.addEventListener("mousedown", this._onMouseDown, false);
  11363. element.addEventListener("mouseup", this._onMouseUp, false);
  11364. element.addEventListener("mouseout", this._onMouseOut, false);
  11365. element.addEventListener("mousemove", this._onMouseMove, false);
  11366. BABYLON.Tools.RegisterTopRootEvents([
  11367. { name: "keydown", handler: this._onKeyDown },
  11368. { name: "keyup", handler: this._onKeyUp },
  11369. { name: "blur", handler: this._onLostFocus }
  11370. ]);
  11371. };
  11372. FreeCamera.prototype.detachControl = function (element) {
  11373. if (this._attachedElement !== element) {
  11374. return;
  11375. }
  11376. element.removeEventListener("mousedown", this._onMouseDown);
  11377. element.removeEventListener("mouseup", this._onMouseUp);
  11378. element.removeEventListener("mouseout", this._onMouseOut);
  11379. element.removeEventListener("mousemove", this._onMouseMove);
  11380. BABYLON.Tools.UnregisterTopRootEvents([
  11381. { name: "keydown", handler: this._onKeyDown },
  11382. { name: "keyup", handler: this._onKeyUp },
  11383. { name: "blur", handler: this._onLostFocus }
  11384. ]);
  11385. this._attachedElement = null;
  11386. if (this._reset) {
  11387. this._reset();
  11388. }
  11389. };
  11390. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11391. var globalPosition;
  11392. if (this.parent) {
  11393. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11394. }
  11395. else {
  11396. globalPosition = this.position;
  11397. }
  11398. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11399. this._collider.radius = this.ellipsoid;
  11400. //no need for clone, as long as gravity is not on.
  11401. var actualVelocity = velocity;
  11402. //add gravity to the velocity to prevent the dual-collision checking
  11403. if (this.applyGravity) {
  11404. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11405. actualVelocity = velocity.add(this.getScene().gravity);
  11406. }
  11407. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11408. };
  11409. FreeCamera.prototype._checkInputs = function () {
  11410. if (!this._localDirection) {
  11411. this._localDirection = BABYLON.Vector3.Zero();
  11412. this._transformedDirection = BABYLON.Vector3.Zero();
  11413. }
  11414. // Keyboard
  11415. for (var index = 0; index < this._keys.length; index++) {
  11416. var keyCode = this._keys[index];
  11417. var speed = this._computeLocalCameraSpeed();
  11418. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11419. this._localDirection.copyFromFloats(-speed, 0, 0);
  11420. }
  11421. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11422. this._localDirection.copyFromFloats(0, 0, speed);
  11423. }
  11424. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11425. this._localDirection.copyFromFloats(speed, 0, 0);
  11426. }
  11427. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11428. this._localDirection.copyFromFloats(0, 0, -speed);
  11429. }
  11430. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11431. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11432. this.cameraDirection.addInPlace(this._transformedDirection);
  11433. }
  11434. _super.prototype._checkInputs.call(this);
  11435. };
  11436. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11437. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11438. };
  11439. FreeCamera.prototype._updatePosition = function () {
  11440. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11441. this._collideWithWorld(this.cameraDirection);
  11442. }
  11443. else {
  11444. this.position.addInPlace(this.cameraDirection);
  11445. }
  11446. };
  11447. FreeCamera.prototype.getTypeName = function () {
  11448. return "FreeCamera";
  11449. };
  11450. __decorate([
  11451. BABYLON.serializeAsVector3()
  11452. ], FreeCamera.prototype, "ellipsoid", void 0);
  11453. __decorate([
  11454. BABYLON.serialize()
  11455. ], FreeCamera.prototype, "keysUp", void 0);
  11456. __decorate([
  11457. BABYLON.serialize()
  11458. ], FreeCamera.prototype, "keysDown", void 0);
  11459. __decorate([
  11460. BABYLON.serialize()
  11461. ], FreeCamera.prototype, "keysLeft", void 0);
  11462. __decorate([
  11463. BABYLON.serialize()
  11464. ], FreeCamera.prototype, "keysRight", void 0);
  11465. __decorate([
  11466. BABYLON.serialize()
  11467. ], FreeCamera.prototype, "checkCollisions", void 0);
  11468. __decorate([
  11469. BABYLON.serialize()
  11470. ], FreeCamera.prototype, "applyGravity", void 0);
  11471. __decorate([
  11472. BABYLON.serialize()
  11473. ], FreeCamera.prototype, "angularSensibility", void 0);
  11474. return FreeCamera;
  11475. })(BABYLON.TargetCamera);
  11476. BABYLON.FreeCamera = FreeCamera;
  11477. })(BABYLON || (BABYLON = {}));
  11478. var BABYLON;
  11479. (function (BABYLON) {
  11480. var FollowCamera = (function (_super) {
  11481. __extends(FollowCamera, _super);
  11482. function FollowCamera(name, position, scene, target) {
  11483. _super.call(this, name, position, scene);
  11484. this.radius = 12;
  11485. this.rotationOffset = 0;
  11486. this.heightOffset = 4;
  11487. this.cameraAcceleration = 0.05;
  11488. this.maxCameraSpeed = 20;
  11489. this.target = target;
  11490. }
  11491. FollowCamera.prototype.getRadians = function (degrees) {
  11492. return degrees * Math.PI / 180;
  11493. };
  11494. FollowCamera.prototype.follow = function (cameraTarget) {
  11495. if (!cameraTarget)
  11496. return;
  11497. var yRotation;
  11498. if (cameraTarget.rotationQuaternion) {
  11499. var rotMatrix = new BABYLON.Matrix();
  11500. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11501. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11502. }
  11503. else {
  11504. yRotation = cameraTarget.rotation.y;
  11505. }
  11506. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11507. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11508. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11509. var dx = targetX - this.position.x;
  11510. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11511. var dz = (targetZ) - this.position.z;
  11512. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11513. var vy = dy * this.cameraAcceleration;
  11514. var vz = dz * this.cameraAcceleration * 2;
  11515. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11516. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11517. }
  11518. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11519. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11520. }
  11521. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11522. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11523. }
  11524. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11525. this.setTarget(cameraTarget.position);
  11526. };
  11527. FollowCamera.prototype._checkInputs = function () {
  11528. _super.prototype._checkInputs.call(this);
  11529. this.follow(this.target);
  11530. };
  11531. FollowCamera.prototype.getTypeName = function () {
  11532. return "FollowCamera";
  11533. };
  11534. __decorate([
  11535. BABYLON.serialize()
  11536. ], FollowCamera.prototype, "radius", void 0);
  11537. __decorate([
  11538. BABYLON.serialize()
  11539. ], FollowCamera.prototype, "rotationOffset", void 0);
  11540. __decorate([
  11541. BABYLON.serialize()
  11542. ], FollowCamera.prototype, "heightOffset", void 0);
  11543. __decorate([
  11544. BABYLON.serialize()
  11545. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11546. __decorate([
  11547. BABYLON.serialize()
  11548. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11549. __decorate([
  11550. BABYLON.serializeAsMeshReference("lockedTargetId")
  11551. ], FollowCamera.prototype, "target", void 0);
  11552. return FollowCamera;
  11553. })(BABYLON.TargetCamera);
  11554. BABYLON.FollowCamera = FollowCamera;
  11555. var ArcFollowCamera = (function (_super) {
  11556. __extends(ArcFollowCamera, _super);
  11557. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11558. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11559. this.alpha = alpha;
  11560. this.beta = beta;
  11561. this.radius = radius;
  11562. this.target = target;
  11563. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11564. this.follow();
  11565. }
  11566. ArcFollowCamera.prototype.follow = function () {
  11567. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11568. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11569. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11570. this.position = this.target.position.add(this._cartesianCoordinates);
  11571. this.setTarget(this.target.position);
  11572. };
  11573. ArcFollowCamera.prototype._checkInputs = function () {
  11574. _super.prototype._checkInputs.call(this);
  11575. this.follow();
  11576. };
  11577. ArcFollowCamera.prototype.getTypeName = function () {
  11578. return "ArcFollowCamera";
  11579. };
  11580. return ArcFollowCamera;
  11581. })(BABYLON.TargetCamera);
  11582. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11583. })(BABYLON || (BABYLON = {}));
  11584. var BABYLON;
  11585. (function (BABYLON) {
  11586. // We're mainly based on the logic defined into the FreeCamera code
  11587. var TouchCamera = (function (_super) {
  11588. __extends(TouchCamera, _super);
  11589. function TouchCamera(name, position, scene) {
  11590. _super.call(this, name, position, scene);
  11591. this._offsetX = null;
  11592. this._offsetY = null;
  11593. this._pointerCount = 0;
  11594. this._pointerPressed = [];
  11595. this.touchAngularSensibility = 200000.0;
  11596. this.touchMoveSensibility = 250.0;
  11597. }
  11598. TouchCamera.prototype._onLostFocus = function (e) {
  11599. this._offsetX = null;
  11600. this._offsetY = null;
  11601. _super.prototype._onLostFocus.call(this, e);
  11602. };
  11603. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11604. var _this = this;
  11605. var previousPosition;
  11606. if (this._attachedCanvas) {
  11607. return;
  11608. }
  11609. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11610. if (this._onPointerDown === undefined) {
  11611. this._onPointerDown = function (evt) {
  11612. if (evt.pointerType === "mouse") {
  11613. return;
  11614. }
  11615. if (!noPreventDefault) {
  11616. evt.preventDefault();
  11617. }
  11618. _this._pointerPressed.push(evt.pointerId);
  11619. if (_this._pointerPressed.length !== 1) {
  11620. return;
  11621. }
  11622. previousPosition = {
  11623. x: evt.clientX,
  11624. y: evt.clientY
  11625. };
  11626. };
  11627. this._onPointerUp = function (evt) {
  11628. if (evt.pointerType === "mouse") {
  11629. return;
  11630. }
  11631. if (!noPreventDefault) {
  11632. evt.preventDefault();
  11633. }
  11634. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11635. if (index === -1) {
  11636. return;
  11637. }
  11638. _this._pointerPressed.splice(index, 1);
  11639. if (index != 0) {
  11640. return;
  11641. }
  11642. previousPosition = null;
  11643. _this._offsetX = null;
  11644. _this._offsetY = null;
  11645. };
  11646. this._onPointerMove = function (evt) {
  11647. if (evt.pointerType === "mouse") {
  11648. return;
  11649. }
  11650. if (!noPreventDefault) {
  11651. evt.preventDefault();
  11652. }
  11653. if (!previousPosition) {
  11654. return;
  11655. }
  11656. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11657. if (index != 0) {
  11658. return;
  11659. }
  11660. _this._offsetX = evt.clientX - previousPosition.x;
  11661. _this._offsetY = -(evt.clientY - previousPosition.y);
  11662. };
  11663. }
  11664. canvas.addEventListener("pointerdown", this._onPointerDown);
  11665. canvas.addEventListener("pointerup", this._onPointerUp);
  11666. canvas.addEventListener("pointerout", this._onPointerUp);
  11667. canvas.addEventListener("pointermove", this._onPointerMove);
  11668. _super.prototype.attachControl.call(this, canvas);
  11669. };
  11670. TouchCamera.prototype.detachControl = function (canvas) {
  11671. if (this._attachedCanvas !== canvas) {
  11672. return;
  11673. }
  11674. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11675. canvas.removeEventListener("pointerup", this._onPointerUp);
  11676. canvas.removeEventListener("pointerout", this._onPointerUp);
  11677. canvas.removeEventListener("pointermove", this._onPointerMove);
  11678. _super.prototype.detachControl.call(this, canvas);
  11679. };
  11680. TouchCamera.prototype._checkInputs = function () {
  11681. if (this._offsetX) {
  11682. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11683. if (this._pointerPressed.length > 1) {
  11684. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11685. }
  11686. else {
  11687. var speed = this._computeLocalCameraSpeed();
  11688. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11689. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11690. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11691. }
  11692. }
  11693. _super.prototype._checkInputs.call(this);
  11694. };
  11695. TouchCamera.prototype.getTypeName = function () {
  11696. return "TouchCamera";
  11697. };
  11698. __decorate([
  11699. BABYLON.serialize()
  11700. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11701. __decorate([
  11702. BABYLON.serialize()
  11703. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11704. return TouchCamera;
  11705. })(BABYLON.FreeCamera);
  11706. BABYLON.TouchCamera = TouchCamera;
  11707. })(BABYLON || (BABYLON = {}));
  11708. var BABYLON;
  11709. (function (BABYLON) {
  11710. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11711. var ArcRotateCamera = (function (_super) {
  11712. __extends(ArcRotateCamera, _super);
  11713. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11714. var _this = this;
  11715. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11716. this.inertialAlphaOffset = 0;
  11717. this.inertialBetaOffset = 0;
  11718. this.inertialRadiusOffset = 0;
  11719. this.lowerAlphaLimit = null;
  11720. this.upperAlphaLimit = null;
  11721. this.lowerBetaLimit = 0.01;
  11722. this.upperBetaLimit = Math.PI;
  11723. this.lowerRadiusLimit = null;
  11724. this.upperRadiusLimit = null;
  11725. this.angularSensibilityX = 1000.0;
  11726. this.angularSensibilityY = 1000.0;
  11727. this.wheelPrecision = 3.0;
  11728. this.pinchPrecision = 2.0;
  11729. this.panningSensibility = 50.0;
  11730. this.inertialPanningX = 0;
  11731. this.inertialPanningY = 0;
  11732. this.keysUp = [38];
  11733. this.keysDown = [40];
  11734. this.keysLeft = [37];
  11735. this.keysRight = [39];
  11736. this.zoomOnFactor = 1;
  11737. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11738. this.pinchInwards = true;
  11739. this.allowUpsideDown = true;
  11740. this._keys = [];
  11741. this._viewMatrix = new BABYLON.Matrix();
  11742. // Panning
  11743. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11744. this._isRightClick = false;
  11745. this._isCtrlPushed = false;
  11746. this.checkCollisions = false;
  11747. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11748. this._collider = new BABYLON.Collider();
  11749. this._previousPosition = BABYLON.Vector3.Zero();
  11750. this._collisionVelocity = BABYLON.Vector3.Zero();
  11751. this._newPosition = BABYLON.Vector3.Zero();
  11752. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11753. if (collidedMesh === void 0) { collidedMesh = null; }
  11754. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11755. newPosition.multiplyInPlace(_this._collider.radius);
  11756. }
  11757. if (!collidedMesh) {
  11758. _this._previousPosition.copyFrom(_this.position);
  11759. }
  11760. else {
  11761. _this.setPosition(newPosition);
  11762. if (_this.onCollide) {
  11763. _this.onCollide(collidedMesh);
  11764. }
  11765. }
  11766. // Recompute because of constraints
  11767. var cosa = Math.cos(_this.alpha);
  11768. var sina = Math.sin(_this.alpha);
  11769. var cosb = Math.cos(_this.beta);
  11770. var sinb = Math.sin(_this.beta);
  11771. if (sinb === 0) {
  11772. sinb = 0.0001;
  11773. }
  11774. var target = _this._getTargetPosition();
  11775. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11776. _this.position.copyFrom(_this._newPosition);
  11777. var up = _this.upVector;
  11778. if (_this.allowUpsideDown && _this.beta < 0) {
  11779. up = up.clone();
  11780. up = up.negate();
  11781. }
  11782. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11783. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11784. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11785. _this._collisionTriggered = false;
  11786. };
  11787. if (!target) {
  11788. this.target = BABYLON.Vector3.Zero();
  11789. }
  11790. else {
  11791. this.target = target;
  11792. }
  11793. this.alpha = alpha;
  11794. this.beta = beta;
  11795. this.radius = radius;
  11796. this.getViewMatrix();
  11797. }
  11798. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11799. //deprecated angularSensibility support
  11800. get: function () {
  11801. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11802. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11803. },
  11804. //deprecated angularSensibility support
  11805. set: function (value) {
  11806. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11807. this.angularSensibilityX = value;
  11808. this.angularSensibilityY = value;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. // Cache
  11814. ArcRotateCamera.prototype._initCache = function () {
  11815. _super.prototype._initCache.call(this);
  11816. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11817. this._cache.alpha = undefined;
  11818. this._cache.beta = undefined;
  11819. this._cache.radius = undefined;
  11820. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11821. };
  11822. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11823. if (!ignoreParentClass) {
  11824. _super.prototype._updateCache.call(this);
  11825. }
  11826. this._cache.target.copyFrom(this._getTargetPosition());
  11827. this._cache.alpha = this.alpha;
  11828. this._cache.beta = this.beta;
  11829. this._cache.radius = this.radius;
  11830. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11831. };
  11832. ArcRotateCamera.prototype._getTargetPosition = function () {
  11833. if (this.target.getAbsolutePosition) {
  11834. return this.target.getAbsolutePosition();
  11835. }
  11836. return this.target;
  11837. };
  11838. // Synchronized
  11839. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11840. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11841. return false;
  11842. return this._cache.target.equals(this.target)
  11843. && this._cache.alpha === this.alpha
  11844. && this._cache.beta === this.beta
  11845. && this._cache.radius === this.radius
  11846. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11847. };
  11848. // Methods
  11849. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11850. var _this = this;
  11851. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11852. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11853. var previousPinchDistance = 0;
  11854. var pointers = new BABYLON.SmartCollection();
  11855. if (this._attachedElement) {
  11856. return;
  11857. }
  11858. this._attachedElement = element;
  11859. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11860. var engine = this.getEngine();
  11861. if (this._onPointerDown === undefined) {
  11862. this._onPointerDown = function (evt) {
  11863. // Manage panning with right click
  11864. _this._isRightClick = evt.button === 2;
  11865. // manage pointers
  11866. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11867. cacheSoloPointer = pointers.item(evt.pointerId);
  11868. if (!noPreventDefault) {
  11869. evt.preventDefault();
  11870. }
  11871. };
  11872. this._onPointerUp = function (evt) {
  11873. cacheSoloPointer = null;
  11874. previousPinchDistance = 0;
  11875. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11876. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11877. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11878. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11879. pointers.empty();
  11880. if (!noPreventDefault) {
  11881. evt.preventDefault();
  11882. }
  11883. };
  11884. this._onContextMenu = function (evt) {
  11885. evt.preventDefault();
  11886. };
  11887. this._onPointerMove = function (evt) {
  11888. if (!noPreventDefault) {
  11889. evt.preventDefault();
  11890. }
  11891. switch (pointers.count) {
  11892. case 1:
  11893. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11894. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11895. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11896. }
  11897. else {
  11898. var offsetX = evt.clientX - cacheSoloPointer.x;
  11899. var offsetY = evt.clientY - cacheSoloPointer.y;
  11900. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11901. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11902. }
  11903. cacheSoloPointer.x = evt.clientX;
  11904. cacheSoloPointer.y = evt.clientY;
  11905. break;
  11906. case 2:
  11907. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11908. pointers.item(evt.pointerId).x = evt.clientX;
  11909. pointers.item(evt.pointerId).y = evt.clientY;
  11910. var direction = _this.pinchInwards ? 1 : -1;
  11911. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11912. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11913. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11914. if (previousPinchDistance === 0) {
  11915. previousPinchDistance = pinchSquaredDistance;
  11916. return;
  11917. }
  11918. if (pinchSquaredDistance !== previousPinchDistance) {
  11919. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11920. previousPinchDistance = pinchSquaredDistance;
  11921. }
  11922. break;
  11923. default:
  11924. if (pointers.item(evt.pointerId)) {
  11925. pointers.item(evt.pointerId).x = evt.clientX;
  11926. pointers.item(evt.pointerId).y = evt.clientY;
  11927. }
  11928. }
  11929. };
  11930. this._onMouseMove = function (evt) {
  11931. if (!engine.isPointerLock) {
  11932. return;
  11933. }
  11934. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11935. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11936. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11937. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11938. if (!noPreventDefault) {
  11939. evt.preventDefault();
  11940. }
  11941. };
  11942. this._wheel = function (event) {
  11943. var delta = 0;
  11944. if (event.wheelDelta) {
  11945. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11946. }
  11947. else if (event.detail) {
  11948. delta = -event.detail / _this.wheelPrecision;
  11949. }
  11950. if (delta)
  11951. _this.inertialRadiusOffset += delta;
  11952. if (event.preventDefault) {
  11953. if (!noPreventDefault) {
  11954. event.preventDefault();
  11955. }
  11956. }
  11957. };
  11958. this._onKeyDown = function (evt) {
  11959. _this._isCtrlPushed = evt.ctrlKey;
  11960. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11961. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11962. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11963. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11964. var index = _this._keys.indexOf(evt.keyCode);
  11965. if (index === -1) {
  11966. _this._keys.push(evt.keyCode);
  11967. }
  11968. if (evt.preventDefault) {
  11969. if (!noPreventDefault) {
  11970. evt.preventDefault();
  11971. }
  11972. }
  11973. }
  11974. };
  11975. this._onKeyUp = function (evt) {
  11976. _this._isCtrlPushed = evt.ctrlKey;
  11977. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11978. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11979. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11980. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11981. var index = _this._keys.indexOf(evt.keyCode);
  11982. if (index >= 0) {
  11983. _this._keys.splice(index, 1);
  11984. }
  11985. if (evt.preventDefault) {
  11986. if (!noPreventDefault) {
  11987. evt.preventDefault();
  11988. }
  11989. }
  11990. }
  11991. };
  11992. this._onLostFocus = function () {
  11993. _this._keys = [];
  11994. pointers.empty();
  11995. previousPinchDistance = 0;
  11996. cacheSoloPointer = null;
  11997. };
  11998. this._onGestureStart = function (e) {
  11999. if (window.MSGesture === undefined) {
  12000. return;
  12001. }
  12002. if (!_this._MSGestureHandler) {
  12003. _this._MSGestureHandler = new MSGesture();
  12004. _this._MSGestureHandler.target = element;
  12005. }
  12006. _this._MSGestureHandler.addPointer(e.pointerId);
  12007. };
  12008. this._onGesture = function (e) {
  12009. _this.radius *= e.scale;
  12010. if (e.preventDefault) {
  12011. if (!noPreventDefault) {
  12012. e.stopPropagation();
  12013. e.preventDefault();
  12014. }
  12015. }
  12016. };
  12017. this._reset = function () {
  12018. _this._keys = [];
  12019. _this.inertialAlphaOffset = 0;
  12020. _this.inertialBetaOffset = 0;
  12021. _this.inertialRadiusOffset = 0;
  12022. pointers.empty();
  12023. previousPinchDistance = 0;
  12024. cacheSoloPointer = null;
  12025. };
  12026. }
  12027. if (!useCtrlForPanning) {
  12028. element.addEventListener("contextmenu", this._onContextMenu, false);
  12029. }
  12030. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12031. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12032. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12033. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12034. element.addEventListener("mousemove", this._onMouseMove, false);
  12035. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12036. element.addEventListener("MSGestureChange", this._onGesture, false);
  12037. element.addEventListener('mousewheel', this._wheel, false);
  12038. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12039. BABYLON.Tools.RegisterTopRootEvents([
  12040. { name: "keydown", handler: this._onKeyDown },
  12041. { name: "keyup", handler: this._onKeyUp },
  12042. { name: "blur", handler: this._onLostFocus }
  12043. ]);
  12044. };
  12045. ArcRotateCamera.prototype.detachControl = function (element) {
  12046. if (this._attachedElement !== element) {
  12047. return;
  12048. }
  12049. element.removeEventListener("contextmenu", this._onContextMenu);
  12050. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12051. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12052. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12053. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12054. element.removeEventListener("mousemove", this._onMouseMove);
  12055. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12056. element.removeEventListener("MSGestureChange", this._onGesture);
  12057. element.removeEventListener('mousewheel', this._wheel);
  12058. element.removeEventListener('DOMMouseScroll', this._wheel);
  12059. BABYLON.Tools.UnregisterTopRootEvents([
  12060. { name: "keydown", handler: this._onKeyDown },
  12061. { name: "keyup", handler: this._onKeyUp },
  12062. { name: "blur", handler: this._onLostFocus }
  12063. ]);
  12064. this._MSGestureHandler = null;
  12065. this._attachedElement = null;
  12066. if (this._reset) {
  12067. this._reset();
  12068. }
  12069. };
  12070. ArcRotateCamera.prototype._checkInputs = function () {
  12071. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12072. if (this._collisionTriggered) {
  12073. return;
  12074. }
  12075. // Keyboard
  12076. for (var index = 0; index < this._keys.length; index++) {
  12077. var keyCode = this._keys[index];
  12078. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12079. this.inertialAlphaOffset -= 0.01;
  12080. }
  12081. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12082. this.inertialBetaOffset -= 0.01;
  12083. }
  12084. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12085. this.inertialAlphaOffset += 0.01;
  12086. }
  12087. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12088. this.inertialBetaOffset += 0.01;
  12089. }
  12090. }
  12091. // Inertia
  12092. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12093. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12094. this.beta += this.inertialBetaOffset;
  12095. this.radius -= this.inertialRadiusOffset;
  12096. this.inertialAlphaOffset *= this.inertia;
  12097. this.inertialBetaOffset *= this.inertia;
  12098. this.inertialRadiusOffset *= this.inertia;
  12099. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  12100. this.inertialAlphaOffset = 0;
  12101. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  12102. this.inertialBetaOffset = 0;
  12103. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  12104. this.inertialRadiusOffset = 0;
  12105. }
  12106. // Panning inertia
  12107. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12108. if (!this._localDirection) {
  12109. this._localDirection = BABYLON.Vector3.Zero();
  12110. this._transformedDirection = BABYLON.Vector3.Zero();
  12111. }
  12112. this.inertialPanningX *= this.inertia;
  12113. this.inertialPanningY *= this.inertia;
  12114. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  12115. this.inertialPanningX = 0;
  12116. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  12117. this.inertialPanningY = 0;
  12118. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12119. this._localDirection.multiplyInPlace(this.panningAxis);
  12120. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12121. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12122. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12123. if (!this.panningAxis.y) {
  12124. this._transformedDirection.y = 0;
  12125. }
  12126. this.target.addInPlace(this._transformedDirection);
  12127. }
  12128. // Limits
  12129. this._checkLimits();
  12130. _super.prototype._checkInputs.call(this);
  12131. };
  12132. ArcRotateCamera.prototype._checkLimits = function () {
  12133. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12134. if (this.allowUpsideDown && this.beta > Math.PI) {
  12135. this.beta = this.beta - (2 * Math.PI);
  12136. }
  12137. }
  12138. else {
  12139. if (this.beta < this.lowerBetaLimit) {
  12140. this.beta = this.lowerBetaLimit;
  12141. }
  12142. }
  12143. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12144. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12145. this.beta = this.beta + (2 * Math.PI);
  12146. }
  12147. }
  12148. else {
  12149. if (this.beta > this.upperBetaLimit) {
  12150. this.beta = this.upperBetaLimit;
  12151. }
  12152. }
  12153. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12154. this.alpha = this.lowerAlphaLimit;
  12155. }
  12156. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12157. this.alpha = this.upperAlphaLimit;
  12158. }
  12159. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12160. this.radius = this.lowerRadiusLimit;
  12161. }
  12162. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12163. this.radius = this.upperRadiusLimit;
  12164. }
  12165. };
  12166. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12167. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12168. this.radius = radiusv3.length();
  12169. // Alpha
  12170. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12171. if (radiusv3.z < 0) {
  12172. this.alpha = 2 * Math.PI - this.alpha;
  12173. }
  12174. // Beta
  12175. this.beta = Math.acos(radiusv3.y / this.radius);
  12176. this._checkLimits();
  12177. };
  12178. ArcRotateCamera.prototype.setPosition = function (position) {
  12179. if (this.position.equals(position)) {
  12180. return;
  12181. }
  12182. this.position = position;
  12183. this.rebuildAnglesAndRadius();
  12184. };
  12185. ArcRotateCamera.prototype.setTarget = function (target) {
  12186. if (this._getTargetPosition().equals(target)) {
  12187. return;
  12188. }
  12189. this.target = target;
  12190. this.rebuildAnglesAndRadius();
  12191. };
  12192. ArcRotateCamera.prototype._getViewMatrix = function () {
  12193. // Compute
  12194. var cosa = Math.cos(this.alpha);
  12195. var sina = Math.sin(this.alpha);
  12196. var cosb = Math.cos(this.beta);
  12197. var sinb = Math.sin(this.beta);
  12198. if (sinb === 0) {
  12199. sinb = 0.0001;
  12200. }
  12201. var target = this._getTargetPosition();
  12202. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12203. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12204. this._collider.radius = this.collisionRadius;
  12205. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12206. this._collisionTriggered = true;
  12207. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12208. }
  12209. else {
  12210. this.position.copyFrom(this._newPosition);
  12211. var up = this.upVector;
  12212. if (this.allowUpsideDown && this.beta < 0) {
  12213. up = up.clone();
  12214. up = up.negate();
  12215. }
  12216. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12217. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12218. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12219. }
  12220. return this._viewMatrix;
  12221. };
  12222. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12223. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12224. meshes = meshes || this.getScene().meshes;
  12225. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12226. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12227. this.radius = distance * this.zoomOnFactor;
  12228. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12229. };
  12230. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12231. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12232. var meshesOrMinMaxVector;
  12233. var distance;
  12234. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12235. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12236. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12237. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12238. }
  12239. else {
  12240. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12241. distance = meshesOrMinMaxVectorAndDistance.distance;
  12242. }
  12243. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12244. if (!doNotUpdateMaxZ) {
  12245. this.maxZ = distance * 2;
  12246. }
  12247. };
  12248. /**
  12249. * @override
  12250. * Override Camera.createRigCamera
  12251. */
  12252. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12253. switch (this.cameraRigMode) {
  12254. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12255. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12258. case BABYLON.Camera.RIG_MODE_VR:
  12259. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12260. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12261. }
  12262. return null;
  12263. };
  12264. /**
  12265. * @override
  12266. * Override Camera._updateRigCameras
  12267. */
  12268. ArcRotateCamera.prototype._updateRigCameras = function () {
  12269. switch (this.cameraRigMode) {
  12270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12274. case BABYLON.Camera.RIG_MODE_VR:
  12275. var camLeft = this._rigCameras[0];
  12276. var camRight = this._rigCameras[1];
  12277. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12278. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12279. camLeft.beta = camRight.beta = this.beta;
  12280. camLeft.radius = camRight.radius = this.radius;
  12281. break;
  12282. }
  12283. _super.prototype._updateRigCameras.call(this);
  12284. };
  12285. ArcRotateCamera.prototype.getTypeName = function () {
  12286. return "ArcRotateCamera";
  12287. };
  12288. __decorate([
  12289. BABYLON.serialize()
  12290. ], ArcRotateCamera.prototype, "alpha", void 0);
  12291. __decorate([
  12292. BABYLON.serialize()
  12293. ], ArcRotateCamera.prototype, "beta", void 0);
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], ArcRotateCamera.prototype, "radius", void 0);
  12297. __decorate([
  12298. BABYLON.serializeAsVector3()
  12299. ], ArcRotateCamera.prototype, "target", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12303. __decorate([
  12304. BABYLON.serialize()
  12305. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12306. __decorate([
  12307. BABYLON.serialize()
  12308. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12309. __decorate([
  12310. BABYLON.serialize()
  12311. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12312. __decorate([
  12313. BABYLON.serialize()
  12314. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12315. __decorate([
  12316. BABYLON.serialize()
  12317. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12318. __decorate([
  12319. BABYLON.serialize()
  12320. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12321. __decorate([
  12322. BABYLON.serialize()
  12323. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12324. __decorate([
  12325. BABYLON.serialize()
  12326. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12327. __decorate([
  12328. BABYLON.serialize()
  12329. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12330. __decorate([
  12331. BABYLON.serialize()
  12332. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12333. __decorate([
  12334. BABYLON.serialize()
  12335. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12336. __decorate([
  12337. BABYLON.serialize()
  12338. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12339. __decorate([
  12340. BABYLON.serialize()
  12341. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12342. __decorate([
  12343. BABYLON.serialize()
  12344. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12345. __decorate([
  12346. BABYLON.serialize()
  12347. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12348. __decorate([
  12349. BABYLON.serialize()
  12350. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12351. __decorate([
  12352. BABYLON.serialize()
  12353. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12354. __decorate([
  12355. BABYLON.serialize()
  12356. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12357. __decorate([
  12358. BABYLON.serialize()
  12359. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12360. __decorate([
  12361. BABYLON.serialize()
  12362. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12363. __decorate([
  12364. BABYLON.serialize()
  12365. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12366. return ArcRotateCamera;
  12367. })(BABYLON.TargetCamera);
  12368. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12369. })(BABYLON || (BABYLON = {}));
  12370. var BABYLON;
  12371. (function (BABYLON) {
  12372. var RenderingManager = (function () {
  12373. function RenderingManager(scene) {
  12374. this._renderingGroups = new Array();
  12375. this._scene = scene;
  12376. }
  12377. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12378. if (this._scene._activeParticleSystems.length === 0) {
  12379. return;
  12380. }
  12381. // Particles
  12382. var activeCamera = this._scene.activeCamera;
  12383. var beforeParticlesDate = BABYLON.Tools.Now;
  12384. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12385. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12386. if (particleSystem.renderingGroupId !== index) {
  12387. continue;
  12388. }
  12389. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12390. continue;
  12391. }
  12392. this._clearDepthBuffer();
  12393. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12394. this._scene._activeParticles += particleSystem.render();
  12395. }
  12396. }
  12397. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12398. };
  12399. RenderingManager.prototype._renderSprites = function (index) {
  12400. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12401. return;
  12402. }
  12403. // Sprites
  12404. var activeCamera = this._scene.activeCamera;
  12405. var beforeSpritessDate = BABYLON.Tools.Now;
  12406. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12407. var spriteManager = this._scene.spriteManagers[id];
  12408. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12409. this._clearDepthBuffer();
  12410. spriteManager.render();
  12411. }
  12412. }
  12413. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12414. };
  12415. RenderingManager.prototype._clearDepthBuffer = function () {
  12416. if (this._depthBufferAlreadyCleaned) {
  12417. return;
  12418. }
  12419. this._scene.getEngine().clear(0, false, true);
  12420. this._depthBufferAlreadyCleaned = true;
  12421. };
  12422. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12423. if (this._currentRenderSprites) {
  12424. this._renderSprites(this._currentIndex);
  12425. }
  12426. if (this._currentRenderParticles) {
  12427. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12428. }
  12429. };
  12430. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12431. this._currentActiveMeshes = activeMeshes;
  12432. this._currentRenderParticles = renderParticles;
  12433. this._currentRenderSprites = renderSprites;
  12434. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12435. this._depthBufferAlreadyCleaned = index == 0;
  12436. var renderingGroup = this._renderingGroups[index];
  12437. var needToStepBack = false;
  12438. this._currentIndex = index;
  12439. if (renderingGroup) {
  12440. this._clearDepthBuffer();
  12441. if (!renderingGroup.onBeforeTransparentRendering) {
  12442. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12443. }
  12444. if (!renderingGroup.render(customRenderFunction)) {
  12445. this._renderingGroups.splice(index, 1);
  12446. needToStepBack = true;
  12447. this._renderSpritesAndParticles();
  12448. }
  12449. }
  12450. else {
  12451. this._renderSpritesAndParticles();
  12452. }
  12453. if (needToStepBack) {
  12454. index--;
  12455. }
  12456. }
  12457. };
  12458. RenderingManager.prototype.reset = function () {
  12459. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12460. if (renderingGroup) {
  12461. renderingGroup.prepare();
  12462. }
  12463. });
  12464. };
  12465. RenderingManager.prototype.dispatch = function (subMesh) {
  12466. var mesh = subMesh.getMesh();
  12467. var renderingGroupId = mesh.renderingGroupId || 0;
  12468. if (!this._renderingGroups[renderingGroupId]) {
  12469. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12470. }
  12471. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12472. };
  12473. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12474. return RenderingManager;
  12475. })();
  12476. BABYLON.RenderingManager = RenderingManager;
  12477. })(BABYLON || (BABYLON = {}));
  12478. var BABYLON;
  12479. (function (BABYLON) {
  12480. var RenderingGroup = (function () {
  12481. function RenderingGroup(index, scene) {
  12482. this.index = index;
  12483. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12484. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12485. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12486. this._scene = scene;
  12487. }
  12488. RenderingGroup.prototype.render = function (customRenderFunction) {
  12489. if (customRenderFunction) {
  12490. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12491. return true;
  12492. }
  12493. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12494. if (this.onBeforeTransparentRendering) {
  12495. this.onBeforeTransparentRendering();
  12496. }
  12497. return false;
  12498. }
  12499. var engine = this._scene.getEngine();
  12500. // Opaque
  12501. var subIndex;
  12502. var submesh;
  12503. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12504. submesh = this._opaqueSubMeshes.data[subIndex];
  12505. submesh.render(false);
  12506. }
  12507. // Alpha test
  12508. engine.setAlphaTesting(true);
  12509. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12510. submesh = this._alphaTestSubMeshes.data[subIndex];
  12511. submesh.render(false);
  12512. }
  12513. engine.setAlphaTesting(false);
  12514. if (this.onBeforeTransparentRendering) {
  12515. this.onBeforeTransparentRendering();
  12516. }
  12517. // Transparent
  12518. if (this._transparentSubMeshes.length) {
  12519. // Sorting
  12520. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12521. submesh = this._transparentSubMeshes.data[subIndex];
  12522. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12523. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12524. }
  12525. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12526. sortedArray.sort(function (a, b) {
  12527. // Alpha index first
  12528. if (a._alphaIndex > b._alphaIndex) {
  12529. return 1;
  12530. }
  12531. if (a._alphaIndex < b._alphaIndex) {
  12532. return -1;
  12533. }
  12534. // Then distance to camera
  12535. if (a._distanceToCamera < b._distanceToCamera) {
  12536. return 1;
  12537. }
  12538. if (a._distanceToCamera > b._distanceToCamera) {
  12539. return -1;
  12540. }
  12541. return 0;
  12542. });
  12543. // Rendering
  12544. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12545. submesh = sortedArray[subIndex];
  12546. submesh.render(true);
  12547. }
  12548. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12549. }
  12550. return true;
  12551. };
  12552. RenderingGroup.prototype.prepare = function () {
  12553. this._opaqueSubMeshes.reset();
  12554. this._transparentSubMeshes.reset();
  12555. this._alphaTestSubMeshes.reset();
  12556. };
  12557. RenderingGroup.prototype.dispatch = function (subMesh) {
  12558. var material = subMesh.getMaterial();
  12559. var mesh = subMesh.getMesh();
  12560. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12561. this._transparentSubMeshes.push(subMesh);
  12562. }
  12563. else if (material.needAlphaTesting()) {
  12564. this._alphaTestSubMeshes.push(subMesh);
  12565. }
  12566. else {
  12567. this._opaqueSubMeshes.push(subMesh); // Opaque
  12568. }
  12569. };
  12570. return RenderingGroup;
  12571. })();
  12572. BABYLON.RenderingGroup = RenderingGroup;
  12573. })(BABYLON || (BABYLON = {}));
  12574. var BABYLON;
  12575. (function (BABYLON) {
  12576. /**
  12577. * Represents a scene to be rendered by the engine.
  12578. * @see http://doc.babylonjs.com/page.php?p=21911
  12579. */
  12580. var Scene = (function () {
  12581. /**
  12582. * @constructor
  12583. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12584. */
  12585. function Scene(engine) {
  12586. // Members
  12587. this.autoClear = true;
  12588. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12589. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12590. this.forceWireframe = false;
  12591. this.forcePointsCloud = false;
  12592. this.forceShowBoundingBoxes = false;
  12593. this.animationsEnabled = true;
  12594. this.constantlyUpdateMeshUnderPointer = false;
  12595. // Animations
  12596. this.animations = [];
  12597. 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
  12598. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12599. this._startingPointerTime = 0;
  12600. // Fog
  12601. /**
  12602. * is fog enabled on this scene.
  12603. * @type {boolean}
  12604. */
  12605. this.fogEnabled = true;
  12606. this.fogMode = Scene.FOGMODE_NONE;
  12607. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12608. this.fogDensity = 0.1;
  12609. this.fogStart = 0;
  12610. this.fogEnd = 1000.0;
  12611. // Lights
  12612. /**
  12613. * is shadow enabled on this scene.
  12614. * @type {boolean}
  12615. */
  12616. this.shadowsEnabled = true;
  12617. /**
  12618. * is light enabled on this scene.
  12619. * @type {boolean}
  12620. */
  12621. this.lightsEnabled = true;
  12622. /**
  12623. * All of the lights added to this scene.
  12624. * @see BABYLON.Light
  12625. * @type {BABYLON.Light[]}
  12626. */
  12627. this.lights = new Array();
  12628. // Cameras
  12629. /**
  12630. * All of the cameras added to this scene.
  12631. * @see BABYLON.Camera
  12632. * @type {BABYLON.Camera[]}
  12633. */
  12634. this.cameras = new Array();
  12635. this.activeCameras = new Array();
  12636. // Meshes
  12637. /**
  12638. * All of the (abstract) meshes added to this scene.
  12639. * @see BABYLON.AbstractMesh
  12640. * @type {BABYLON.AbstractMesh[]}
  12641. */
  12642. this.meshes = new Array();
  12643. // Geometries
  12644. this._geometries = new Array();
  12645. this.materials = new Array();
  12646. this.multiMaterials = new Array();
  12647. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12648. // Textures
  12649. this.texturesEnabled = true;
  12650. this.textures = new Array();
  12651. // Particles
  12652. this.particlesEnabled = true;
  12653. this.particleSystems = new Array();
  12654. // Sprites
  12655. this.spritesEnabled = true;
  12656. this.spriteManagers = new Array();
  12657. // Layers
  12658. this.layers = new Array();
  12659. // Skeletons
  12660. this.skeletonsEnabled = true;
  12661. this.skeletons = new Array();
  12662. // Lens flares
  12663. this.lensFlaresEnabled = true;
  12664. this.lensFlareSystems = new Array();
  12665. // Collisions
  12666. this.collisionsEnabled = true;
  12667. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12668. // Postprocesses
  12669. this.postProcessesEnabled = true;
  12670. // Customs render targets
  12671. this.renderTargetsEnabled = true;
  12672. this.dumpNextRenderTargets = false;
  12673. this.customRenderTargets = new Array();
  12674. // Imported meshes
  12675. this.importedMeshesFiles = new Array();
  12676. // Probes
  12677. this.probesEnabled = true;
  12678. this.reflectionProbes = new Array();
  12679. this._actionManagers = new Array();
  12680. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12681. // Procedural textures
  12682. this.proceduralTexturesEnabled = true;
  12683. this._proceduralTextures = new Array();
  12684. this.soundTracks = new Array();
  12685. this._audioEnabled = true;
  12686. this._headphone = false;
  12687. this._totalVertices = 0;
  12688. this._activeIndices = 0;
  12689. this._activeParticles = 0;
  12690. this._lastFrameDuration = 0;
  12691. this._evaluateActiveMeshesDuration = 0;
  12692. this._renderTargetsDuration = 0;
  12693. this._particlesDuration = 0;
  12694. this._renderDuration = 0;
  12695. this._spritesDuration = 0;
  12696. this._animationRatio = 0;
  12697. this._renderId = 0;
  12698. this._executeWhenReadyTimeoutId = -1;
  12699. this._toBeDisposed = new BABYLON.SmartArray(256);
  12700. this._onReadyCallbacks = new Array();
  12701. this._pendingData = []; //ANY
  12702. this._onBeforeRenderCallbacks = new Array();
  12703. this._onAfterRenderCallbacks = new Array();
  12704. this._activeMeshes = new BABYLON.SmartArray(256);
  12705. this._processedMaterials = new BABYLON.SmartArray(256);
  12706. this._renderTargets = new BABYLON.SmartArray(256);
  12707. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12708. this._activeSkeletons = new BABYLON.SmartArray(32);
  12709. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12710. this._activeBones = 0;
  12711. this._activeAnimatables = new Array();
  12712. this._transformMatrix = BABYLON.Matrix.Zero();
  12713. this._edgesRenderers = new BABYLON.SmartArray(16);
  12714. this._uniqueIdCounter = 0;
  12715. this._engine = engine;
  12716. engine.scenes.push(this);
  12717. this._renderingManager = new BABYLON.RenderingManager(this);
  12718. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12719. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12720. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12721. if (BABYLON.OutlineRenderer) {
  12722. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12723. }
  12724. this.attachControl();
  12725. this._debugLayer = new BABYLON.DebugLayer(this);
  12726. if (BABYLON.SoundTrack) {
  12727. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12728. }
  12729. //simplification queue
  12730. if (BABYLON.SimplificationQueue) {
  12731. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12732. }
  12733. //collision coordinator initialization. For now legacy per default.
  12734. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12735. }
  12736. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12737. get: function () {
  12738. return Scene._FOGMODE_NONE;
  12739. },
  12740. enumerable: true,
  12741. configurable: true
  12742. });
  12743. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12744. get: function () {
  12745. return Scene._FOGMODE_EXP;
  12746. },
  12747. enumerable: true,
  12748. configurable: true
  12749. });
  12750. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12751. get: function () {
  12752. return Scene._FOGMODE_EXP2;
  12753. },
  12754. enumerable: true,
  12755. configurable: true
  12756. });
  12757. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12758. get: function () {
  12759. return Scene._FOGMODE_LINEAR;
  12760. },
  12761. enumerable: true,
  12762. configurable: true
  12763. });
  12764. Object.defineProperty(Scene.prototype, "debugLayer", {
  12765. // Properties
  12766. get: function () {
  12767. return this._debugLayer;
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12773. get: function () {
  12774. return this._workerCollisions;
  12775. },
  12776. set: function (enabled) {
  12777. enabled = (enabled && !!Worker);
  12778. this._workerCollisions = enabled;
  12779. if (this.collisionCoordinator) {
  12780. this.collisionCoordinator.destroy();
  12781. }
  12782. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12783. this.collisionCoordinator.init(this);
  12784. },
  12785. enumerable: true,
  12786. configurable: true
  12787. });
  12788. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12789. get: function () {
  12790. return this._selectionOctree;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12796. /**
  12797. * The mesh that is currently under the pointer.
  12798. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12799. */
  12800. get: function () {
  12801. return this._pointerOverMesh;
  12802. },
  12803. enumerable: true,
  12804. configurable: true
  12805. });
  12806. Object.defineProperty(Scene.prototype, "pointerX", {
  12807. /**
  12808. * Current on-screen X position of the pointer
  12809. * @return {number} X position of the pointer
  12810. */
  12811. get: function () {
  12812. return this._pointerX;
  12813. },
  12814. enumerable: true,
  12815. configurable: true
  12816. });
  12817. Object.defineProperty(Scene.prototype, "pointerY", {
  12818. /**
  12819. * Current on-screen Y position of the pointer
  12820. * @return {number} Y position of the pointer
  12821. */
  12822. get: function () {
  12823. return this._pointerY;
  12824. },
  12825. enumerable: true,
  12826. configurable: true
  12827. });
  12828. Scene.prototype.getCachedMaterial = function () {
  12829. return this._cachedMaterial;
  12830. };
  12831. Scene.prototype.getBoundingBoxRenderer = function () {
  12832. return this._boundingBoxRenderer;
  12833. };
  12834. Scene.prototype.getOutlineRenderer = function () {
  12835. return this._outlineRenderer;
  12836. };
  12837. Scene.prototype.getEngine = function () {
  12838. return this._engine;
  12839. };
  12840. Scene.prototype.getTotalVertices = function () {
  12841. return this._totalVertices;
  12842. };
  12843. Scene.prototype.getActiveIndices = function () {
  12844. return this._activeIndices;
  12845. };
  12846. Scene.prototype.getActiveParticles = function () {
  12847. return this._activeParticles;
  12848. };
  12849. Scene.prototype.getActiveBones = function () {
  12850. return this._activeBones;
  12851. };
  12852. // Stats
  12853. Scene.prototype.getLastFrameDuration = function () {
  12854. return this._lastFrameDuration;
  12855. };
  12856. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12857. return this._evaluateActiveMeshesDuration;
  12858. };
  12859. Scene.prototype.getActiveMeshes = function () {
  12860. return this._activeMeshes;
  12861. };
  12862. Scene.prototype.getRenderTargetsDuration = function () {
  12863. return this._renderTargetsDuration;
  12864. };
  12865. Scene.prototype.getRenderDuration = function () {
  12866. return this._renderDuration;
  12867. };
  12868. Scene.prototype.getParticlesDuration = function () {
  12869. return this._particlesDuration;
  12870. };
  12871. Scene.prototype.getSpritesDuration = function () {
  12872. return this._spritesDuration;
  12873. };
  12874. Scene.prototype.getAnimationRatio = function () {
  12875. return this._animationRatio;
  12876. };
  12877. Scene.prototype.getRenderId = function () {
  12878. return this._renderId;
  12879. };
  12880. Scene.prototype.incrementRenderId = function () {
  12881. this._renderId++;
  12882. };
  12883. Scene.prototype._updatePointerPosition = function (evt) {
  12884. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12885. this._pointerX = evt.clientX - canvasRect.left;
  12886. this._pointerY = evt.clientY - canvasRect.top;
  12887. this._unTranslatedPointerX = this._pointerX;
  12888. this._unTranslatedPointerY = this._pointerY;
  12889. if (this.cameraToUseForPointers) {
  12890. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12891. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12892. }
  12893. };
  12894. // Pointers handling
  12895. Scene.prototype.attachControl = function () {
  12896. var _this = this;
  12897. var spritePredicate = function (sprite) {
  12898. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12899. };
  12900. this._onPointerMove = function (evt) {
  12901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12902. return;
  12903. }
  12904. var canvas = _this._engine.getRenderingCanvas();
  12905. _this._updatePointerPosition(evt);
  12906. if (!_this.pointerMovePredicate) {
  12907. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  12908. }
  12909. // Meshes
  12910. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  12911. if (pickResult.hit && pickResult.pickedMesh) {
  12912. _this.setPointerOverSprite(null);
  12913. _this.setPointerOverMesh(pickResult.pickedMesh);
  12914. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12915. canvas.style.cursor = "pointer";
  12916. }
  12917. else {
  12918. canvas.style.cursor = "";
  12919. }
  12920. }
  12921. else {
  12922. _this.setPointerOverMesh(null);
  12923. // Sprites
  12924. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12925. if (pickResult.hit && pickResult.pickedSprite) {
  12926. canvas.style.cursor = "pointer";
  12927. _this.setPointerOverSprite(pickResult.pickedSprite);
  12928. }
  12929. else {
  12930. _this.setPointerOverSprite(null);
  12931. // Restore pointer
  12932. canvas.style.cursor = "";
  12933. }
  12934. }
  12935. if (_this.onPointerMove) {
  12936. _this.onPointerMove(evt, pickResult);
  12937. }
  12938. };
  12939. this._onPointerDown = function (evt) {
  12940. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12941. return;
  12942. }
  12943. _this._updatePointerPosition(evt);
  12944. _this._startingPointerPosition.x = _this._pointerX;
  12945. _this._startingPointerPosition.y = _this._pointerY;
  12946. _this._startingPointerTime = new Date().getTime();
  12947. if (!_this.pointerDownPredicate) {
  12948. _this.pointerDownPredicate = function (mesh) {
  12949. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  12950. };
  12951. }
  12952. // Meshes
  12953. _this._pickedDownMesh = null;
  12954. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, 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. _this._updatePointerPosition(evt);
  13019. if (!_this.pointerUpPredicate) {
  13020. _this.pointerUpPredicate = function (mesh) {
  13021. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  13022. };
  13023. }
  13024. // Meshes
  13025. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13026. if (pickResult.hit && pickResult.pickedMesh) {
  13027. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13028. _this.onPointerPick(evt, pickResult);
  13029. }
  13030. if (pickResult.pickedMesh.actionManager) {
  13031. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13032. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13033. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13034. }
  13035. }
  13036. }
  13037. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13038. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13039. }
  13040. if (_this.onPointerUp) {
  13041. _this.onPointerUp(evt, pickResult);
  13042. }
  13043. _this._startingPointerTime = 0;
  13044. // Sprites
  13045. if (_this.spriteManagers.length > 0) {
  13046. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13047. if (pickResult.hit && pickResult.pickedSprite) {
  13048. if (pickResult.pickedSprite.actionManager) {
  13049. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13050. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13051. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13052. }
  13053. }
  13054. }
  13055. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13056. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13057. }
  13058. }
  13059. };
  13060. this._onKeyDown = function (evt) {
  13061. if (_this.actionManager) {
  13062. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13063. }
  13064. };
  13065. this._onKeyUp = function (evt) {
  13066. if (_this.actionManager) {
  13067. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13068. }
  13069. };
  13070. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13071. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13072. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13073. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13074. // Wheel
  13075. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13076. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13077. BABYLON.Tools.RegisterTopRootEvents([
  13078. { name: "keydown", handler: this._onKeyDown },
  13079. { name: "keyup", handler: this._onKeyUp }
  13080. ]);
  13081. };
  13082. Scene.prototype.detachControl = function () {
  13083. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13084. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13085. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13086. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13087. // Wheel
  13088. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13089. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13090. BABYLON.Tools.UnregisterTopRootEvents([
  13091. { name: "keydown", handler: this._onKeyDown },
  13092. { name: "keyup", handler: this._onKeyUp }
  13093. ]);
  13094. };
  13095. // Ready
  13096. Scene.prototype.isReady = function () {
  13097. if (this._pendingData.length > 0) {
  13098. return false;
  13099. }
  13100. var index;
  13101. for (index = 0; index < this._geometries.length; index++) {
  13102. var geometry = this._geometries[index];
  13103. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13104. return false;
  13105. }
  13106. }
  13107. for (index = 0; index < this.meshes.length; index++) {
  13108. var mesh = this.meshes[index];
  13109. if (!mesh.isReady()) {
  13110. return false;
  13111. }
  13112. var mat = mesh.material;
  13113. if (mat) {
  13114. if (!mat.isReady(mesh)) {
  13115. return false;
  13116. }
  13117. }
  13118. }
  13119. return true;
  13120. };
  13121. Scene.prototype.resetCachedMaterial = function () {
  13122. this._cachedMaterial = null;
  13123. };
  13124. Scene.prototype.registerBeforeRender = function (func) {
  13125. this._onBeforeRenderCallbacks.push(func);
  13126. };
  13127. Scene.prototype.unregisterBeforeRender = function (func) {
  13128. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13129. if (index > -1) {
  13130. this._onBeforeRenderCallbacks.splice(index, 1);
  13131. }
  13132. };
  13133. Scene.prototype.registerAfterRender = function (func) {
  13134. this._onAfterRenderCallbacks.push(func);
  13135. };
  13136. Scene.prototype.unregisterAfterRender = function (func) {
  13137. var index = this._onAfterRenderCallbacks.indexOf(func);
  13138. if (index > -1) {
  13139. this._onAfterRenderCallbacks.splice(index, 1);
  13140. }
  13141. };
  13142. Scene.prototype._addPendingData = function (data) {
  13143. this._pendingData.push(data);
  13144. };
  13145. Scene.prototype._removePendingData = function (data) {
  13146. var index = this._pendingData.indexOf(data);
  13147. if (index !== -1) {
  13148. this._pendingData.splice(index, 1);
  13149. }
  13150. };
  13151. Scene.prototype.getWaitingItemsCount = function () {
  13152. return this._pendingData.length;
  13153. };
  13154. /**
  13155. * Registers a function to be executed when the scene is ready.
  13156. * @param {Function} func - the function to be executed.
  13157. */
  13158. Scene.prototype.executeWhenReady = function (func) {
  13159. var _this = this;
  13160. this._onReadyCallbacks.push(func);
  13161. if (this._executeWhenReadyTimeoutId !== -1) {
  13162. return;
  13163. }
  13164. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13165. _this._checkIsReady();
  13166. }, 150);
  13167. };
  13168. Scene.prototype._checkIsReady = function () {
  13169. var _this = this;
  13170. if (this.isReady()) {
  13171. this._onReadyCallbacks.forEach(function (func) {
  13172. func();
  13173. });
  13174. this._onReadyCallbacks = [];
  13175. this._executeWhenReadyTimeoutId = -1;
  13176. return;
  13177. }
  13178. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13179. _this._checkIsReady();
  13180. }, 150);
  13181. };
  13182. // Animations
  13183. /**
  13184. * Will start the animation sequence of a given target
  13185. * @param target - the target
  13186. * @param {number} from - from which frame should animation start
  13187. * @param {number} to - till which frame should animation run.
  13188. * @param {boolean} [loop] - should the animation loop
  13189. * @param {number} [speedRatio] - the speed in which to run the animation
  13190. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13191. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13192. * @return {BABYLON.Animatable} the animatable object created for this animation
  13193. * @see BABYLON.Animatable
  13194. * @see http://doc.babylonjs.com/page.php?p=22081
  13195. */
  13196. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13197. if (speedRatio === void 0) { speedRatio = 1.0; }
  13198. this.stopAnimation(target);
  13199. if (!animatable) {
  13200. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13201. }
  13202. // Local animations
  13203. if (target.animations) {
  13204. animatable.appendAnimations(target, target.animations);
  13205. }
  13206. // Children animations
  13207. if (target.getAnimatables) {
  13208. var animatables = target.getAnimatables();
  13209. for (var index = 0; index < animatables.length; index++) {
  13210. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13211. }
  13212. }
  13213. animatable.reset();
  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.getRenderWidth(), engine.getRenderHeight());
  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.getRenderWidth(), engine.getRenderHeight());
  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"], ["_poseMatrix"]);
  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, parsedMesh.autoAnimateSpeed || 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[3].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. if (match[4]) {
  19205. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  19206. }
  19207. // Replace
  19208. returnValue = returnValue.replace(match[0], includeContent);
  19209. }
  19210. else {
  19211. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19212. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19213. Effect.IncludesShadersStore[includeFile] = fileContent;
  19214. _this._processIncludes(returnValue, callback);
  19215. });
  19216. return;
  19217. }
  19218. match = regex.exec(sourceCode);
  19219. }
  19220. callback(returnValue);
  19221. };
  19222. Effect.prototype._processPrecision = function (source) {
  19223. if (source.indexOf("precision highp float") === -1) {
  19224. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19225. source = "precision mediump float;\n" + source;
  19226. }
  19227. else {
  19228. source = "precision highp float;\n" + source;
  19229. }
  19230. }
  19231. else {
  19232. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19233. source = source.replace("precision highp float", "precision mediump float");
  19234. }
  19235. }
  19236. return source;
  19237. };
  19238. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19239. try {
  19240. var engine = this._engine;
  19241. // Precision
  19242. vertexSourceCode = this._processPrecision(vertexSourceCode);
  19243. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  19244. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19245. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19246. this._attributes = engine.getAttributes(this._program, attributesNames);
  19247. for (var index = 0; index < this._samplers.length; index++) {
  19248. var sampler = this.getUniform(this._samplers[index]);
  19249. if (sampler == null) {
  19250. this._samplers.splice(index, 1);
  19251. index--;
  19252. }
  19253. }
  19254. engine.bindSamplers(this);
  19255. this._isReady = true;
  19256. if (this.onCompiled) {
  19257. this.onCompiled(this);
  19258. }
  19259. }
  19260. catch (e) {
  19261. // Is it a problem with precision?
  19262. if (e.message.indexOf("highp") !== -1) {
  19263. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19264. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19265. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19266. return;
  19267. }
  19268. // Let's go through fallbacks then
  19269. if (fallbacks && fallbacks.isMoreFallbacks) {
  19270. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19271. this._dumpShadersName();
  19272. defines = fallbacks.reduce(defines);
  19273. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19274. }
  19275. else {
  19276. BABYLON.Tools.Error("Unable to compile effect: ");
  19277. this._dumpShadersName();
  19278. BABYLON.Tools.Error("Defines: " + defines);
  19279. BABYLON.Tools.Error("Error: " + e.message);
  19280. this._compilationError = e.message;
  19281. if (this.onError) {
  19282. this.onError(this, this._compilationError);
  19283. }
  19284. }
  19285. }
  19286. };
  19287. Object.defineProperty(Effect.prototype, "isSupported", {
  19288. get: function () {
  19289. return this._compilationError === "";
  19290. },
  19291. enumerable: true,
  19292. configurable: true
  19293. });
  19294. Effect.prototype._bindTexture = function (channel, texture) {
  19295. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19296. };
  19297. Effect.prototype.setTexture = function (channel, texture) {
  19298. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19299. };
  19300. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19301. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19302. };
  19303. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19304. if (!this._valueCache[uniformName]) {
  19305. this._valueCache[uniformName] = new BABYLON.Matrix();
  19306. }
  19307. for (var index = 0; index < 16; index++) {
  19308. this._valueCache[uniformName].m[index] = matrix.m[index];
  19309. }
  19310. };
  19311. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19312. if (!this._valueCache[uniformName]) {
  19313. this._valueCache[uniformName] = [x, y];
  19314. return;
  19315. }
  19316. this._valueCache[uniformName][0] = x;
  19317. this._valueCache[uniformName][1] = y;
  19318. };
  19319. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19320. if (!this._valueCache[uniformName]) {
  19321. this._valueCache[uniformName] = [x, y, z];
  19322. return;
  19323. }
  19324. this._valueCache[uniformName][0] = x;
  19325. this._valueCache[uniformName][1] = y;
  19326. this._valueCache[uniformName][2] = z;
  19327. };
  19328. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19329. if (!this._valueCache[uniformName]) {
  19330. this._valueCache[uniformName] = [x, y, z, w];
  19331. return;
  19332. }
  19333. this._valueCache[uniformName][0] = x;
  19334. this._valueCache[uniformName][1] = y;
  19335. this._valueCache[uniformName][2] = z;
  19336. this._valueCache[uniformName][3] = w;
  19337. };
  19338. Effect.prototype.setArray = function (uniformName, array) {
  19339. this._engine.setArray(this.getUniform(uniformName), array);
  19340. return this;
  19341. };
  19342. Effect.prototype.setArray2 = function (uniformName, array) {
  19343. this._engine.setArray2(this.getUniform(uniformName), array);
  19344. return this;
  19345. };
  19346. Effect.prototype.setArray3 = function (uniformName, array) {
  19347. this._engine.setArray3(this.getUniform(uniformName), array);
  19348. return this;
  19349. };
  19350. Effect.prototype.setArray4 = function (uniformName, array) {
  19351. this._engine.setArray4(this.getUniform(uniformName), array);
  19352. return this;
  19353. };
  19354. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19355. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19356. return this;
  19357. };
  19358. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19359. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19360. // return this;
  19361. // this._cacheMatrix(uniformName, matrix);
  19362. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19363. return this;
  19364. };
  19365. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19366. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19367. return this;
  19368. };
  19369. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19370. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19371. return this;
  19372. };
  19373. Effect.prototype.setFloat = function (uniformName, value) {
  19374. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19375. return this;
  19376. this._valueCache[uniformName] = value;
  19377. this._engine.setFloat(this.getUniform(uniformName), value);
  19378. return this;
  19379. };
  19380. Effect.prototype.setBool = function (uniformName, bool) {
  19381. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19382. return this;
  19383. this._valueCache[uniformName] = bool;
  19384. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19385. return this;
  19386. };
  19387. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19388. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19389. return this;
  19390. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19391. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19392. return this;
  19393. };
  19394. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19395. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19396. return this;
  19397. this._cacheFloat2(uniformName, x, y);
  19398. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19399. return this;
  19400. };
  19401. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19402. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19403. return this;
  19404. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19405. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19406. return this;
  19407. };
  19408. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19409. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19410. return this;
  19411. this._cacheFloat3(uniformName, x, y, z);
  19412. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19413. return this;
  19414. };
  19415. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19416. 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)
  19417. return this;
  19418. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19419. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19420. return this;
  19421. };
  19422. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19423. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19424. return this;
  19425. this._cacheFloat4(uniformName, x, y, z, w);
  19426. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19427. return this;
  19428. };
  19429. Effect.prototype.setColor3 = function (uniformName, color3) {
  19430. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19431. return this;
  19432. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19433. this._engine.setColor3(this.getUniform(uniformName), color3);
  19434. return this;
  19435. };
  19436. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19437. 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)
  19438. return this;
  19439. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19440. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19441. return this;
  19442. };
  19443. // Statics
  19444. Effect.ShadersStore = {};
  19445. Effect.IncludesShadersStore = {};
  19446. return Effect;
  19447. })();
  19448. BABYLON.Effect = Effect;
  19449. })(BABYLON || (BABYLON = {}));
  19450. var BABYLON;
  19451. (function (BABYLON) {
  19452. var maxSimultaneousLights = 4;
  19453. var MaterialHelper = (function () {
  19454. function MaterialHelper() {
  19455. }
  19456. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19457. var lightIndex = 0;
  19458. var needNormals = false;
  19459. for (var index = 0; index < scene.lights.length; index++) {
  19460. var light = scene.lights[index];
  19461. if (!light.isEnabled()) {
  19462. continue;
  19463. }
  19464. // Excluded check
  19465. if (light._excludedMeshesIds.length > 0) {
  19466. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19467. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19468. if (excludedMesh) {
  19469. light.excludedMeshes.push(excludedMesh);
  19470. }
  19471. }
  19472. light._excludedMeshesIds = [];
  19473. }
  19474. // Included check
  19475. if (light._includedOnlyMeshesIds.length > 0) {
  19476. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19477. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19478. if (includedOnlyMesh) {
  19479. light.includedOnlyMeshes.push(includedOnlyMesh);
  19480. }
  19481. }
  19482. light._includedOnlyMeshesIds = [];
  19483. }
  19484. if (!light.canAffectMesh(mesh)) {
  19485. continue;
  19486. }
  19487. needNormals = true;
  19488. defines["LIGHT" + lightIndex] = true;
  19489. var type;
  19490. if (light instanceof BABYLON.SpotLight) {
  19491. type = "SPOTLIGHT" + lightIndex;
  19492. }
  19493. else if (light instanceof BABYLON.HemisphericLight) {
  19494. type = "HEMILIGHT" + lightIndex;
  19495. }
  19496. else if (light instanceof BABYLON.PointLight) {
  19497. type = "POINTLIGHT" + lightIndex;
  19498. }
  19499. else {
  19500. type = "DIRLIGHT" + lightIndex;
  19501. }
  19502. defines[type] = true;
  19503. // Specular
  19504. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19505. defines["SPECULARTERM"] = true;
  19506. }
  19507. // Shadows
  19508. if (scene.shadowsEnabled) {
  19509. var shadowGenerator = light.getShadowGenerator();
  19510. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19511. defines["SHADOW" + lightIndex] = true;
  19512. defines["SHADOWS"] = true;
  19513. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19514. defines["SHADOWVSM" + lightIndex] = true;
  19515. }
  19516. if (shadowGenerator.usePoissonSampling) {
  19517. defines["SHADOWPCF" + lightIndex] = true;
  19518. }
  19519. }
  19520. }
  19521. lightIndex++;
  19522. if (lightIndex === maxSimultaneousLights)
  19523. break;
  19524. }
  19525. return needNormals;
  19526. };
  19527. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19528. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19529. if (!defines["LIGHT" + lightIndex]) {
  19530. continue;
  19531. }
  19532. if (lightIndex > 0) {
  19533. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19534. }
  19535. if (defines["SHADOW" + lightIndex]) {
  19536. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19537. }
  19538. if (defines["SHADOWPCF" + lightIndex]) {
  19539. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19540. }
  19541. if (defines["SHADOWVSM" + lightIndex]) {
  19542. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19543. }
  19544. }
  19545. };
  19546. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19547. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19548. fallbacks.addCPUSkinningFallback(0, mesh);
  19549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19551. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19552. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19553. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19554. }
  19555. }
  19556. };
  19557. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19558. if (defines["INSTANCES"]) {
  19559. attribs.push("world0");
  19560. attribs.push("world1");
  19561. attribs.push("world2");
  19562. attribs.push("world3");
  19563. }
  19564. };
  19565. // Bindings
  19566. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19567. var shadowGenerator = light.getShadowGenerator();
  19568. if (mesh.receiveShadows && shadowGenerator) {
  19569. if (!light.needCube()) {
  19570. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19571. }
  19572. else {
  19573. if (!depthValuesAlreadySet) {
  19574. depthValuesAlreadySet = true;
  19575. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19576. }
  19577. }
  19578. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19579. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19580. }
  19581. return depthValuesAlreadySet;
  19582. };
  19583. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19584. if (light instanceof BABYLON.PointLight) {
  19585. // Point Light
  19586. light.transferToEffect(effect, "vLightData" + lightIndex);
  19587. }
  19588. else if (light instanceof BABYLON.DirectionalLight) {
  19589. // Directional Light
  19590. light.transferToEffect(effect, "vLightData" + lightIndex);
  19591. }
  19592. else if (light instanceof BABYLON.SpotLight) {
  19593. // Spot Light
  19594. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19595. }
  19596. else if (light instanceof BABYLON.HemisphericLight) {
  19597. // Hemispheric Light
  19598. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19599. }
  19600. };
  19601. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19602. var lightIndex = 0;
  19603. var depthValuesAlreadySet = false;
  19604. for (var index = 0; index < scene.lights.length; index++) {
  19605. var light = scene.lights[index];
  19606. if (!light.isEnabled()) {
  19607. continue;
  19608. }
  19609. if (!light.canAffectMesh(mesh)) {
  19610. continue;
  19611. }
  19612. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19613. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19614. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19615. if (defines["SPECULARTERM"]) {
  19616. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19617. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19618. }
  19619. // Shadows
  19620. if (scene.shadowsEnabled) {
  19621. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19622. }
  19623. lightIndex++;
  19624. if (lightIndex === maxSimultaneousLights)
  19625. break;
  19626. }
  19627. };
  19628. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19629. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19630. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19631. effect.setColor3("vFogColor", scene.fogColor);
  19632. }
  19633. };
  19634. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19635. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19636. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19637. }
  19638. };
  19639. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19640. if (defines["LOGARITHMICDEPTH"]) {
  19641. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19642. }
  19643. };
  19644. MaterialHelper.BindClipPlane = function (effect, scene) {
  19645. if (scene.clipPlane) {
  19646. var clipPlane = scene.clipPlane;
  19647. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19648. }
  19649. };
  19650. return MaterialHelper;
  19651. })();
  19652. BABYLON.MaterialHelper = MaterialHelper;
  19653. })(BABYLON || (BABYLON = {}));
  19654. var BABYLON;
  19655. (function (BABYLON) {
  19656. var FresnelParameters = (function () {
  19657. function FresnelParameters() {
  19658. this.isEnabled = true;
  19659. this.leftColor = BABYLON.Color3.White();
  19660. this.rightColor = BABYLON.Color3.Black();
  19661. this.bias = 0;
  19662. this.power = 1;
  19663. }
  19664. FresnelParameters.prototype.clone = function () {
  19665. var newFresnelParameters = new FresnelParameters();
  19666. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19667. return new FresnelParameters;
  19668. };
  19669. FresnelParameters.prototype.serialize = function () {
  19670. var serializationObject = {};
  19671. serializationObject.isEnabled = this.isEnabled;
  19672. serializationObject.leftColor = this.leftColor;
  19673. serializationObject.rightColor = this.rightColor;
  19674. serializationObject.bias = this.bias;
  19675. serializationObject.power = this.power;
  19676. return serializationObject;
  19677. };
  19678. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19679. var fresnelParameters = new FresnelParameters();
  19680. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19681. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19682. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19683. fresnelParameters.bias = parsedFresnelParameters.bias;
  19684. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19685. return fresnelParameters;
  19686. };
  19687. return FresnelParameters;
  19688. })();
  19689. BABYLON.FresnelParameters = FresnelParameters;
  19690. })(BABYLON || (BABYLON = {}));
  19691. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19692. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19693. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19694. 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;
  19695. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19696. };
  19697. var BABYLON;
  19698. (function (BABYLON) {
  19699. var MaterialDefines = (function () {
  19700. function MaterialDefines() {
  19701. }
  19702. MaterialDefines.prototype.isEqual = function (other) {
  19703. for (var index = 0; index < this._keys.length; index++) {
  19704. var prop = this._keys[index];
  19705. if (this[prop] !== other[prop]) {
  19706. return false;
  19707. }
  19708. }
  19709. return true;
  19710. };
  19711. MaterialDefines.prototype.cloneTo = function (other) {
  19712. for (var index = 0; index < this._keys.length; index++) {
  19713. var prop = this._keys[index];
  19714. other[prop] = this[prop];
  19715. }
  19716. };
  19717. MaterialDefines.prototype.reset = function () {
  19718. for (var index = 0; index < this._keys.length; index++) {
  19719. var prop = this._keys[index];
  19720. if (typeof (this[prop]) === "number") {
  19721. this[prop] = 0;
  19722. }
  19723. else {
  19724. this[prop] = false;
  19725. }
  19726. }
  19727. };
  19728. MaterialDefines.prototype.toString = function () {
  19729. var result = "";
  19730. for (var index = 0; index < this._keys.length; index++) {
  19731. var prop = this._keys[index];
  19732. if (typeof (this[prop]) === "number") {
  19733. result += "#define " + prop + " " + this[prop] + "\n";
  19734. }
  19735. else if (this[prop]) {
  19736. result += "#define " + prop + "\n";
  19737. }
  19738. }
  19739. return result;
  19740. };
  19741. return MaterialDefines;
  19742. })();
  19743. BABYLON.MaterialDefines = MaterialDefines;
  19744. var Material = (function () {
  19745. function Material(name, scene, doNotAdd) {
  19746. this.name = name;
  19747. this.checkReadyOnEveryCall = false;
  19748. this.checkReadyOnlyOnce = false;
  19749. this.state = "";
  19750. this.alpha = 1.0;
  19751. this.backFaceCulling = true;
  19752. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19753. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19754. this.disableDepthWrite = false;
  19755. this.fogEnabled = true;
  19756. this.pointSize = 1.0;
  19757. this.zOffset = 0;
  19758. this._wasPreviouslyReady = false;
  19759. this._fillMode = Material.TriangleFillMode;
  19760. this.id = name;
  19761. this._scene = scene;
  19762. if (!doNotAdd) {
  19763. scene.materials.push(this);
  19764. }
  19765. }
  19766. Object.defineProperty(Material, "TriangleFillMode", {
  19767. get: function () {
  19768. return Material._TriangleFillMode;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(Material, "WireFrameFillMode", {
  19774. get: function () {
  19775. return Material._WireFrameFillMode;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Material, "PointFillMode", {
  19781. get: function () {
  19782. return Material._PointFillMode;
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19788. get: function () {
  19789. return Material._ClockWiseSideOrientation;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19795. get: function () {
  19796. return Material._CounterClockWiseSideOrientation;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(Material.prototype, "wireframe", {
  19802. get: function () {
  19803. return this._fillMode === Material.WireFrameFillMode;
  19804. },
  19805. set: function (value) {
  19806. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(Material.prototype, "pointsCloud", {
  19812. get: function () {
  19813. return this._fillMode === Material.PointFillMode;
  19814. },
  19815. set: function (value) {
  19816. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Material.prototype, "fillMode", {
  19822. get: function () {
  19823. return this._fillMode;
  19824. },
  19825. set: function (value) {
  19826. this._fillMode = value;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(Material.prototype, "isFrozen", {
  19832. get: function () {
  19833. return this.checkReadyOnlyOnce;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Material.prototype.freeze = function () {
  19839. this.checkReadyOnlyOnce = true;
  19840. };
  19841. Material.prototype.unfreeze = function () {
  19842. this.checkReadyOnlyOnce = false;
  19843. };
  19844. Material.prototype.isReady = function (mesh, useInstances) {
  19845. return true;
  19846. };
  19847. Material.prototype.getEffect = function () {
  19848. return this._effect;
  19849. };
  19850. Material.prototype.getScene = function () {
  19851. return this._scene;
  19852. };
  19853. Material.prototype.needAlphaBlending = function () {
  19854. return (this.alpha < 1.0);
  19855. };
  19856. Material.prototype.needAlphaTesting = function () {
  19857. return false;
  19858. };
  19859. Material.prototype.getAlphaTestTexture = function () {
  19860. return null;
  19861. };
  19862. Material.prototype.trackCreation = function (onCompiled, onError) {
  19863. };
  19864. Material.prototype.markDirty = function () {
  19865. this._wasPreviouslyReady = false;
  19866. };
  19867. Material.prototype._preBind = function () {
  19868. var engine = this._scene.getEngine();
  19869. engine.enableEffect(this._effect);
  19870. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19871. };
  19872. Material.prototype.bind = function (world, mesh) {
  19873. this._scene._cachedMaterial = this;
  19874. if (this.onBind) {
  19875. this.onBind(this, mesh);
  19876. }
  19877. if (this.disableDepthWrite) {
  19878. var engine = this._scene.getEngine();
  19879. this._cachedDepthWriteState = engine.getDepthWrite();
  19880. engine.setDepthWrite(false);
  19881. }
  19882. };
  19883. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19884. };
  19885. Material.prototype.unbind = function () {
  19886. if (this.disableDepthWrite) {
  19887. var engine = this._scene.getEngine();
  19888. engine.setDepthWrite(this._cachedDepthWriteState);
  19889. }
  19890. };
  19891. Material.prototype.clone = function (name) {
  19892. return null;
  19893. };
  19894. Material.prototype.getBindedMeshes = function () {
  19895. var result = new Array();
  19896. for (var index = 0; index < this._scene.meshes.length; index++) {
  19897. var mesh = this._scene.meshes[index];
  19898. if (mesh.material === this) {
  19899. result.push(mesh);
  19900. }
  19901. }
  19902. return result;
  19903. };
  19904. Material.prototype.dispose = function (forceDisposeEffect) {
  19905. // Animations
  19906. this.getScene().stopAnimation(this);
  19907. // Remove from scene
  19908. var index = this._scene.materials.indexOf(this);
  19909. if (index >= 0) {
  19910. this._scene.materials.splice(index, 1);
  19911. }
  19912. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19913. if (forceDisposeEffect && this._effect) {
  19914. this._scene.getEngine()._releaseEffect(this._effect);
  19915. this._effect = null;
  19916. }
  19917. // Remove from meshes
  19918. for (index = 0; index < this._scene.meshes.length; index++) {
  19919. var mesh = this._scene.meshes[index];
  19920. if (mesh.material === this) {
  19921. mesh.material = null;
  19922. }
  19923. }
  19924. // Callback
  19925. if (this.onDispose) {
  19926. this.onDispose();
  19927. }
  19928. };
  19929. Material.prototype.serialize = function () {
  19930. return BABYLON.SerializationHelper.Serialize(this);
  19931. };
  19932. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19933. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19934. multiMaterial.id = parsedMultiMaterial.id;
  19935. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19936. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19937. var subMatId = parsedMultiMaterial.materials[matIndex];
  19938. if (subMatId) {
  19939. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19940. }
  19941. else {
  19942. multiMaterial.subMaterials.push(null);
  19943. }
  19944. }
  19945. return multiMaterial;
  19946. };
  19947. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19948. if (!parsedMaterial.customType) {
  19949. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19950. }
  19951. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19952. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19953. ;
  19954. };
  19955. Material._TriangleFillMode = 0;
  19956. Material._WireFrameFillMode = 1;
  19957. Material._PointFillMode = 2;
  19958. Material._ClockWiseSideOrientation = 0;
  19959. Material._CounterClockWiseSideOrientation = 1;
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Material.prototype, "id", void 0);
  19963. __decorate([
  19964. BABYLON.serialize()
  19965. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Material.prototype, "state", void 0);
  19972. __decorate([
  19973. BABYLON.serialize()
  19974. ], Material.prototype, "alpha", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Material.prototype, "backFaceCulling", void 0);
  19978. __decorate([
  19979. BABYLON.serialize()
  19980. ], Material.prototype, "sideOrientation", void 0);
  19981. __decorate([
  19982. BABYLON.serialize()
  19983. ], Material.prototype, "alphaMode", void 0);
  19984. __decorate([
  19985. BABYLON.serialize()
  19986. ], Material.prototype, "disableDepthWrite", void 0);
  19987. __decorate([
  19988. BABYLON.serialize()
  19989. ], Material.prototype, "fogEnabled", void 0);
  19990. __decorate([
  19991. BABYLON.serialize()
  19992. ], Material.prototype, "pointSize", void 0);
  19993. __decorate([
  19994. BABYLON.serialize()
  19995. ], Material.prototype, "zOffset", void 0);
  19996. __decorate([
  19997. BABYLON.serialize()
  19998. ], Material.prototype, "wireframe", null);
  19999. __decorate([
  20000. BABYLON.serialize()
  20001. ], Material.prototype, "pointsCloud", null);
  20002. __decorate([
  20003. BABYLON.serialize()
  20004. ], Material.prototype, "fillMode", null);
  20005. return Material;
  20006. })();
  20007. BABYLON.Material = Material;
  20008. })(BABYLON || (BABYLON = {}));
  20009. var BABYLON;
  20010. (function (BABYLON) {
  20011. var StandardMaterialDefines = (function (_super) {
  20012. __extends(StandardMaterialDefines, _super);
  20013. function StandardMaterialDefines() {
  20014. _super.call(this);
  20015. this.DIFFUSE = false;
  20016. this.AMBIENT = false;
  20017. this.OPACITY = false;
  20018. this.OPACITYRGB = false;
  20019. this.REFLECTION = false;
  20020. this.EMISSIVE = false;
  20021. this.SPECULAR = false;
  20022. this.BUMP = false;
  20023. this.PARALLAX = false;
  20024. this.PARALLAXOCCLUSION = false;
  20025. this.SPECULAROVERALPHA = false;
  20026. this.CLIPPLANE = false;
  20027. this.ALPHATEST = false;
  20028. this.ALPHAFROMDIFFUSE = false;
  20029. this.POINTSIZE = false;
  20030. this.FOG = false;
  20031. this.LIGHT0 = false;
  20032. this.LIGHT1 = false;
  20033. this.LIGHT2 = false;
  20034. this.LIGHT3 = false;
  20035. this.SPOTLIGHT0 = false;
  20036. this.SPOTLIGHT1 = false;
  20037. this.SPOTLIGHT2 = false;
  20038. this.SPOTLIGHT3 = false;
  20039. this.HEMILIGHT0 = false;
  20040. this.HEMILIGHT1 = false;
  20041. this.HEMILIGHT2 = false;
  20042. this.HEMILIGHT3 = false;
  20043. this.POINTLIGHT0 = false;
  20044. this.POINTLIGHT1 = false;
  20045. this.POINTLIGHT2 = false;
  20046. this.POINTLIGHT3 = false;
  20047. this.DIRLIGHT0 = false;
  20048. this.DIRLIGHT1 = false;
  20049. this.DIRLIGHT2 = false;
  20050. this.DIRLIGHT3 = false;
  20051. this.SPECULARTERM = false;
  20052. this.SHADOW0 = false;
  20053. this.SHADOW1 = false;
  20054. this.SHADOW2 = false;
  20055. this.SHADOW3 = false;
  20056. this.SHADOWS = false;
  20057. this.SHADOWVSM0 = false;
  20058. this.SHADOWVSM1 = false;
  20059. this.SHADOWVSM2 = false;
  20060. this.SHADOWVSM3 = false;
  20061. this.SHADOWPCF0 = false;
  20062. this.SHADOWPCF1 = false;
  20063. this.SHADOWPCF2 = false;
  20064. this.SHADOWPCF3 = false;
  20065. this.DIFFUSEFRESNEL = false;
  20066. this.OPACITYFRESNEL = false;
  20067. this.REFLECTIONFRESNEL = false;
  20068. this.REFRACTIONFRESNEL = false;
  20069. this.EMISSIVEFRESNEL = false;
  20070. this.FRESNEL = false;
  20071. this.NORMAL = false;
  20072. this.UV1 = false;
  20073. this.UV2 = false;
  20074. this.VERTEXCOLOR = false;
  20075. this.VERTEXALPHA = false;
  20076. this.NUM_BONE_INFLUENCERS = 0;
  20077. this.BonesPerMesh = 0;
  20078. this.INSTANCES = false;
  20079. this.GLOSSINESS = false;
  20080. this.ROUGHNESS = false;
  20081. this.EMISSIVEASILLUMINATION = false;
  20082. this.LINKEMISSIVEWITHDIFFUSE = false;
  20083. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20084. this.LIGHTMAP = false;
  20085. this.USELIGHTMAPASSHADOWMAP = false;
  20086. this.REFLECTIONMAP_3D = false;
  20087. this.REFLECTIONMAP_SPHERICAL = false;
  20088. this.REFLECTIONMAP_PLANAR = false;
  20089. this.REFLECTIONMAP_CUBIC = false;
  20090. this.REFLECTIONMAP_PROJECTION = false;
  20091. this.REFLECTIONMAP_SKYBOX = false;
  20092. this.REFLECTIONMAP_EXPLICIT = false;
  20093. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20094. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20095. this.INVERTCUBICMAP = false;
  20096. this.LOGARITHMICDEPTH = false;
  20097. this.REFRACTION = false;
  20098. this.REFRACTIONMAP_3D = false;
  20099. this.REFLECTIONOVERALPHA = false;
  20100. this._keys = Object.keys(this);
  20101. }
  20102. return StandardMaterialDefines;
  20103. })(BABYLON.MaterialDefines);
  20104. var StandardMaterial = (function (_super) {
  20105. __extends(StandardMaterial, _super);
  20106. function StandardMaterial(name, scene) {
  20107. var _this = this;
  20108. _super.call(this, name, scene);
  20109. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20110. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20111. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20112. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20113. this.specularPower = 64;
  20114. this.useAlphaFromDiffuseTexture = false;
  20115. this.useEmissiveAsIllumination = false;
  20116. this.linkEmissiveWithDiffuse = false;
  20117. this.useReflectionFresnelFromSpecular = false;
  20118. this.useSpecularOverAlpha = false;
  20119. this.useReflectionOverAlpha = false;
  20120. this.disableLighting = false;
  20121. this.useParallax = false;
  20122. this.useParallaxOcclusion = false;
  20123. this.parallaxScaleBias = 0.05;
  20124. this.roughness = 0;
  20125. this.indexOfRefraction = 0.98;
  20126. this.invertRefractionY = true;
  20127. this.useLightmapAsShadowmap = false;
  20128. this.useGlossinessFromSpecularMapAlpha = false;
  20129. this._renderTargets = new BABYLON.SmartArray(16);
  20130. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20131. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20132. this._defines = new StandardMaterialDefines();
  20133. this._cachedDefines = new StandardMaterialDefines();
  20134. this._cachedDefines.BonesPerMesh = -1;
  20135. this.getRenderTargetTextures = function () {
  20136. _this._renderTargets.reset();
  20137. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20138. _this._renderTargets.push(_this.reflectionTexture);
  20139. }
  20140. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20141. _this._renderTargets.push(_this.refractionTexture);
  20142. }
  20143. return _this._renderTargets;
  20144. };
  20145. }
  20146. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20147. get: function () {
  20148. return this._useLogarithmicDepth;
  20149. },
  20150. set: function (value) {
  20151. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. StandardMaterial.prototype.needAlphaBlending = function () {
  20157. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20158. };
  20159. StandardMaterial.prototype.needAlphaTesting = function () {
  20160. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20161. };
  20162. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20163. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20164. };
  20165. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20166. return this.diffuseTexture;
  20167. };
  20168. // Methods
  20169. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20170. if (!mesh) {
  20171. return true;
  20172. }
  20173. if (this._defines.INSTANCES !== useInstances) {
  20174. return false;
  20175. }
  20176. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20177. return true;
  20178. }
  20179. return false;
  20180. };
  20181. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20182. if (this.isFrozen) {
  20183. if (this._wasPreviouslyReady) {
  20184. return true;
  20185. }
  20186. }
  20187. var scene = this.getScene();
  20188. if (!this.checkReadyOnEveryCall) {
  20189. if (this._renderId === scene.getRenderId()) {
  20190. if (this._checkCache(scene, mesh, useInstances)) {
  20191. return true;
  20192. }
  20193. }
  20194. }
  20195. var engine = scene.getEngine();
  20196. var needNormals = false;
  20197. var needUVs = false;
  20198. this._defines.reset();
  20199. // Textures
  20200. if (scene.texturesEnabled) {
  20201. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20202. if (!this.diffuseTexture.isReady()) {
  20203. return false;
  20204. }
  20205. else {
  20206. needUVs = true;
  20207. this._defines.DIFFUSE = true;
  20208. }
  20209. }
  20210. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20211. if (!this.ambientTexture.isReady()) {
  20212. return false;
  20213. }
  20214. else {
  20215. needUVs = true;
  20216. this._defines.AMBIENT = true;
  20217. }
  20218. }
  20219. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20220. if (!this.opacityTexture.isReady()) {
  20221. return false;
  20222. }
  20223. else {
  20224. needUVs = true;
  20225. this._defines.OPACITY = true;
  20226. if (this.opacityTexture.getAlphaFromRGB) {
  20227. this._defines.OPACITYRGB = true;
  20228. }
  20229. }
  20230. }
  20231. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20232. if (!this.reflectionTexture.isReady()) {
  20233. return false;
  20234. }
  20235. else {
  20236. needNormals = true;
  20237. this._defines.REFLECTION = true;
  20238. if (this.roughness > 0) {
  20239. this._defines.ROUGHNESS = true;
  20240. }
  20241. if (this.useReflectionOverAlpha) {
  20242. this._defines.REFLECTIONOVERALPHA = true;
  20243. }
  20244. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20245. this._defines.INVERTCUBICMAP = true;
  20246. }
  20247. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20248. switch (this.reflectionTexture.coordinatesMode) {
  20249. case BABYLON.Texture.CUBIC_MODE:
  20250. case BABYLON.Texture.INVCUBIC_MODE:
  20251. this._defines.REFLECTIONMAP_CUBIC = true;
  20252. break;
  20253. case BABYLON.Texture.EXPLICIT_MODE:
  20254. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20255. break;
  20256. case BABYLON.Texture.PLANAR_MODE:
  20257. this._defines.REFLECTIONMAP_PLANAR = true;
  20258. break;
  20259. case BABYLON.Texture.PROJECTION_MODE:
  20260. this._defines.REFLECTIONMAP_PROJECTION = true;
  20261. break;
  20262. case BABYLON.Texture.SKYBOX_MODE:
  20263. this._defines.REFLECTIONMAP_SKYBOX = true;
  20264. break;
  20265. case BABYLON.Texture.SPHERICAL_MODE:
  20266. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20267. break;
  20268. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20269. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20270. break;
  20271. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20272. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20273. break;
  20274. }
  20275. }
  20276. }
  20277. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20278. if (!this.emissiveTexture.isReady()) {
  20279. return false;
  20280. }
  20281. else {
  20282. needUVs = true;
  20283. this._defines.EMISSIVE = true;
  20284. }
  20285. }
  20286. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20287. if (!this.lightmapTexture.isReady()) {
  20288. return false;
  20289. }
  20290. else {
  20291. needUVs = true;
  20292. this._defines.LIGHTMAP = true;
  20293. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20294. }
  20295. }
  20296. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20297. if (!this.specularTexture.isReady()) {
  20298. return false;
  20299. }
  20300. else {
  20301. needUVs = true;
  20302. this._defines.SPECULAR = true;
  20303. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20304. }
  20305. }
  20306. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20307. if (!this.bumpTexture.isReady()) {
  20308. return false;
  20309. }
  20310. else {
  20311. needUVs = true;
  20312. this._defines.BUMP = true;
  20313. if (this.useParallax) {
  20314. this._defines.PARALLAX = true;
  20315. if (this.useParallaxOcclusion) {
  20316. this._defines.PARALLAXOCCLUSION = true;
  20317. }
  20318. }
  20319. }
  20320. }
  20321. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20322. if (!this.refractionTexture.isReady()) {
  20323. return false;
  20324. }
  20325. else {
  20326. needUVs = true;
  20327. this._defines.REFRACTION = true;
  20328. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20329. }
  20330. }
  20331. }
  20332. // Effect
  20333. if (scene.clipPlane) {
  20334. this._defines.CLIPPLANE = true;
  20335. }
  20336. if (engine.getAlphaTesting()) {
  20337. this._defines.ALPHATEST = true;
  20338. }
  20339. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20340. this._defines.ALPHAFROMDIFFUSE = true;
  20341. }
  20342. if (this.useEmissiveAsIllumination) {
  20343. this._defines.EMISSIVEASILLUMINATION = true;
  20344. }
  20345. if (this.linkEmissiveWithDiffuse) {
  20346. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20347. }
  20348. if (this.useLogarithmicDepth) {
  20349. this._defines.LOGARITHMICDEPTH = true;
  20350. }
  20351. // Point size
  20352. if (this.pointsCloud || scene.forcePointsCloud) {
  20353. this._defines.POINTSIZE = true;
  20354. }
  20355. // Fog
  20356. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20357. this._defines.FOG = true;
  20358. }
  20359. if (scene.lightsEnabled && !this.disableLighting) {
  20360. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20361. }
  20362. if (StandardMaterial.FresnelEnabled) {
  20363. // Fresnel
  20364. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20365. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20366. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20367. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20368. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20369. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20370. this._defines.DIFFUSEFRESNEL = true;
  20371. }
  20372. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20373. this._defines.OPACITYFRESNEL = true;
  20374. }
  20375. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20376. this._defines.REFLECTIONFRESNEL = true;
  20377. if (this.useReflectionFresnelFromSpecular) {
  20378. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20379. }
  20380. }
  20381. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20382. this._defines.REFRACTIONFRESNEL = true;
  20383. }
  20384. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20385. this._defines.EMISSIVEFRESNEL = true;
  20386. }
  20387. needNormals = true;
  20388. this._defines.FRESNEL = true;
  20389. }
  20390. }
  20391. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20392. this._defines.SPECULAROVERALPHA = true;
  20393. }
  20394. // Attribs
  20395. if (mesh) {
  20396. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20397. this._defines.NORMAL = true;
  20398. }
  20399. if (needUVs) {
  20400. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20401. this._defines.UV1 = true;
  20402. }
  20403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20404. this._defines.UV2 = true;
  20405. }
  20406. }
  20407. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20408. this._defines.VERTEXCOLOR = true;
  20409. if (mesh.hasVertexAlpha) {
  20410. this._defines.VERTEXALPHA = true;
  20411. }
  20412. }
  20413. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20414. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20415. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20416. }
  20417. // Instances
  20418. if (useInstances) {
  20419. this._defines.INSTANCES = true;
  20420. }
  20421. }
  20422. // Get correct effect
  20423. if (!this._defines.isEqual(this._cachedDefines)) {
  20424. this._defines.cloneTo(this._cachedDefines);
  20425. scene.resetCachedMaterial();
  20426. // Fallbacks
  20427. var fallbacks = new BABYLON.EffectFallbacks();
  20428. if (this._defines.REFLECTION) {
  20429. fallbacks.addFallback(0, "REFLECTION");
  20430. }
  20431. if (this._defines.SPECULAR) {
  20432. fallbacks.addFallback(0, "SPECULAR");
  20433. }
  20434. if (this._defines.BUMP) {
  20435. fallbacks.addFallback(0, "BUMP");
  20436. }
  20437. if (this._defines.PARALLAX) {
  20438. fallbacks.addFallback(1, "PARALLAX");
  20439. }
  20440. if (this._defines.PARALLAXOCCLUSION) {
  20441. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20442. }
  20443. if (this._defines.SPECULAROVERALPHA) {
  20444. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20445. }
  20446. if (this._defines.FOG) {
  20447. fallbacks.addFallback(1, "FOG");
  20448. }
  20449. if (this._defines.POINTSIZE) {
  20450. fallbacks.addFallback(0, "POINTSIZE");
  20451. }
  20452. if (this._defines.LOGARITHMICDEPTH) {
  20453. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20454. }
  20455. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20456. if (this._defines.SPECULARTERM) {
  20457. fallbacks.addFallback(0, "SPECULARTERM");
  20458. }
  20459. if (this._defines.DIFFUSEFRESNEL) {
  20460. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20461. }
  20462. if (this._defines.OPACITYFRESNEL) {
  20463. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20464. }
  20465. if (this._defines.REFLECTIONFRESNEL) {
  20466. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20467. }
  20468. if (this._defines.EMISSIVEFRESNEL) {
  20469. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20470. }
  20471. if (this._defines.FRESNEL) {
  20472. fallbacks.addFallback(4, "FRESNEL");
  20473. }
  20474. //Attributes
  20475. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20476. if (this._defines.NORMAL) {
  20477. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20478. }
  20479. if (this._defines.UV1) {
  20480. attribs.push(BABYLON.VertexBuffer.UVKind);
  20481. }
  20482. if (this._defines.UV2) {
  20483. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20484. }
  20485. if (this._defines.VERTEXCOLOR) {
  20486. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20487. }
  20488. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20489. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20490. // Legacy browser patch
  20491. var shaderName = "default";
  20492. if (!scene.getEngine().getCaps().standardDerivatives) {
  20493. shaderName = "legacydefault";
  20494. }
  20495. var join = this._defines.toString();
  20496. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20497. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20498. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20499. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20500. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20501. "vFogInfos", "vFogColor", "pointSize",
  20502. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20503. "mBones",
  20504. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20505. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20506. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20507. "logarithmicDepthConstant"
  20508. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20509. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20510. ], join, fallbacks, this.onCompiled, this.onError);
  20511. }
  20512. if (!this._effect.isReady()) {
  20513. return false;
  20514. }
  20515. this._renderId = scene.getRenderId();
  20516. this._wasPreviouslyReady = true;
  20517. if (mesh) {
  20518. if (!mesh._materialDefines) {
  20519. mesh._materialDefines = new StandardMaterialDefines();
  20520. }
  20521. this._defines.cloneTo(mesh._materialDefines);
  20522. }
  20523. return true;
  20524. };
  20525. StandardMaterial.prototype.unbind = function () {
  20526. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20527. this._effect.setTexture("reflection2DSampler", null);
  20528. }
  20529. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20530. this._effect.setTexture("refraction2DSampler", null);
  20531. }
  20532. _super.prototype.unbind.call(this);
  20533. };
  20534. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20535. this._effect.setMatrix("world", world);
  20536. };
  20537. StandardMaterial.prototype.bind = function (world, mesh) {
  20538. var scene = this.getScene();
  20539. // Matrices
  20540. this.bindOnlyWorldMatrix(world);
  20541. // Bones
  20542. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20543. if (scene.getCachedMaterial() !== this) {
  20544. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20545. if (StandardMaterial.FresnelEnabled) {
  20546. // Fresnel
  20547. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20548. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20549. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20550. }
  20551. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20552. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20553. }
  20554. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20555. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20556. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20557. }
  20558. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20559. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20560. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20561. }
  20562. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20563. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20564. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20565. }
  20566. }
  20567. // Textures
  20568. if (scene.texturesEnabled) {
  20569. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20570. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20571. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20572. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20573. }
  20574. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20575. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20576. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20577. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20578. }
  20579. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20580. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20581. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20582. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20583. }
  20584. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20585. if (this.reflectionTexture.isCube) {
  20586. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20587. }
  20588. else {
  20589. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20590. }
  20591. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20592. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20593. }
  20594. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20595. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20596. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20597. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20598. }
  20599. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20600. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20601. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20602. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20603. }
  20604. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20605. this._effect.setTexture("specularSampler", this.specularTexture);
  20606. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20607. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20608. }
  20609. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20610. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20611. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20612. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20613. }
  20614. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20615. var depth = 1.0;
  20616. if (this.refractionTexture.isCube) {
  20617. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20618. }
  20619. else {
  20620. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20621. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20622. if (this.refractionTexture.depth) {
  20623. depth = this.refractionTexture.depth;
  20624. }
  20625. }
  20626. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20627. }
  20628. }
  20629. // Clip plane
  20630. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20631. // Point size
  20632. if (this.pointsCloud) {
  20633. this._effect.setFloat("pointSize", this.pointSize);
  20634. }
  20635. // Colors
  20636. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20637. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20638. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20639. if (this._defines.SPECULARTERM) {
  20640. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20641. }
  20642. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20643. }
  20644. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20645. // Diffuse
  20646. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20647. // Lights
  20648. if (scene.lightsEnabled && !this.disableLighting) {
  20649. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20650. }
  20651. // View
  20652. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20653. this._effect.setMatrix("view", scene.getViewMatrix());
  20654. }
  20655. // Fog
  20656. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20657. // Log. depth
  20658. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20659. }
  20660. _super.prototype.bind.call(this, world, mesh);
  20661. };
  20662. StandardMaterial.prototype.getAnimatables = function () {
  20663. var results = [];
  20664. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20665. results.push(this.diffuseTexture);
  20666. }
  20667. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20668. results.push(this.ambientTexture);
  20669. }
  20670. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20671. results.push(this.opacityTexture);
  20672. }
  20673. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20674. results.push(this.reflectionTexture);
  20675. }
  20676. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20677. results.push(this.emissiveTexture);
  20678. }
  20679. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20680. results.push(this.specularTexture);
  20681. }
  20682. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20683. results.push(this.bumpTexture);
  20684. }
  20685. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20686. results.push(this.lightmapTexture);
  20687. }
  20688. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20689. results.push(this.refractionTexture);
  20690. }
  20691. return results;
  20692. };
  20693. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20694. if (this.diffuseTexture) {
  20695. this.diffuseTexture.dispose();
  20696. }
  20697. if (this.ambientTexture) {
  20698. this.ambientTexture.dispose();
  20699. }
  20700. if (this.opacityTexture) {
  20701. this.opacityTexture.dispose();
  20702. }
  20703. if (this.reflectionTexture) {
  20704. this.reflectionTexture.dispose();
  20705. }
  20706. if (this.emissiveTexture) {
  20707. this.emissiveTexture.dispose();
  20708. }
  20709. if (this.specularTexture) {
  20710. this.specularTexture.dispose();
  20711. }
  20712. if (this.bumpTexture) {
  20713. this.bumpTexture.dispose();
  20714. }
  20715. if (this.lightmapTexture) {
  20716. this.lightmapTexture.dispose();
  20717. }
  20718. if (this.refractionTexture) {
  20719. this.refractionTexture.dispose();
  20720. }
  20721. _super.prototype.dispose.call(this, forceDisposeEffect);
  20722. };
  20723. StandardMaterial.prototype.clone = function (name) {
  20724. var _this = this;
  20725. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20726. };
  20727. StandardMaterial.prototype.serialize = function () {
  20728. return BABYLON.SerializationHelper.Serialize(this);
  20729. };
  20730. // Statics
  20731. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20732. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20733. };
  20734. // Flags used to enable or disable a type of texture for all Standard Materials
  20735. StandardMaterial.DiffuseTextureEnabled = true;
  20736. StandardMaterial.AmbientTextureEnabled = true;
  20737. StandardMaterial.OpacityTextureEnabled = true;
  20738. StandardMaterial.ReflectionTextureEnabled = true;
  20739. StandardMaterial.EmissiveTextureEnabled = true;
  20740. StandardMaterial.SpecularTextureEnabled = true;
  20741. StandardMaterial.BumpTextureEnabled = true;
  20742. StandardMaterial.FresnelEnabled = true;
  20743. StandardMaterial.LightmapTextureEnabled = true;
  20744. StandardMaterial.RefractionTextureEnabled = true;
  20745. __decorate([
  20746. BABYLON.serializeAsTexture()
  20747. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20748. __decorate([
  20749. BABYLON.serializeAsTexture()
  20750. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20751. __decorate([
  20752. BABYLON.serializeAsTexture()
  20753. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20754. __decorate([
  20755. BABYLON.serializeAsTexture()
  20756. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20757. __decorate([
  20758. BABYLON.serializeAsTexture()
  20759. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20760. __decorate([
  20761. BABYLON.serializeAsTexture()
  20762. ], StandardMaterial.prototype, "specularTexture", void 0);
  20763. __decorate([
  20764. BABYLON.serializeAsTexture()
  20765. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20766. __decorate([
  20767. BABYLON.serializeAsTexture()
  20768. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20769. __decorate([
  20770. BABYLON.serializeAsTexture()
  20771. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20772. __decorate([
  20773. BABYLON.serializeAsColor3("ambient")
  20774. ], StandardMaterial.prototype, "ambientColor", void 0);
  20775. __decorate([
  20776. BABYLON.serializeAsColor3("diffuse")
  20777. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20778. __decorate([
  20779. BABYLON.serializeAsColor3("specular")
  20780. ], StandardMaterial.prototype, "specularColor", void 0);
  20781. __decorate([
  20782. BABYLON.serializeAsColor3("emissive")
  20783. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20784. __decorate([
  20785. BABYLON.serialize()
  20786. ], StandardMaterial.prototype, "specularPower", void 0);
  20787. __decorate([
  20788. BABYLON.serialize()
  20789. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20790. __decorate([
  20791. BABYLON.serialize()
  20792. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20793. __decorate([
  20794. BABYLON.serialize()
  20795. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20796. __decorate([
  20797. BABYLON.serialize()
  20798. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20799. __decorate([
  20800. BABYLON.serialize()
  20801. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20802. __decorate([
  20803. BABYLON.serialize()
  20804. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20805. __decorate([
  20806. BABYLON.serialize()
  20807. ], StandardMaterial.prototype, "disableLighting", void 0);
  20808. __decorate([
  20809. BABYLON.serialize()
  20810. ], StandardMaterial.prototype, "useParallax", void 0);
  20811. __decorate([
  20812. BABYLON.serialize()
  20813. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20814. __decorate([
  20815. BABYLON.serialize()
  20816. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20817. __decorate([
  20818. BABYLON.serialize()
  20819. ], StandardMaterial.prototype, "roughness", void 0);
  20820. __decorate([
  20821. BABYLON.serialize()
  20822. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20823. __decorate([
  20824. BABYLON.serialize()
  20825. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20826. __decorate([
  20827. BABYLON.serialize()
  20828. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20829. __decorate([
  20830. BABYLON.serializeAsFresnelParameters()
  20831. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20832. __decorate([
  20833. BABYLON.serializeAsFresnelParameters()
  20834. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20835. __decorate([
  20836. BABYLON.serializeAsFresnelParameters()
  20837. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20838. __decorate([
  20839. BABYLON.serializeAsFresnelParameters()
  20840. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20841. __decorate([
  20842. BABYLON.serializeAsFresnelParameters()
  20843. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20844. __decorate([
  20845. BABYLON.serialize()
  20846. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20847. __decorate([
  20848. BABYLON.serialize()
  20849. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20850. return StandardMaterial;
  20851. })(BABYLON.Material);
  20852. BABYLON.StandardMaterial = StandardMaterial;
  20853. })(BABYLON || (BABYLON = {}));
  20854. var BABYLON;
  20855. (function (BABYLON) {
  20856. var MultiMaterial = (function (_super) {
  20857. __extends(MultiMaterial, _super);
  20858. function MultiMaterial(name, scene) {
  20859. _super.call(this, name, scene, true);
  20860. this.subMaterials = new Array();
  20861. scene.multiMaterials.push(this);
  20862. }
  20863. // Properties
  20864. MultiMaterial.prototype.getSubMaterial = function (index) {
  20865. if (index < 0 || index >= this.subMaterials.length) {
  20866. return this.getScene().defaultMaterial;
  20867. }
  20868. return this.subMaterials[index];
  20869. };
  20870. // Methods
  20871. MultiMaterial.prototype.isReady = function (mesh) {
  20872. for (var index = 0; index < this.subMaterials.length; index++) {
  20873. var subMaterial = this.subMaterials[index];
  20874. if (subMaterial) {
  20875. if (!this.subMaterials[index].isReady(mesh)) {
  20876. return false;
  20877. }
  20878. }
  20879. }
  20880. return true;
  20881. };
  20882. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20883. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20884. for (var index = 0; index < this.subMaterials.length; index++) {
  20885. var subMaterial = null;
  20886. if (cloneChildren) {
  20887. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20888. }
  20889. else {
  20890. subMaterial = this.subMaterials[index];
  20891. }
  20892. newMultiMaterial.subMaterials.push(subMaterial);
  20893. }
  20894. return newMultiMaterial;
  20895. };
  20896. MultiMaterial.prototype.serialize = function () {
  20897. var serializationObject = {};
  20898. serializationObject.name = this.name;
  20899. serializationObject.id = this.id;
  20900. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20901. serializationObject.materials = [];
  20902. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20903. var subMat = this.subMaterials[matIndex];
  20904. if (subMat) {
  20905. serializationObject.materials.push(subMat.id);
  20906. }
  20907. else {
  20908. serializationObject.materials.push(null);
  20909. }
  20910. }
  20911. return serializationObject;
  20912. };
  20913. return MultiMaterial;
  20914. })(BABYLON.Material);
  20915. BABYLON.MultiMaterial = MultiMaterial;
  20916. })(BABYLON || (BABYLON = {}));
  20917. var BABYLON;
  20918. (function (BABYLON) {
  20919. var SceneLoader = (function () {
  20920. function SceneLoader() {
  20921. }
  20922. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20923. get: function () {
  20924. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20925. },
  20926. set: function (value) {
  20927. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20928. },
  20929. enumerable: true,
  20930. configurable: true
  20931. });
  20932. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20933. get: function () {
  20934. return SceneLoader._ShowLoadingScreen;
  20935. },
  20936. set: function (value) {
  20937. SceneLoader._ShowLoadingScreen = value;
  20938. },
  20939. enumerable: true,
  20940. configurable: true
  20941. });
  20942. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20943. var dotPosition = sceneFilename.lastIndexOf(".");
  20944. var queryStringPosition = sceneFilename.indexOf("?");
  20945. if (queryStringPosition === -1) {
  20946. queryStringPosition = sceneFilename.length;
  20947. }
  20948. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20949. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20950. var plugin = this._registeredPlugins[index];
  20951. if (plugin.extensions.indexOf(extension) !== -1) {
  20952. return plugin;
  20953. }
  20954. }
  20955. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20956. };
  20957. // Public functions
  20958. SceneLoader.GetPluginForExtension = function (extension) {
  20959. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20960. var plugin = this._registeredPlugins[index];
  20961. if (plugin.extensions.indexOf(extension) !== -1) {
  20962. return plugin;
  20963. }
  20964. }
  20965. return null;
  20966. };
  20967. SceneLoader.RegisterPlugin = function (plugin) {
  20968. plugin.extensions = plugin.extensions.toLowerCase();
  20969. SceneLoader._registeredPlugins.push(plugin);
  20970. };
  20971. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20972. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20973. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20974. return;
  20975. }
  20976. var loadingToken = {};
  20977. scene._addPendingData(loadingToken);
  20978. var manifestChecked = function (success) {
  20979. scene.database = database;
  20980. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20981. var importMeshFromData = function (data) {
  20982. var meshes = [];
  20983. var particleSystems = [];
  20984. var skeletons = [];
  20985. try {
  20986. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20987. if (onerror) {
  20988. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20989. }
  20990. scene._removePendingData(loadingToken);
  20991. return;
  20992. }
  20993. }
  20994. catch (e) {
  20995. if (onerror) {
  20996. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20997. }
  20998. scene._removePendingData(loadingToken);
  20999. return;
  21000. }
  21001. if (onsuccess) {
  21002. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  21003. onsuccess(meshes, particleSystems, skeletons);
  21004. scene._removePendingData(loadingToken);
  21005. }
  21006. };
  21007. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21008. // Direct load
  21009. importMeshFromData(sceneFilename.substr(5));
  21010. return;
  21011. }
  21012. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  21013. importMeshFromData(data);
  21014. }, progressCallBack, database);
  21015. };
  21016. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21017. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21018. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21019. }
  21020. else {
  21021. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21022. manifestChecked(true);
  21023. }
  21024. };
  21025. /**
  21026. * Load a scene
  21027. * @param rootUrl a string that defines the root url for scene and resources
  21028. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21029. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21030. */
  21031. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21032. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21033. };
  21034. /**
  21035. * Append a scene
  21036. * @param rootUrl a string that defines the root url for scene and resources
  21037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21038. * @param scene is the instance of BABYLON.Scene to append to
  21039. */
  21040. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21041. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21042. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21043. return;
  21044. }
  21045. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21046. var database;
  21047. var loadingToken = {};
  21048. scene._addPendingData(loadingToken);
  21049. if (SceneLoader.ShowLoadingScreen) {
  21050. scene.getEngine().displayLoadingUI();
  21051. }
  21052. var loadSceneFromData = function (data) {
  21053. scene.database = database;
  21054. if (!plugin.load(scene, data, rootUrl)) {
  21055. if (onerror) {
  21056. onerror(scene);
  21057. }
  21058. scene._removePendingData(loadingToken);
  21059. scene.getEngine().hideLoadingUI();
  21060. return;
  21061. }
  21062. if (onsuccess) {
  21063. onsuccess(scene);
  21064. }
  21065. scene._removePendingData(loadingToken);
  21066. if (SceneLoader.ShowLoadingScreen) {
  21067. scene.executeWhenReady(function () {
  21068. scene.getEngine().hideLoadingUI();
  21069. });
  21070. }
  21071. };
  21072. var manifestChecked = function (success) {
  21073. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21074. };
  21075. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21076. // Direct load
  21077. loadSceneFromData(sceneFilename.substr(5));
  21078. return;
  21079. }
  21080. if (rootUrl.indexOf("file:") === -1) {
  21081. if (scene.getEngine().enableOfflineSupport) {
  21082. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21083. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21084. }
  21085. else {
  21086. manifestChecked(true);
  21087. }
  21088. }
  21089. else {
  21090. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21091. }
  21092. };
  21093. // Flags
  21094. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21095. SceneLoader._ShowLoadingScreen = true;
  21096. // Members
  21097. SceneLoader._registeredPlugins = new Array();
  21098. return SceneLoader;
  21099. })();
  21100. BABYLON.SceneLoader = SceneLoader;
  21101. ;
  21102. })(BABYLON || (BABYLON = {}));
  21103. var BABYLON;
  21104. (function (BABYLON) {
  21105. var Internals;
  21106. (function (Internals) {
  21107. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21108. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21109. var parsedMaterial = parsedData.materials[index];
  21110. if (parsedMaterial.id === id) {
  21111. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21112. }
  21113. }
  21114. return null;
  21115. };
  21116. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21117. names = (names instanceof Array) ? names : [names];
  21118. for (var i in names) {
  21119. if (mesh.name === names[i]) {
  21120. hierarchyIds.push(mesh.id);
  21121. return true;
  21122. }
  21123. }
  21124. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21125. hierarchyIds.push(mesh.id);
  21126. return true;
  21127. }
  21128. return false;
  21129. };
  21130. BABYLON.SceneLoader.RegisterPlugin({
  21131. extensions: ".babylon",
  21132. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21133. var parsedData = JSON.parse(data);
  21134. var loadedSkeletonsIds = [];
  21135. var loadedMaterialsIds = [];
  21136. var hierarchyIds = [];
  21137. var index;
  21138. var cache;
  21139. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21140. var parsedMesh = parsedData.meshes[index];
  21141. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21142. if (meshesNames instanceof Array) {
  21143. // Remove found mesh name from list.
  21144. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21145. }
  21146. //Geometry?
  21147. if (parsedMesh.geometryId) {
  21148. //does the file contain geometries?
  21149. if (parsedData.geometries) {
  21150. //find the correct geometry and add it to the scene
  21151. var found = false;
  21152. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21153. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21154. return;
  21155. }
  21156. else {
  21157. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21158. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21159. switch (geometryType) {
  21160. case "boxes":
  21161. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21162. break;
  21163. case "spheres":
  21164. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21165. break;
  21166. case "cylinders":
  21167. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21168. break;
  21169. case "toruses":
  21170. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21171. break;
  21172. case "grounds":
  21173. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21174. break;
  21175. case "planes":
  21176. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21177. break;
  21178. case "torusKnots":
  21179. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21180. break;
  21181. case "vertexData":
  21182. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21183. break;
  21184. }
  21185. found = true;
  21186. }
  21187. });
  21188. }
  21189. });
  21190. if (!found) {
  21191. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21192. }
  21193. }
  21194. }
  21195. // Material ?
  21196. if (parsedMesh.materialId) {
  21197. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21198. if (!materialFound && parsedData.multiMaterials) {
  21199. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21200. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21201. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21202. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21203. var subMatId = parsedMultiMaterial.materials[matIndex];
  21204. loadedMaterialsIds.push(subMatId);
  21205. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21206. }
  21207. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21208. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21209. materialFound = true;
  21210. break;
  21211. }
  21212. }
  21213. }
  21214. if (!materialFound) {
  21215. loadedMaterialsIds.push(parsedMesh.materialId);
  21216. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21217. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21218. }
  21219. }
  21220. }
  21221. // Skeleton ?
  21222. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21223. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21224. if (!skeletonAlreadyLoaded) {
  21225. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21226. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21227. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21228. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21229. loadedSkeletonsIds.push(parsedSkeleton.id);
  21230. }
  21231. }
  21232. }
  21233. }
  21234. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21235. meshes.push(mesh);
  21236. }
  21237. }
  21238. // Connecting parents
  21239. var currentMesh;
  21240. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21241. currentMesh = scene.meshes[index];
  21242. if (currentMesh._waitingParentId) {
  21243. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21244. currentMesh._waitingParentId = undefined;
  21245. }
  21246. }
  21247. // freeze and compute world matrix application
  21248. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21249. currentMesh = scene.meshes[index];
  21250. if (currentMesh._waitingFreezeWorldMatrix) {
  21251. currentMesh.freezeWorldMatrix();
  21252. currentMesh._waitingFreezeWorldMatrix = undefined;
  21253. }
  21254. else {
  21255. currentMesh.computeWorldMatrix(true);
  21256. }
  21257. }
  21258. // Particles
  21259. if (parsedData.particleSystems) {
  21260. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21261. var parsedParticleSystem = parsedData.particleSystems[index];
  21262. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21263. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21264. }
  21265. }
  21266. }
  21267. return true;
  21268. },
  21269. load: function (scene, data, rootUrl) {
  21270. var parsedData = JSON.parse(data);
  21271. // Scene
  21272. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21273. scene.autoClear = parsedData.autoClear;
  21274. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21275. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21276. if (parsedData.gravity) {
  21277. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21278. }
  21279. // Fog
  21280. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21281. scene.fogMode = parsedData.fogMode;
  21282. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21283. scene.fogStart = parsedData.fogStart;
  21284. scene.fogEnd = parsedData.fogEnd;
  21285. scene.fogDensity = parsedData.fogDensity;
  21286. }
  21287. //Physics
  21288. if (parsedData.physicsEnabled) {
  21289. var physicsPlugin;
  21290. if (parsedData.physicsEngine === "cannon") {
  21291. physicsPlugin = new BABYLON.CannonJSPlugin();
  21292. }
  21293. else if (parsedData.physicsEngine === "oimo") {
  21294. physicsPlugin = new BABYLON.OimoJSPlugin();
  21295. }
  21296. //else - default engine, which is currently oimo
  21297. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21298. scene.enablePhysics(physicsGravity, physicsPlugin);
  21299. }
  21300. //collisions, if defined. otherwise, default is true
  21301. if (parsedData.collisionsEnabled != undefined) {
  21302. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21303. }
  21304. scene.workerCollisions = !!parsedData.workerCollisions;
  21305. var index;
  21306. var cache;
  21307. // Lights
  21308. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21309. var parsedLight = parsedData.lights[index];
  21310. BABYLON.Light.Parse(parsedLight, scene);
  21311. }
  21312. // Animations
  21313. if (parsedData.animations) {
  21314. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21315. var parsedAnimation = parsedData.animations[index];
  21316. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21317. }
  21318. }
  21319. if (parsedData.autoAnimate) {
  21320. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  21321. }
  21322. // Materials
  21323. if (parsedData.materials) {
  21324. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21325. var parsedMaterial = parsedData.materials[index];
  21326. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21327. }
  21328. }
  21329. if (parsedData.multiMaterials) {
  21330. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21331. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21332. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21333. }
  21334. }
  21335. // Skeletons
  21336. if (parsedData.skeletons) {
  21337. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21338. var parsedSkeleton = parsedData.skeletons[index];
  21339. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21340. }
  21341. }
  21342. // Geometries
  21343. var geometries = parsedData.geometries;
  21344. if (geometries) {
  21345. // Boxes
  21346. var boxes = geometries.boxes;
  21347. if (boxes) {
  21348. for (index = 0, cache = boxes.length; index < cache; index++) {
  21349. var parsedBox = boxes[index];
  21350. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21351. }
  21352. }
  21353. // Spheres
  21354. var spheres = geometries.spheres;
  21355. if (spheres) {
  21356. for (index = 0, cache = spheres.length; index < cache; index++) {
  21357. var parsedSphere = spheres[index];
  21358. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21359. }
  21360. }
  21361. // Cylinders
  21362. var cylinders = geometries.cylinders;
  21363. if (cylinders) {
  21364. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21365. var parsedCylinder = cylinders[index];
  21366. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21367. }
  21368. }
  21369. // Toruses
  21370. var toruses = geometries.toruses;
  21371. if (toruses) {
  21372. for (index = 0, cache = toruses.length; index < cache; index++) {
  21373. var parsedTorus = toruses[index];
  21374. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21375. }
  21376. }
  21377. // Grounds
  21378. var grounds = geometries.grounds;
  21379. if (grounds) {
  21380. for (index = 0, cache = grounds.length; index < cache; index++) {
  21381. var parsedGround = grounds[index];
  21382. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21383. }
  21384. }
  21385. // Planes
  21386. var planes = geometries.planes;
  21387. if (planes) {
  21388. for (index = 0, cache = planes.length; index < cache; index++) {
  21389. var parsedPlane = planes[index];
  21390. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21391. }
  21392. }
  21393. // TorusKnots
  21394. var torusKnots = geometries.torusKnots;
  21395. if (torusKnots) {
  21396. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21397. var parsedTorusKnot = torusKnots[index];
  21398. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21399. }
  21400. }
  21401. // VertexData
  21402. var vertexData = geometries.vertexData;
  21403. if (vertexData) {
  21404. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21405. var parsedVertexData = vertexData[index];
  21406. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21407. }
  21408. }
  21409. }
  21410. // Meshes
  21411. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21412. var parsedMesh = parsedData.meshes[index];
  21413. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21414. }
  21415. // Cameras
  21416. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21417. var parsedCamera = parsedData.cameras[index];
  21418. BABYLON.Camera.Parse(parsedCamera, scene);
  21419. }
  21420. if (parsedData.activeCameraID) {
  21421. scene.setActiveCameraByID(parsedData.activeCameraID);
  21422. }
  21423. // Browsing all the graph to connect the dots
  21424. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21425. var camera = scene.cameras[index];
  21426. if (camera._waitingParentId) {
  21427. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21428. camera._waitingParentId = undefined;
  21429. }
  21430. }
  21431. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21432. var light = scene.lights[index];
  21433. if (light._waitingParentId) {
  21434. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21435. light._waitingParentId = undefined;
  21436. }
  21437. }
  21438. // Sounds
  21439. var loadedSounds = [];
  21440. var loadedSound;
  21441. if (BABYLON.AudioEngine && parsedData.sounds) {
  21442. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21443. var parsedSound = parsedData.sounds[index];
  21444. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21445. if (!parsedSound.url)
  21446. parsedSound.url = parsedSound.name;
  21447. if (!loadedSounds[parsedSound.url]) {
  21448. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21449. loadedSounds[parsedSound.url] = loadedSound;
  21450. }
  21451. else {
  21452. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21453. }
  21454. }
  21455. else {
  21456. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21457. }
  21458. }
  21459. }
  21460. loadedSounds = [];
  21461. // Connect parents & children and parse actions
  21462. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21463. var mesh = scene.meshes[index];
  21464. if (mesh._waitingParentId) {
  21465. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21466. mesh._waitingParentId = undefined;
  21467. }
  21468. if (mesh._waitingActions) {
  21469. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21470. mesh._waitingActions = undefined;
  21471. }
  21472. }
  21473. // freeze world matrix application
  21474. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21475. var currentMesh = scene.meshes[index];
  21476. if (currentMesh._waitingFreezeWorldMatrix) {
  21477. currentMesh.freezeWorldMatrix();
  21478. currentMesh._waitingFreezeWorldMatrix = undefined;
  21479. }
  21480. else {
  21481. currentMesh.computeWorldMatrix(true);
  21482. }
  21483. }
  21484. // Particles Systems
  21485. if (parsedData.particleSystems) {
  21486. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21487. var parsedParticleSystem = parsedData.particleSystems[index];
  21488. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21489. }
  21490. }
  21491. // Lens flares
  21492. if (parsedData.lensFlareSystems) {
  21493. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21494. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21495. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21496. }
  21497. }
  21498. // Shadows
  21499. if (parsedData.shadowGenerators) {
  21500. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21501. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21502. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21503. }
  21504. }
  21505. // Actions (scene)
  21506. if (parsedData.actions) {
  21507. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21508. }
  21509. // Finish
  21510. return true;
  21511. }
  21512. });
  21513. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21514. })(BABYLON || (BABYLON = {}));
  21515. var BABYLON;
  21516. (function (BABYLON) {
  21517. var SpriteManager = (function () {
  21518. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21520. this.name = name;
  21521. this.cellSize = cellSize;
  21522. this.sprites = new Array();
  21523. this.renderingGroupId = 0;
  21524. this.layerMask = 0x0FFFFFFF;
  21525. this.fogEnabled = true;
  21526. this.isPickable = false;
  21527. this._vertexDeclaration = [4, 4, 4, 4];
  21528. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21529. this._capacity = capacity;
  21530. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21531. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21532. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21533. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21534. this._scene = scene;
  21535. this._scene.spriteManagers.push(this);
  21536. // VBO
  21537. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21538. var indices = [];
  21539. var index = 0;
  21540. for (var count = 0; count < capacity; count++) {
  21541. indices.push(index);
  21542. indices.push(index + 1);
  21543. indices.push(index + 2);
  21544. indices.push(index);
  21545. indices.push(index + 2);
  21546. indices.push(index + 3);
  21547. index += 4;
  21548. }
  21549. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21550. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21551. // Effects
  21552. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21553. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21554. }
  21555. Object.defineProperty(SpriteManager.prototype, "texture", {
  21556. get: function () {
  21557. return this._spriteTexture;
  21558. },
  21559. set: function (value) {
  21560. this._spriteTexture = value;
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21566. var arrayOffset = index * 16;
  21567. if (offsetX === 0)
  21568. offsetX = this._epsilon;
  21569. else if (offsetX === 1)
  21570. offsetX = 1 - this._epsilon;
  21571. if (offsetY === 0)
  21572. offsetY = this._epsilon;
  21573. else if (offsetY === 1)
  21574. offsetY = 1 - this._epsilon;
  21575. this._vertices[arrayOffset] = sprite.position.x;
  21576. this._vertices[arrayOffset + 1] = sprite.position.y;
  21577. this._vertices[arrayOffset + 2] = sprite.position.z;
  21578. this._vertices[arrayOffset + 3] = sprite.angle;
  21579. this._vertices[arrayOffset + 4] = sprite.width;
  21580. this._vertices[arrayOffset + 5] = sprite.height;
  21581. this._vertices[arrayOffset + 6] = offsetX;
  21582. this._vertices[arrayOffset + 7] = offsetY;
  21583. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21584. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21585. var offset = (sprite.cellIndex / rowSize) >> 0;
  21586. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21587. this._vertices[arrayOffset + 11] = offset;
  21588. // Color
  21589. this._vertices[arrayOffset + 12] = sprite.color.r;
  21590. this._vertices[arrayOffset + 13] = sprite.color.g;
  21591. this._vertices[arrayOffset + 14] = sprite.color.b;
  21592. this._vertices[arrayOffset + 15] = sprite.color.a;
  21593. };
  21594. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21595. var count = Math.min(this._capacity, this.sprites.length);
  21596. var min = BABYLON.Vector3.Zero();
  21597. var max = BABYLON.Vector3.Zero();
  21598. var distance = Number.MAX_VALUE;
  21599. var currentSprite;
  21600. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21601. var cameraView = camera.getViewMatrix();
  21602. for (var index = 0; index < count; index++) {
  21603. var sprite = this.sprites[index];
  21604. if (!sprite) {
  21605. continue;
  21606. }
  21607. if (predicate) {
  21608. if (!predicate(sprite)) {
  21609. continue;
  21610. }
  21611. }
  21612. else if (!sprite.isPickable) {
  21613. continue;
  21614. }
  21615. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21616. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21617. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21618. if (ray.intersectsBoxMinMax(min, max)) {
  21619. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21620. if (distance > currentDistance) {
  21621. distance = currentDistance;
  21622. currentSprite = sprite;
  21623. if (fastCheck) {
  21624. break;
  21625. }
  21626. }
  21627. }
  21628. }
  21629. if (currentSprite) {
  21630. var result = new BABYLON.PickingInfo();
  21631. result.hit = true;
  21632. result.pickedSprite = currentSprite;
  21633. result.distance = distance;
  21634. return result;
  21635. }
  21636. return null;
  21637. };
  21638. SpriteManager.prototype.render = function () {
  21639. // Check
  21640. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21641. return;
  21642. var engine = this._scene.getEngine();
  21643. var baseSize = this._spriteTexture.getBaseSize();
  21644. // Sprites
  21645. var deltaTime = engine.getDeltaTime();
  21646. var max = Math.min(this._capacity, this.sprites.length);
  21647. var rowSize = baseSize.width / this.cellSize;
  21648. var offset = 0;
  21649. for (var index = 0; index < max; index++) {
  21650. var sprite = this.sprites[index];
  21651. if (!sprite) {
  21652. continue;
  21653. }
  21654. sprite._animate(deltaTime);
  21655. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21656. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21657. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21658. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21659. }
  21660. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21661. // Render
  21662. var effect = this._effectBase;
  21663. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21664. effect = this._effectFog;
  21665. }
  21666. engine.enableEffect(effect);
  21667. var viewMatrix = this._scene.getViewMatrix();
  21668. effect.setTexture("diffuseSampler", this._spriteTexture);
  21669. effect.setMatrix("view", viewMatrix);
  21670. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21671. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21672. // Fog
  21673. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21674. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21675. effect.setColor3("vFogColor", this._scene.fogColor);
  21676. }
  21677. // VBOs
  21678. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21679. // Draw order
  21680. engine.setDepthFunctionToLessOrEqual();
  21681. effect.setBool("alphaTest", true);
  21682. engine.setColorWrite(false);
  21683. engine.draw(true, 0, max * 6);
  21684. engine.setColorWrite(true);
  21685. effect.setBool("alphaTest", false);
  21686. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21687. engine.draw(true, 0, max * 6);
  21688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21689. };
  21690. SpriteManager.prototype.dispose = function () {
  21691. if (this._vertexBuffer) {
  21692. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21693. this._vertexBuffer = null;
  21694. }
  21695. if (this._indexBuffer) {
  21696. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21697. this._indexBuffer = null;
  21698. }
  21699. if (this._spriteTexture) {
  21700. this._spriteTexture.dispose();
  21701. this._spriteTexture = null;
  21702. }
  21703. // Remove from scene
  21704. var index = this._scene.spriteManagers.indexOf(this);
  21705. this._scene.spriteManagers.splice(index, 1);
  21706. // Callback
  21707. if (this.onDispose) {
  21708. this.onDispose();
  21709. }
  21710. };
  21711. return SpriteManager;
  21712. })();
  21713. BABYLON.SpriteManager = SpriteManager;
  21714. })(BABYLON || (BABYLON = {}));
  21715. var BABYLON;
  21716. (function (BABYLON) {
  21717. var Sprite = (function () {
  21718. function Sprite(name, manager) {
  21719. this.name = name;
  21720. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21721. this.width = 1.0;
  21722. this.height = 1.0;
  21723. this.angle = 0;
  21724. this.cellIndex = 0;
  21725. this.invertU = 0;
  21726. this.invertV = 0;
  21727. this.animations = new Array();
  21728. this.isPickable = false;
  21729. this._animationStarted = false;
  21730. this._loopAnimation = false;
  21731. this._fromIndex = 0;
  21732. this._toIndex = 0;
  21733. this._delay = 0;
  21734. this._direction = 1;
  21735. this._frameCount = 0;
  21736. this._time = 0;
  21737. this._manager = manager;
  21738. this._manager.sprites.push(this);
  21739. this.position = BABYLON.Vector3.Zero();
  21740. }
  21741. Object.defineProperty(Sprite.prototype, "size", {
  21742. get: function () {
  21743. return this.width;
  21744. },
  21745. set: function (value) {
  21746. this.width = value;
  21747. this.height = value;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21753. this._fromIndex = from;
  21754. this._toIndex = to;
  21755. this._loopAnimation = loop;
  21756. this._delay = delay;
  21757. this._animationStarted = true;
  21758. this._direction = from < to ? 1 : -1;
  21759. this.cellIndex = from;
  21760. this._time = 0;
  21761. };
  21762. Sprite.prototype.stopAnimation = function () {
  21763. this._animationStarted = false;
  21764. };
  21765. Sprite.prototype._animate = function (deltaTime) {
  21766. if (!this._animationStarted)
  21767. return;
  21768. this._time += deltaTime;
  21769. if (this._time > this._delay) {
  21770. this._time = this._time % this._delay;
  21771. this.cellIndex += this._direction;
  21772. if (this.cellIndex == this._toIndex) {
  21773. if (this._loopAnimation) {
  21774. this.cellIndex = this._fromIndex;
  21775. }
  21776. else {
  21777. this._animationStarted = false;
  21778. if (this.disposeWhenFinishedAnimating) {
  21779. this.dispose();
  21780. }
  21781. }
  21782. }
  21783. }
  21784. };
  21785. Sprite.prototype.dispose = function () {
  21786. for (var i = 0; i < this._manager.sprites.length; i++) {
  21787. if (this._manager.sprites[i] == this) {
  21788. this._manager.sprites.splice(i, 1);
  21789. }
  21790. }
  21791. };
  21792. return Sprite;
  21793. })();
  21794. BABYLON.Sprite = Sprite;
  21795. })(BABYLON || (BABYLON = {}));
  21796. var BABYLON;
  21797. (function (BABYLON) {
  21798. var Layer = (function () {
  21799. function Layer(name, imgUrl, scene, isBackground, color) {
  21800. this.name = name;
  21801. this.scale = new BABYLON.Vector2(1, 1);
  21802. this.offset = new BABYLON.Vector2(0, 0);
  21803. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21804. this._vertexDeclaration = [2];
  21805. this._vertexStrideSize = 2 * 4;
  21806. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21807. this.isBackground = isBackground === undefined ? true : isBackground;
  21808. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21809. this._scene = scene;
  21810. this._scene.layers.push(this);
  21811. // VBO
  21812. var vertices = [];
  21813. vertices.push(1, 1);
  21814. vertices.push(-1, 1);
  21815. vertices.push(-1, -1);
  21816. vertices.push(1, -1);
  21817. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21818. // Indices
  21819. var indices = [];
  21820. indices.push(0);
  21821. indices.push(1);
  21822. indices.push(2);
  21823. indices.push(0);
  21824. indices.push(2);
  21825. indices.push(3);
  21826. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21827. // Effects
  21828. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21829. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  21830. }
  21831. Layer.prototype.render = function () {
  21832. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  21833. // Check
  21834. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  21835. return;
  21836. var engine = this._scene.getEngine();
  21837. if (this.onBeforeRender) {
  21838. this.onBeforeRender();
  21839. }
  21840. // Render
  21841. engine.enableEffect(currentEffect);
  21842. engine.setState(false);
  21843. // Texture
  21844. currentEffect.setTexture("textureSampler", this.texture);
  21845. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21846. // Color
  21847. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21848. // Scale / offset
  21849. currentEffect.setVector2("offset", this.offset);
  21850. currentEffect.setVector2("scale", this.scale);
  21851. // VBOs
  21852. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  21853. // Draw order
  21854. if (!this._alphaTestEffect) {
  21855. engine.setAlphaMode(this.alphaBlendingMode);
  21856. engine.draw(true, 0, 6);
  21857. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21858. }
  21859. else {
  21860. engine.draw(true, 0, 6);
  21861. }
  21862. if (this.onAfterRender) {
  21863. this.onAfterRender();
  21864. }
  21865. };
  21866. Layer.prototype.dispose = function () {
  21867. if (this._vertexBuffer) {
  21868. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21869. this._vertexBuffer = null;
  21870. }
  21871. if (this._indexBuffer) {
  21872. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21873. this._indexBuffer = null;
  21874. }
  21875. if (this.texture) {
  21876. this.texture.dispose();
  21877. this.texture = null;
  21878. }
  21879. // Remove from scene
  21880. var index = this._scene.layers.indexOf(this);
  21881. this._scene.layers.splice(index, 1);
  21882. // Callback
  21883. if (this.onDispose) {
  21884. this.onDispose();
  21885. }
  21886. };
  21887. return Layer;
  21888. })();
  21889. BABYLON.Layer = Layer;
  21890. })(BABYLON || (BABYLON = {}));
  21891. var BABYLON;
  21892. (function (BABYLON) {
  21893. var Particle = (function () {
  21894. function Particle() {
  21895. this.position = BABYLON.Vector3.Zero();
  21896. this.direction = BABYLON.Vector3.Zero();
  21897. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21898. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21899. this.lifeTime = 1.0;
  21900. this.age = 0;
  21901. this.size = 0;
  21902. this.angle = 0;
  21903. this.angularSpeed = 0;
  21904. }
  21905. Particle.prototype.copyTo = function (other) {
  21906. other.position.copyFrom(this.position);
  21907. other.direction.copyFrom(this.direction);
  21908. other.color.copyFrom(this.color);
  21909. other.colorStep.copyFrom(this.colorStep);
  21910. other.lifeTime = this.lifeTime;
  21911. other.age = this.age;
  21912. other.size = this.size;
  21913. other.angle = this.angle;
  21914. other.angularSpeed = this.angularSpeed;
  21915. };
  21916. return Particle;
  21917. })();
  21918. BABYLON.Particle = Particle;
  21919. })(BABYLON || (BABYLON = {}));
  21920. var BABYLON;
  21921. (function (BABYLON) {
  21922. var randomNumber = function (min, max) {
  21923. if (min === max) {
  21924. return (min);
  21925. }
  21926. var random = Math.random();
  21927. return ((random * (max - min)) + min);
  21928. };
  21929. var ParticleSystem = (function () {
  21930. function ParticleSystem(name, capacity, scene, customEffect) {
  21931. var _this = this;
  21932. this.name = name;
  21933. // Members
  21934. this.animations = [];
  21935. this.renderingGroupId = 0;
  21936. this.emitter = null;
  21937. this.emitRate = 10;
  21938. this.manualEmitCount = -1;
  21939. this.updateSpeed = 0.01;
  21940. this.targetStopDuration = 0;
  21941. this.disposeOnStop = false;
  21942. this.minEmitPower = 1;
  21943. this.maxEmitPower = 1;
  21944. this.minLifeTime = 1;
  21945. this.maxLifeTime = 1;
  21946. this.minSize = 1;
  21947. this.maxSize = 1;
  21948. this.minAngularSpeed = 0;
  21949. this.maxAngularSpeed = 0;
  21950. this.layerMask = 0x0FFFFFFF;
  21951. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21952. this.forceDepthWrite = false;
  21953. this.gravity = BABYLON.Vector3.Zero();
  21954. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21955. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21956. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21957. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21958. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21959. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21960. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21961. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21962. this.particles = new Array();
  21963. this._vertexDeclaration = [3, 4, 4];
  21964. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21965. this._stockParticles = new Array();
  21966. this._newPartsExcess = 0;
  21967. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21968. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21969. this._scaledDirection = BABYLON.Vector3.Zero();
  21970. this._scaledGravity = BABYLON.Vector3.Zero();
  21971. this._currentRenderId = -1;
  21972. this._started = false;
  21973. this._stopped = false;
  21974. this._actualFrame = 0;
  21975. this.id = name;
  21976. this._capacity = capacity;
  21977. this._scene = scene;
  21978. this._customEffect = customEffect;
  21979. scene.particleSystems.push(this);
  21980. // VBO
  21981. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21982. var indices = [];
  21983. var index = 0;
  21984. for (var count = 0; count < capacity; count++) {
  21985. indices.push(index);
  21986. indices.push(index + 1);
  21987. indices.push(index + 2);
  21988. indices.push(index);
  21989. indices.push(index + 2);
  21990. indices.push(index + 3);
  21991. index += 4;
  21992. }
  21993. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21994. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21995. // Default behaviors
  21996. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21997. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21998. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21999. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  22000. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  22001. };
  22002. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  22003. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  22004. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  22005. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  22006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  22007. };
  22008. this.updateFunction = function (particles) {
  22009. for (var index = 0; index < particles.length; index++) {
  22010. var particle = particles[index];
  22011. particle.age += _this._scaledUpdateSpeed;
  22012. if (particle.age >= particle.lifeTime) {
  22013. _this.recycleParticle(particle);
  22014. index--;
  22015. continue;
  22016. }
  22017. else {
  22018. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22019. particle.color.addInPlace(_this._scaledColorStep);
  22020. if (particle.color.a < 0)
  22021. particle.color.a = 0;
  22022. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22023. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22024. particle.position.addInPlace(_this._scaledDirection);
  22025. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22026. particle.direction.addInPlace(_this._scaledGravity);
  22027. }
  22028. }
  22029. };
  22030. }
  22031. ParticleSystem.prototype.recycleParticle = function (particle) {
  22032. var lastParticle = this.particles.pop();
  22033. if (lastParticle !== particle) {
  22034. lastParticle.copyTo(particle);
  22035. this._stockParticles.push(lastParticle);
  22036. }
  22037. };
  22038. ParticleSystem.prototype.getCapacity = function () {
  22039. return this._capacity;
  22040. };
  22041. ParticleSystem.prototype.isAlive = function () {
  22042. return this._alive;
  22043. };
  22044. ParticleSystem.prototype.isStarted = function () {
  22045. return this._started;
  22046. };
  22047. ParticleSystem.prototype.start = function () {
  22048. this._started = true;
  22049. this._stopped = false;
  22050. this._actualFrame = 0;
  22051. };
  22052. ParticleSystem.prototype.stop = function () {
  22053. this._stopped = true;
  22054. };
  22055. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22056. var offset = index * 11;
  22057. this._vertices[offset] = particle.position.x;
  22058. this._vertices[offset + 1] = particle.position.y;
  22059. this._vertices[offset + 2] = particle.position.z;
  22060. this._vertices[offset + 3] = particle.color.r;
  22061. this._vertices[offset + 4] = particle.color.g;
  22062. this._vertices[offset + 5] = particle.color.b;
  22063. this._vertices[offset + 6] = particle.color.a;
  22064. this._vertices[offset + 7] = particle.angle;
  22065. this._vertices[offset + 8] = particle.size;
  22066. this._vertices[offset + 9] = offsetX;
  22067. this._vertices[offset + 10] = offsetY;
  22068. };
  22069. ParticleSystem.prototype._update = function (newParticles) {
  22070. // Update current
  22071. this._alive = this.particles.length > 0;
  22072. this.updateFunction(this.particles);
  22073. // Add new ones
  22074. var worldMatrix;
  22075. if (this.emitter.position) {
  22076. worldMatrix = this.emitter.getWorldMatrix();
  22077. }
  22078. else {
  22079. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22080. }
  22081. var particle;
  22082. for (var index = 0; index < newParticles; index++) {
  22083. if (this.particles.length === this._capacity) {
  22084. break;
  22085. }
  22086. if (this._stockParticles.length !== 0) {
  22087. particle = this._stockParticles.pop();
  22088. particle.age = 0;
  22089. }
  22090. else {
  22091. particle = new BABYLON.Particle();
  22092. }
  22093. this.particles.push(particle);
  22094. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22095. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22096. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22097. particle.size = randomNumber(this.minSize, this.maxSize);
  22098. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22099. this.startPositionFunction(worldMatrix, particle.position, particle);
  22100. var step = randomNumber(0, 1.0);
  22101. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22102. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22103. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22104. }
  22105. };
  22106. ParticleSystem.prototype._getEffect = function () {
  22107. if (this._customEffect) {
  22108. return this._customEffect;
  22109. }
  22110. ;
  22111. var defines = [];
  22112. if (this._scene.clipPlane) {
  22113. defines.push("#define CLIPPLANE");
  22114. }
  22115. // Effect
  22116. var join = defines.join("\n");
  22117. if (this._cachedDefines !== join) {
  22118. this._cachedDefines = join;
  22119. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22120. }
  22121. return this._effect;
  22122. };
  22123. ParticleSystem.prototype.animate = function () {
  22124. if (!this._started)
  22125. return;
  22126. var effect = this._getEffect();
  22127. // Check
  22128. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22129. return;
  22130. if (this._currentRenderId === this._scene.getRenderId()) {
  22131. return;
  22132. }
  22133. this._currentRenderId = this._scene.getRenderId();
  22134. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22135. // determine the number of particles we need to create
  22136. var newParticles;
  22137. if (this.manualEmitCount > -1) {
  22138. newParticles = this.manualEmitCount;
  22139. this._newPartsExcess = 0;
  22140. this.manualEmitCount = 0;
  22141. }
  22142. else {
  22143. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22144. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22145. }
  22146. if (this._newPartsExcess > 1.0) {
  22147. newParticles += this._newPartsExcess >> 0;
  22148. this._newPartsExcess -= this._newPartsExcess >> 0;
  22149. }
  22150. this._alive = false;
  22151. if (!this._stopped) {
  22152. this._actualFrame += this._scaledUpdateSpeed;
  22153. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22154. this.stop();
  22155. }
  22156. else {
  22157. newParticles = 0;
  22158. }
  22159. this._update(newParticles);
  22160. // Stopped?
  22161. if (this._stopped) {
  22162. if (!this._alive) {
  22163. this._started = false;
  22164. if (this.disposeOnStop) {
  22165. this._scene._toBeDisposed.push(this);
  22166. }
  22167. }
  22168. }
  22169. // Update VBO
  22170. var offset = 0;
  22171. for (var index = 0; index < this.particles.length; index++) {
  22172. var particle = this.particles[index];
  22173. this._appendParticleVertex(offset++, particle, 0, 0);
  22174. this._appendParticleVertex(offset++, particle, 1, 0);
  22175. this._appendParticleVertex(offset++, particle, 1, 1);
  22176. this._appendParticleVertex(offset++, particle, 0, 1);
  22177. }
  22178. var engine = this._scene.getEngine();
  22179. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22180. };
  22181. ParticleSystem.prototype.render = function () {
  22182. var effect = this._getEffect();
  22183. // Check
  22184. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22185. return 0;
  22186. var engine = this._scene.getEngine();
  22187. // Render
  22188. engine.enableEffect(effect);
  22189. engine.setState(false);
  22190. var viewMatrix = this._scene.getViewMatrix();
  22191. effect.setTexture("diffuseSampler", this.particleTexture);
  22192. effect.setMatrix("view", viewMatrix);
  22193. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22194. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22195. if (this._scene.clipPlane) {
  22196. var clipPlane = this._scene.clipPlane;
  22197. var invView = viewMatrix.clone();
  22198. invView.invert();
  22199. effect.setMatrix("invView", invView);
  22200. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22201. }
  22202. // VBOs
  22203. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22204. // Draw order
  22205. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22206. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22207. }
  22208. else {
  22209. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22210. }
  22211. if (this.forceDepthWrite) {
  22212. engine.setDepthWrite(true);
  22213. }
  22214. engine.draw(true, 0, this.particles.length * 6);
  22215. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22216. return this.particles.length;
  22217. };
  22218. ParticleSystem.prototype.dispose = function () {
  22219. if (this._vertexBuffer) {
  22220. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22221. this._vertexBuffer = null;
  22222. }
  22223. if (this._indexBuffer) {
  22224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22225. this._indexBuffer = null;
  22226. }
  22227. if (this.particleTexture) {
  22228. this.particleTexture.dispose();
  22229. this.particleTexture = null;
  22230. }
  22231. // Remove from scene
  22232. var index = this._scene.particleSystems.indexOf(this);
  22233. this._scene.particleSystems.splice(index, 1);
  22234. // Callback
  22235. if (this.onDispose) {
  22236. this.onDispose();
  22237. }
  22238. };
  22239. // Clone
  22240. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22241. var result = new ParticleSystem(name, this._capacity, this._scene);
  22242. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22243. if (newEmitter === undefined) {
  22244. newEmitter = this.emitter;
  22245. }
  22246. result.emitter = newEmitter;
  22247. if (this.particleTexture) {
  22248. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22249. }
  22250. result.start();
  22251. return result;
  22252. };
  22253. ParticleSystem.prototype.serialize = function () {
  22254. var serializationObject = {};
  22255. serializationObject.name = this.name;
  22256. serializationObject.id = this.id;
  22257. // Emitter
  22258. if (this.emitter.position) {
  22259. serializationObject.emitterId = this.emitter.id;
  22260. }
  22261. else {
  22262. serializationObject.emitter = this.emitter.asArray();
  22263. }
  22264. serializationObject.capacity = this.getCapacity();
  22265. if (this.particleTexture) {
  22266. serializationObject.textureName = this.particleTexture.name;
  22267. }
  22268. // Animations
  22269. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22270. // Particle system
  22271. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22272. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22273. serializationObject.minSize = this.minSize;
  22274. serializationObject.maxSize = this.maxSize;
  22275. serializationObject.minEmitPower = this.minEmitPower;
  22276. serializationObject.maxEmitPower = this.maxEmitPower;
  22277. serializationObject.minLifeTime = this.minLifeTime;
  22278. serializationObject.maxLifeTime = this.maxLifeTime;
  22279. serializationObject.emitRate = this.emitRate;
  22280. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22281. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22282. serializationObject.gravity = this.gravity.asArray();
  22283. serializationObject.direction1 = this.direction1.asArray();
  22284. serializationObject.direction2 = this.direction2.asArray();
  22285. serializationObject.color1 = this.color1.asArray();
  22286. serializationObject.color2 = this.color2.asArray();
  22287. serializationObject.colorDead = this.colorDead.asArray();
  22288. serializationObject.updateSpeed = this.updateSpeed;
  22289. serializationObject.targetStopDuration = this.targetStopDuration;
  22290. serializationObject.textureMask = this.textureMask.asArray();
  22291. serializationObject.blendMode = this.blendMode;
  22292. return serializationObject;
  22293. };
  22294. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22295. var name = parsedParticleSystem.name;
  22296. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22297. if (parsedParticleSystem.id) {
  22298. particleSystem.id = parsedParticleSystem.id;
  22299. }
  22300. // Texture
  22301. if (parsedParticleSystem.textureName) {
  22302. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22303. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22304. }
  22305. // Emitter
  22306. if (parsedParticleSystem.emitterId) {
  22307. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22308. }
  22309. else {
  22310. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22311. }
  22312. // Animations
  22313. if (parsedParticleSystem.animations) {
  22314. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22315. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22316. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22317. }
  22318. }
  22319. if (parsedParticleSystem.autoAnimate) {
  22320. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  22321. }
  22322. // Particle system
  22323. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22324. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22325. particleSystem.minSize = parsedParticleSystem.minSize;
  22326. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22327. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22328. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22329. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22330. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22331. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22332. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22333. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22334. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22335. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22336. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22337. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22338. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22339. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22340. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22341. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22342. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22343. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22344. particleSystem.start();
  22345. return particleSystem;
  22346. };
  22347. // Statics
  22348. ParticleSystem.BLENDMODE_ONEONE = 0;
  22349. ParticleSystem.BLENDMODE_STANDARD = 1;
  22350. return ParticleSystem;
  22351. })();
  22352. BABYLON.ParticleSystem = ParticleSystem;
  22353. })(BABYLON || (BABYLON = {}));
  22354. var BABYLON;
  22355. (function (BABYLON) {
  22356. var AnimationRange = (function () {
  22357. function AnimationRange(name, from, to) {
  22358. this.name = name;
  22359. this.from = from;
  22360. this.to = to;
  22361. }
  22362. AnimationRange.prototype.clone = function () {
  22363. return new AnimationRange(this.name, this.from, this.to);
  22364. };
  22365. return AnimationRange;
  22366. })();
  22367. BABYLON.AnimationRange = AnimationRange;
  22368. /**
  22369. * Composed of a frame, and an action function
  22370. */
  22371. var AnimationEvent = (function () {
  22372. function AnimationEvent(frame, action, onlyOnce) {
  22373. this.frame = frame;
  22374. this.action = action;
  22375. this.onlyOnce = onlyOnce;
  22376. this.isDone = false;
  22377. }
  22378. return AnimationEvent;
  22379. })();
  22380. BABYLON.AnimationEvent = AnimationEvent;
  22381. var PathCursor = (function () {
  22382. function PathCursor(path) {
  22383. this.path = path;
  22384. this._onchange = new Array();
  22385. this.value = 0;
  22386. this.animations = new Array();
  22387. }
  22388. PathCursor.prototype.getPoint = function () {
  22389. var point = this.path.getPointAtLengthPosition(this.value);
  22390. return new BABYLON.Vector3(point.x, 0, point.y);
  22391. };
  22392. PathCursor.prototype.moveAhead = function (step) {
  22393. if (step === void 0) { step = 0.002; }
  22394. this.move(step);
  22395. return this;
  22396. };
  22397. PathCursor.prototype.moveBack = function (step) {
  22398. if (step === void 0) { step = 0.002; }
  22399. this.move(-step);
  22400. return this;
  22401. };
  22402. PathCursor.prototype.move = function (step) {
  22403. if (Math.abs(step) > 1) {
  22404. throw "step size should be less than 1.";
  22405. }
  22406. this.value += step;
  22407. this.ensureLimits();
  22408. this.raiseOnChange();
  22409. return this;
  22410. };
  22411. PathCursor.prototype.ensureLimits = function () {
  22412. while (this.value > 1) {
  22413. this.value -= 1;
  22414. }
  22415. while (this.value < 0) {
  22416. this.value += 1;
  22417. }
  22418. return this;
  22419. };
  22420. // used by animation engine
  22421. PathCursor.prototype.markAsDirty = function (propertyName) {
  22422. this.ensureLimits();
  22423. this.raiseOnChange();
  22424. return this;
  22425. };
  22426. PathCursor.prototype.raiseOnChange = function () {
  22427. var _this = this;
  22428. this._onchange.forEach(function (f) { return f(_this); });
  22429. return this;
  22430. };
  22431. PathCursor.prototype.onchange = function (f) {
  22432. this._onchange.push(f);
  22433. return this;
  22434. };
  22435. return PathCursor;
  22436. })();
  22437. BABYLON.PathCursor = PathCursor;
  22438. var Animation = (function () {
  22439. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  22440. this.name = name;
  22441. this.targetProperty = targetProperty;
  22442. this.framePerSecond = framePerSecond;
  22443. this.dataType = dataType;
  22444. this.loopMode = loopMode;
  22445. this.enableBlending = enableBlending;
  22446. this._offsetsCache = {};
  22447. this._highLimitsCache = {};
  22448. this._stopped = false;
  22449. this._blendingFactor = 0;
  22450. // The set of event that will be linked to this animation
  22451. this._events = new Array();
  22452. this.allowMatricesInterpolation = false;
  22453. this.blendingSpeed = 0.01;
  22454. this._ranges = {};
  22455. this.targetPropertyPath = targetProperty.split(".");
  22456. this.dataType = dataType;
  22457. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22458. }
  22459. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22460. var dataType = undefined;
  22461. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22462. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22463. }
  22464. else if (from instanceof BABYLON.Quaternion) {
  22465. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22466. }
  22467. else if (from instanceof BABYLON.Vector3) {
  22468. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22469. }
  22470. else if (from instanceof BABYLON.Vector2) {
  22471. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22472. }
  22473. else if (from instanceof BABYLON.Color3) {
  22474. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22475. }
  22476. if (dataType == undefined) {
  22477. return null;
  22478. }
  22479. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22480. var keys = [];
  22481. keys.push({ frame: 0, value: from });
  22482. keys.push({ frame: totalFrame, value: to });
  22483. animation.setKeys(keys);
  22484. if (easingFunction !== undefined) {
  22485. animation.setEasingFunction(easingFunction);
  22486. }
  22487. return animation;
  22488. };
  22489. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22490. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22491. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22492. };
  22493. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22494. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22495. node.animations.push(animation);
  22496. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22497. };
  22498. // Methods
  22499. /**
  22500. * Add an event to this animation.
  22501. */
  22502. Animation.prototype.addEvent = function (event) {
  22503. this._events.push(event);
  22504. };
  22505. /**
  22506. * Remove all events found at the given frame
  22507. * @param frame
  22508. */
  22509. Animation.prototype.removeEvents = function (frame) {
  22510. for (var index = 0; index < this._events.length; index++) {
  22511. if (this._events[index].frame === frame) {
  22512. this._events.splice(index, 1);
  22513. index--;
  22514. }
  22515. }
  22516. };
  22517. Animation.prototype.createRange = function (name, from, to) {
  22518. // check name not already in use; could happen for bones after serialized
  22519. if (!this._ranges[name]) {
  22520. this._ranges[name] = new AnimationRange(name, from, to);
  22521. }
  22522. };
  22523. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22524. if (deleteFrames === void 0) { deleteFrames = true; }
  22525. if (this._ranges[name]) {
  22526. if (deleteFrames) {
  22527. var from = this._ranges[name].from;
  22528. var to = this._ranges[name].to;
  22529. // this loop MUST go high to low for multiple splices to work
  22530. for (var key = this._keys.length - 1; key >= 0; key--) {
  22531. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22532. this._keys.splice(key, 1);
  22533. }
  22534. }
  22535. }
  22536. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22537. }
  22538. };
  22539. Animation.prototype.getRange = function (name) {
  22540. return this._ranges[name];
  22541. };
  22542. Animation.prototype.reset = function () {
  22543. this._offsetsCache = {};
  22544. this._highLimitsCache = {};
  22545. this.currentFrame = 0;
  22546. this._blendingFactor = 0;
  22547. this._originalBlendValue = null;
  22548. };
  22549. Animation.prototype.isStopped = function () {
  22550. return this._stopped;
  22551. };
  22552. Animation.prototype.getKeys = function () {
  22553. return this._keys;
  22554. };
  22555. Animation.prototype.getHighestFrame = function () {
  22556. var ret = 0;
  22557. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22558. if (ret < this._keys[key].frame) {
  22559. ret = this._keys[key].frame;
  22560. }
  22561. }
  22562. return ret;
  22563. };
  22564. Animation.prototype.getEasingFunction = function () {
  22565. return this._easingFunction;
  22566. };
  22567. Animation.prototype.setEasingFunction = function (easingFunction) {
  22568. this._easingFunction = easingFunction;
  22569. };
  22570. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22571. return startValue + (endValue - startValue) * gradient;
  22572. };
  22573. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22574. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22575. };
  22576. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22577. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22578. };
  22579. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22580. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22581. };
  22582. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22583. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22584. };
  22585. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22586. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22587. };
  22588. Animation.prototype.clone = function () {
  22589. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22590. if (this._keys) {
  22591. clone.setKeys(this._keys);
  22592. }
  22593. if (this._ranges) {
  22594. clone._ranges = {};
  22595. for (var name in this._ranges) {
  22596. clone._ranges[name] = this._ranges[name].clone();
  22597. }
  22598. }
  22599. return clone;
  22600. };
  22601. Animation.prototype.setKeys = function (values) {
  22602. this._keys = values.slice(0);
  22603. this._offsetsCache = {};
  22604. this._highLimitsCache = {};
  22605. };
  22606. Animation.prototype._getKeyValue = function (value) {
  22607. if (typeof value === "function") {
  22608. return value();
  22609. }
  22610. return value;
  22611. };
  22612. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22613. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22614. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22615. }
  22616. this.currentFrame = currentFrame;
  22617. // Try to get a hash to find the right key
  22618. 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));
  22619. if (this._keys[startKey].frame >= currentFrame) {
  22620. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22621. startKey--;
  22622. }
  22623. }
  22624. for (var key = startKey; key < this._keys.length; key++) {
  22625. if (this._keys[key + 1].frame >= currentFrame) {
  22626. var startValue = this._getKeyValue(this._keys[key].value);
  22627. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22628. // gradient : percent of currentFrame between the frame inf and the frame sup
  22629. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22630. // check for easingFunction and correction of gradient
  22631. if (this._easingFunction != null) {
  22632. gradient = this._easingFunction.ease(gradient);
  22633. }
  22634. switch (this.dataType) {
  22635. // Float
  22636. case Animation.ANIMATIONTYPE_FLOAT:
  22637. switch (loopMode) {
  22638. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22639. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22640. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22641. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22642. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22643. }
  22644. break;
  22645. // Quaternion
  22646. case Animation.ANIMATIONTYPE_QUATERNION:
  22647. var quaternion = null;
  22648. switch (loopMode) {
  22649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22651. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22652. break;
  22653. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22654. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22655. break;
  22656. }
  22657. return quaternion;
  22658. // Vector3
  22659. case Animation.ANIMATIONTYPE_VECTOR3:
  22660. switch (loopMode) {
  22661. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22662. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22663. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22664. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22665. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22666. }
  22667. // Vector2
  22668. case Animation.ANIMATIONTYPE_VECTOR2:
  22669. switch (loopMode) {
  22670. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22671. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22672. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22673. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22674. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22675. }
  22676. // Color3
  22677. case Animation.ANIMATIONTYPE_COLOR3:
  22678. switch (loopMode) {
  22679. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22680. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22681. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22682. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22683. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22684. }
  22685. // Matrix
  22686. case Animation.ANIMATIONTYPE_MATRIX:
  22687. switch (loopMode) {
  22688. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22689. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22690. if (this.allowMatricesInterpolation) {
  22691. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22692. }
  22693. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22694. return startValue;
  22695. }
  22696. default:
  22697. break;
  22698. }
  22699. break;
  22700. }
  22701. }
  22702. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22703. };
  22704. Animation.prototype.setValue = function (currentValue, blend) {
  22705. if (blend === void 0) { blend = false; }
  22706. // Set value
  22707. var path;
  22708. var destination;
  22709. if (this.targetPropertyPath.length > 1) {
  22710. var property = this._target[this.targetPropertyPath[0]];
  22711. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22712. property = property[this.targetPropertyPath[index]];
  22713. }
  22714. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  22715. destination = property;
  22716. }
  22717. else {
  22718. path = this.targetPropertyPath[0];
  22719. destination = this._target;
  22720. }
  22721. // Blending
  22722. if (this.enableBlending && this._blendingFactor <= 1.0) {
  22723. if (!this._originalBlendValue) {
  22724. this._originalBlendValue = destination[path];
  22725. }
  22726. if (this._originalBlendValue.prototype) {
  22727. if (this._originalBlendValue.prototype.Lerp) {
  22728. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  22729. }
  22730. else {
  22731. destination[path] = currentValue;
  22732. }
  22733. }
  22734. else {
  22735. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  22736. }
  22737. this._blendingFactor += this.blendingSpeed;
  22738. }
  22739. else {
  22740. destination[path] = currentValue;
  22741. }
  22742. if (this._target.markAsDirty) {
  22743. this._target.markAsDirty(this.targetProperty);
  22744. }
  22745. };
  22746. Animation.prototype.goToFrame = function (frame) {
  22747. if (frame < this._keys[0].frame) {
  22748. frame = this._keys[0].frame;
  22749. }
  22750. else if (frame > this._keys[this._keys.length - 1].frame) {
  22751. frame = this._keys[this._keys.length - 1].frame;
  22752. }
  22753. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22754. this.setValue(currentValue);
  22755. };
  22756. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  22757. if (blend === void 0) { blend = false; }
  22758. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22759. this._stopped = true;
  22760. return false;
  22761. }
  22762. var returnValue = true;
  22763. // Adding a start key at frame 0 if missing
  22764. if (this._keys[0].frame !== 0) {
  22765. var newKey = { frame: 0, value: this._keys[0].value };
  22766. this._keys.splice(0, 0, newKey);
  22767. }
  22768. // Check limits
  22769. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22770. from = this._keys[0].frame;
  22771. }
  22772. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22773. to = this._keys[this._keys.length - 1].frame;
  22774. }
  22775. // Compute ratio
  22776. var range = to - from;
  22777. var offsetValue;
  22778. // ratio represents the frame delta between from and to
  22779. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22780. var highLimitValue = 0;
  22781. if (ratio > range && !loop) {
  22782. returnValue = false;
  22783. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22784. }
  22785. else {
  22786. // Get max value if required
  22787. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22788. var keyOffset = to.toString() + from.toString();
  22789. if (!this._offsetsCache[keyOffset]) {
  22790. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22791. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22792. switch (this.dataType) {
  22793. // Float
  22794. case Animation.ANIMATIONTYPE_FLOAT:
  22795. this._offsetsCache[keyOffset] = toValue - fromValue;
  22796. break;
  22797. // Quaternion
  22798. case Animation.ANIMATIONTYPE_QUATERNION:
  22799. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22800. break;
  22801. // Vector3
  22802. case Animation.ANIMATIONTYPE_VECTOR3:
  22803. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22804. // Vector2
  22805. case Animation.ANIMATIONTYPE_VECTOR2:
  22806. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22807. // Color3
  22808. case Animation.ANIMATIONTYPE_COLOR3:
  22809. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22810. default:
  22811. break;
  22812. }
  22813. this._highLimitsCache[keyOffset] = toValue;
  22814. }
  22815. highLimitValue = this._highLimitsCache[keyOffset];
  22816. offsetValue = this._offsetsCache[keyOffset];
  22817. }
  22818. }
  22819. if (offsetValue === undefined) {
  22820. switch (this.dataType) {
  22821. // Float
  22822. case Animation.ANIMATIONTYPE_FLOAT:
  22823. offsetValue = 0;
  22824. break;
  22825. // Quaternion
  22826. case Animation.ANIMATIONTYPE_QUATERNION:
  22827. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22828. break;
  22829. // Vector3
  22830. case Animation.ANIMATIONTYPE_VECTOR3:
  22831. offsetValue = BABYLON.Vector3.Zero();
  22832. break;
  22833. // Vector2
  22834. case Animation.ANIMATIONTYPE_VECTOR2:
  22835. offsetValue = BABYLON.Vector2.Zero();
  22836. break;
  22837. // Color3
  22838. case Animation.ANIMATIONTYPE_COLOR3:
  22839. offsetValue = BABYLON.Color3.Black();
  22840. }
  22841. }
  22842. // Compute value
  22843. var repeatCount = (ratio / range) >> 0;
  22844. var currentFrame = returnValue ? from + ratio % range : to;
  22845. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22846. // Set value
  22847. this.setValue(currentValue);
  22848. // Check events
  22849. for (var index = 0; index < this._events.length; index++) {
  22850. if (currentFrame >= this._events[index].frame) {
  22851. var event = this._events[index];
  22852. if (!event.isDone) {
  22853. // If event should be done only once, remove it.
  22854. if (event.onlyOnce) {
  22855. this._events.splice(index, 1);
  22856. index--;
  22857. }
  22858. event.isDone = true;
  22859. event.action();
  22860. } // Don't do anything if the event has already be done.
  22861. }
  22862. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22863. // reset event, the animation is looping
  22864. this._events[index].isDone = false;
  22865. }
  22866. }
  22867. if (!returnValue) {
  22868. this._stopped = true;
  22869. }
  22870. return returnValue;
  22871. };
  22872. Animation.prototype.serialize = function () {
  22873. var serializationObject = {};
  22874. serializationObject.name = this.name;
  22875. serializationObject.property = this.targetProperty;
  22876. serializationObject.framePerSecond = this.framePerSecond;
  22877. serializationObject.dataType = this.dataType;
  22878. serializationObject.loopBehavior = this.loopMode;
  22879. var dataType = this.dataType;
  22880. serializationObject.keys = [];
  22881. var keys = this.getKeys();
  22882. for (var index = 0; index < keys.length; index++) {
  22883. var animationKey = keys[index];
  22884. var key = {};
  22885. key.frame = animationKey.frame;
  22886. switch (dataType) {
  22887. case Animation.ANIMATIONTYPE_FLOAT:
  22888. key.values = [animationKey.value];
  22889. break;
  22890. case Animation.ANIMATIONTYPE_QUATERNION:
  22891. case Animation.ANIMATIONTYPE_MATRIX:
  22892. case Animation.ANIMATIONTYPE_VECTOR3:
  22893. case Animation.ANIMATIONTYPE_COLOR3:
  22894. key.values = animationKey.value.asArray();
  22895. break;
  22896. }
  22897. serializationObject.keys.push(key);
  22898. }
  22899. serializationObject.ranges = [];
  22900. for (var name in this._ranges) {
  22901. var range = {};
  22902. range.name = name;
  22903. range.from = this._ranges[name].from;
  22904. range.to = this._ranges[name].to;
  22905. serializationObject.ranges.push(range);
  22906. }
  22907. return serializationObject;
  22908. };
  22909. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22910. get: function () {
  22911. return Animation._ANIMATIONTYPE_FLOAT;
  22912. },
  22913. enumerable: true,
  22914. configurable: true
  22915. });
  22916. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22917. get: function () {
  22918. return Animation._ANIMATIONTYPE_VECTOR3;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22924. get: function () {
  22925. return Animation._ANIMATIONTYPE_VECTOR2;
  22926. },
  22927. enumerable: true,
  22928. configurable: true
  22929. });
  22930. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22931. get: function () {
  22932. return Animation._ANIMATIONTYPE_QUATERNION;
  22933. },
  22934. enumerable: true,
  22935. configurable: true
  22936. });
  22937. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22938. get: function () {
  22939. return Animation._ANIMATIONTYPE_MATRIX;
  22940. },
  22941. enumerable: true,
  22942. configurable: true
  22943. });
  22944. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22945. get: function () {
  22946. return Animation._ANIMATIONTYPE_COLOR3;
  22947. },
  22948. enumerable: true,
  22949. configurable: true
  22950. });
  22951. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22952. get: function () {
  22953. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22954. },
  22955. enumerable: true,
  22956. configurable: true
  22957. });
  22958. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22959. get: function () {
  22960. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22961. },
  22962. enumerable: true,
  22963. configurable: true
  22964. });
  22965. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22966. get: function () {
  22967. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22968. },
  22969. enumerable: true,
  22970. configurable: true
  22971. });
  22972. Animation.Parse = function (parsedAnimation) {
  22973. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22974. var dataType = parsedAnimation.dataType;
  22975. var keys = [];
  22976. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22977. var key = parsedAnimation.keys[index];
  22978. var data;
  22979. switch (dataType) {
  22980. case Animation.ANIMATIONTYPE_FLOAT:
  22981. data = key.values[0];
  22982. break;
  22983. case Animation.ANIMATIONTYPE_QUATERNION:
  22984. data = BABYLON.Quaternion.FromArray(key.values);
  22985. break;
  22986. case Animation.ANIMATIONTYPE_MATRIX:
  22987. data = BABYLON.Matrix.FromArray(key.values);
  22988. break;
  22989. case Animation.ANIMATIONTYPE_COLOR3:
  22990. data = BABYLON.Color3.FromArray(key.values);
  22991. break;
  22992. case Animation.ANIMATIONTYPE_VECTOR3:
  22993. default:
  22994. data = BABYLON.Vector3.FromArray(key.values);
  22995. break;
  22996. }
  22997. keys.push({
  22998. frame: key.frame,
  22999. value: data
  23000. });
  23001. }
  23002. animation.setKeys(keys);
  23003. if (parsedAnimation.ranges) {
  23004. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  23005. data = parsedAnimation.ranges[index];
  23006. animation.createRange(data.name, data.from, data.to);
  23007. }
  23008. }
  23009. return animation;
  23010. };
  23011. Animation.AppendSerializedAnimations = function (source, destination) {
  23012. if (source.animations) {
  23013. destination.animations = [];
  23014. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23015. var animation = source.animations[animationIndex];
  23016. destination.animations.push(animation.serialize());
  23017. }
  23018. }
  23019. };
  23020. // Statics
  23021. Animation._ANIMATIONTYPE_FLOAT = 0;
  23022. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  23023. Animation._ANIMATIONTYPE_QUATERNION = 2;
  23024. Animation._ANIMATIONTYPE_MATRIX = 3;
  23025. Animation._ANIMATIONTYPE_COLOR3 = 4;
  23026. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  23027. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  23028. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  23029. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  23030. return Animation;
  23031. })();
  23032. BABYLON.Animation = Animation;
  23033. })(BABYLON || (BABYLON = {}));
  23034. var BABYLON;
  23035. (function (BABYLON) {
  23036. var Animatable = (function () {
  23037. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  23038. if (fromFrame === void 0) { fromFrame = 0; }
  23039. if (toFrame === void 0) { toFrame = 100; }
  23040. if (loopAnimation === void 0) { loopAnimation = false; }
  23041. if (speedRatio === void 0) { speedRatio = 1.0; }
  23042. this.target = target;
  23043. this.fromFrame = fromFrame;
  23044. this.toFrame = toFrame;
  23045. this.loopAnimation = loopAnimation;
  23046. this.speedRatio = speedRatio;
  23047. this.onAnimationEnd = onAnimationEnd;
  23048. this._animations = new Array();
  23049. this._paused = false;
  23050. this.animationStarted = false;
  23051. if (animations) {
  23052. this.appendAnimations(target, animations);
  23053. }
  23054. this._scene = scene;
  23055. scene._activeAnimatables.push(this);
  23056. }
  23057. // Methods
  23058. Animatable.prototype.getAnimations = function () {
  23059. return this._animations;
  23060. };
  23061. Animatable.prototype.appendAnimations = function (target, animations) {
  23062. for (var index = 0; index < animations.length; index++) {
  23063. var animation = animations[index];
  23064. animation._target = target;
  23065. this._animations.push(animation);
  23066. }
  23067. };
  23068. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  23069. var animations = this._animations;
  23070. for (var index = 0; index < animations.length; index++) {
  23071. if (animations[index].targetProperty === property) {
  23072. return animations[index];
  23073. }
  23074. }
  23075. return null;
  23076. };
  23077. Animatable.prototype.reset = function () {
  23078. var animations = this._animations;
  23079. for (var index = 0; index < animations.length; index++) {
  23080. animations[index].reset();
  23081. }
  23082. this._localDelayOffset = null;
  23083. this._pausedDelay = null;
  23084. };
  23085. Animatable.prototype.enableBlending = function (blendingSpeed) {
  23086. var animations = this._animations;
  23087. for (var index = 0; index < animations.length; index++) {
  23088. animations[index].enableBlending = true;
  23089. animations[index].blendingSpeed = blendingSpeed;
  23090. }
  23091. };
  23092. Animatable.prototype.disableBlending = function () {
  23093. var animations = this._animations;
  23094. for (var index = 0; index < animations.length; index++) {
  23095. animations[index].enableBlending = false;
  23096. }
  23097. };
  23098. Animatable.prototype.goToFrame = function (frame) {
  23099. var animations = this._animations;
  23100. for (var index = 0; index < animations.length; index++) {
  23101. animations[index].goToFrame(frame);
  23102. }
  23103. };
  23104. Animatable.prototype.pause = function () {
  23105. if (this._paused) {
  23106. return;
  23107. }
  23108. this._paused = true;
  23109. };
  23110. Animatable.prototype.restart = function () {
  23111. this._paused = false;
  23112. };
  23113. Animatable.prototype.stop = function () {
  23114. var index = this._scene._activeAnimatables.indexOf(this);
  23115. if (index > -1) {
  23116. this._scene._activeAnimatables.splice(index, 1);
  23117. var animations = this._animations;
  23118. for (var index = 0; index < animations.length; index++) {
  23119. animations[index].reset();
  23120. }
  23121. if (this.onAnimationEnd) {
  23122. this.onAnimationEnd();
  23123. }
  23124. }
  23125. };
  23126. Animatable.prototype._animate = function (delay) {
  23127. if (this._paused) {
  23128. this.animationStarted = false;
  23129. if (!this._pausedDelay) {
  23130. this._pausedDelay = delay;
  23131. }
  23132. return true;
  23133. }
  23134. if (!this._localDelayOffset) {
  23135. this._localDelayOffset = delay;
  23136. }
  23137. else if (this._pausedDelay) {
  23138. this._localDelayOffset += delay - this._pausedDelay;
  23139. this._pausedDelay = null;
  23140. }
  23141. // Animating
  23142. var running = false;
  23143. var animations = this._animations;
  23144. var index;
  23145. for (index = 0; index < animations.length; index++) {
  23146. var animation = animations[index];
  23147. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  23148. running = running || isRunning;
  23149. }
  23150. this.animationStarted = running;
  23151. if (!running) {
  23152. // Remove from active animatables
  23153. index = this._scene._activeAnimatables.indexOf(this);
  23154. this._scene._activeAnimatables.splice(index, 1);
  23155. }
  23156. if (!running && this.onAnimationEnd) {
  23157. this.onAnimationEnd();
  23158. this.onAnimationEnd = null;
  23159. }
  23160. return running;
  23161. };
  23162. return Animatable;
  23163. })();
  23164. BABYLON.Animatable = Animatable;
  23165. })(BABYLON || (BABYLON = {}));
  23166. var BABYLON;
  23167. (function (BABYLON) {
  23168. var EasingFunction = (function () {
  23169. function EasingFunction() {
  23170. // Properties
  23171. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23172. }
  23173. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23174. get: function () {
  23175. return EasingFunction._EASINGMODE_EASEIN;
  23176. },
  23177. enumerable: true,
  23178. configurable: true
  23179. });
  23180. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23181. get: function () {
  23182. return EasingFunction._EASINGMODE_EASEOUT;
  23183. },
  23184. enumerable: true,
  23185. configurable: true
  23186. });
  23187. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23188. get: function () {
  23189. return EasingFunction._EASINGMODE_EASEINOUT;
  23190. },
  23191. enumerable: true,
  23192. configurable: true
  23193. });
  23194. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23195. var n = Math.min(Math.max(easingMode, 0), 2);
  23196. this._easingMode = n;
  23197. };
  23198. EasingFunction.prototype.getEasingMode = function () {
  23199. return this._easingMode;
  23200. };
  23201. EasingFunction.prototype.easeInCore = function (gradient) {
  23202. throw new Error('You must implement this method');
  23203. };
  23204. EasingFunction.prototype.ease = function (gradient) {
  23205. switch (this._easingMode) {
  23206. case EasingFunction.EASINGMODE_EASEIN:
  23207. return this.easeInCore(gradient);
  23208. case EasingFunction.EASINGMODE_EASEOUT:
  23209. return (1 - this.easeInCore(1 - gradient));
  23210. }
  23211. if (gradient >= 0.5) {
  23212. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23213. }
  23214. return (this.easeInCore(gradient * 2) * 0.5);
  23215. };
  23216. //Statics
  23217. EasingFunction._EASINGMODE_EASEIN = 0;
  23218. EasingFunction._EASINGMODE_EASEOUT = 1;
  23219. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23220. return EasingFunction;
  23221. })();
  23222. BABYLON.EasingFunction = EasingFunction;
  23223. var CircleEase = (function (_super) {
  23224. __extends(CircleEase, _super);
  23225. function CircleEase() {
  23226. _super.apply(this, arguments);
  23227. }
  23228. CircleEase.prototype.easeInCore = function (gradient) {
  23229. gradient = Math.max(0, Math.min(1, gradient));
  23230. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23231. };
  23232. return CircleEase;
  23233. })(EasingFunction);
  23234. BABYLON.CircleEase = CircleEase;
  23235. var BackEase = (function (_super) {
  23236. __extends(BackEase, _super);
  23237. function BackEase(amplitude) {
  23238. if (amplitude === void 0) { amplitude = 1; }
  23239. _super.call(this);
  23240. this.amplitude = amplitude;
  23241. }
  23242. BackEase.prototype.easeInCore = function (gradient) {
  23243. var num = Math.max(0, this.amplitude);
  23244. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23245. };
  23246. return BackEase;
  23247. })(EasingFunction);
  23248. BABYLON.BackEase = BackEase;
  23249. var BounceEase = (function (_super) {
  23250. __extends(BounceEase, _super);
  23251. function BounceEase(bounces, bounciness) {
  23252. if (bounces === void 0) { bounces = 3; }
  23253. if (bounciness === void 0) { bounciness = 2; }
  23254. _super.call(this);
  23255. this.bounces = bounces;
  23256. this.bounciness = bounciness;
  23257. }
  23258. BounceEase.prototype.easeInCore = function (gradient) {
  23259. var y = Math.max(0.0, this.bounces);
  23260. var bounciness = this.bounciness;
  23261. if (bounciness <= 1.0) {
  23262. bounciness = 1.001;
  23263. }
  23264. var num9 = Math.pow(bounciness, y);
  23265. var num5 = 1.0 - bounciness;
  23266. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23267. var num15 = gradient * num4;
  23268. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23269. var num3 = Math.floor(num65);
  23270. var num13 = num3 + 1.0;
  23271. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23272. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23273. var num7 = (num8 + num12) * 0.5;
  23274. var num6 = gradient - num7;
  23275. var num2 = num7 - num8;
  23276. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23277. };
  23278. return BounceEase;
  23279. })(EasingFunction);
  23280. BABYLON.BounceEase = BounceEase;
  23281. var CubicEase = (function (_super) {
  23282. __extends(CubicEase, _super);
  23283. function CubicEase() {
  23284. _super.apply(this, arguments);
  23285. }
  23286. CubicEase.prototype.easeInCore = function (gradient) {
  23287. return (gradient * gradient * gradient);
  23288. };
  23289. return CubicEase;
  23290. })(EasingFunction);
  23291. BABYLON.CubicEase = CubicEase;
  23292. var ElasticEase = (function (_super) {
  23293. __extends(ElasticEase, _super);
  23294. function ElasticEase(oscillations, springiness) {
  23295. if (oscillations === void 0) { oscillations = 3; }
  23296. if (springiness === void 0) { springiness = 3; }
  23297. _super.call(this);
  23298. this.oscillations = oscillations;
  23299. this.springiness = springiness;
  23300. }
  23301. ElasticEase.prototype.easeInCore = function (gradient) {
  23302. var num2;
  23303. var num3 = Math.max(0.0, this.oscillations);
  23304. var num = Math.max(0.0, this.springiness);
  23305. if (num == 0) {
  23306. num2 = gradient;
  23307. }
  23308. else {
  23309. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23310. }
  23311. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23312. };
  23313. return ElasticEase;
  23314. })(EasingFunction);
  23315. BABYLON.ElasticEase = ElasticEase;
  23316. var ExponentialEase = (function (_super) {
  23317. __extends(ExponentialEase, _super);
  23318. function ExponentialEase(exponent) {
  23319. if (exponent === void 0) { exponent = 2; }
  23320. _super.call(this);
  23321. this.exponent = exponent;
  23322. }
  23323. ExponentialEase.prototype.easeInCore = function (gradient) {
  23324. if (this.exponent <= 0) {
  23325. return gradient;
  23326. }
  23327. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23328. };
  23329. return ExponentialEase;
  23330. })(EasingFunction);
  23331. BABYLON.ExponentialEase = ExponentialEase;
  23332. var PowerEase = (function (_super) {
  23333. __extends(PowerEase, _super);
  23334. function PowerEase(power) {
  23335. if (power === void 0) { power = 2; }
  23336. _super.call(this);
  23337. this.power = power;
  23338. }
  23339. PowerEase.prototype.easeInCore = function (gradient) {
  23340. var y = Math.max(0.0, this.power);
  23341. return Math.pow(gradient, y);
  23342. };
  23343. return PowerEase;
  23344. })(EasingFunction);
  23345. BABYLON.PowerEase = PowerEase;
  23346. var QuadraticEase = (function (_super) {
  23347. __extends(QuadraticEase, _super);
  23348. function QuadraticEase() {
  23349. _super.apply(this, arguments);
  23350. }
  23351. QuadraticEase.prototype.easeInCore = function (gradient) {
  23352. return (gradient * gradient);
  23353. };
  23354. return QuadraticEase;
  23355. })(EasingFunction);
  23356. BABYLON.QuadraticEase = QuadraticEase;
  23357. var QuarticEase = (function (_super) {
  23358. __extends(QuarticEase, _super);
  23359. function QuarticEase() {
  23360. _super.apply(this, arguments);
  23361. }
  23362. QuarticEase.prototype.easeInCore = function (gradient) {
  23363. return (gradient * gradient * gradient * gradient);
  23364. };
  23365. return QuarticEase;
  23366. })(EasingFunction);
  23367. BABYLON.QuarticEase = QuarticEase;
  23368. var QuinticEase = (function (_super) {
  23369. __extends(QuinticEase, _super);
  23370. function QuinticEase() {
  23371. _super.apply(this, arguments);
  23372. }
  23373. QuinticEase.prototype.easeInCore = function (gradient) {
  23374. return (gradient * gradient * gradient * gradient * gradient);
  23375. };
  23376. return QuinticEase;
  23377. })(EasingFunction);
  23378. BABYLON.QuinticEase = QuinticEase;
  23379. var SineEase = (function (_super) {
  23380. __extends(SineEase, _super);
  23381. function SineEase() {
  23382. _super.apply(this, arguments);
  23383. }
  23384. SineEase.prototype.easeInCore = function (gradient) {
  23385. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23386. };
  23387. return SineEase;
  23388. })(EasingFunction);
  23389. BABYLON.SineEase = SineEase;
  23390. var BezierCurveEase = (function (_super) {
  23391. __extends(BezierCurveEase, _super);
  23392. function BezierCurveEase(x1, y1, x2, y2) {
  23393. if (x1 === void 0) { x1 = 0; }
  23394. if (y1 === void 0) { y1 = 0; }
  23395. if (x2 === void 0) { x2 = 1; }
  23396. if (y2 === void 0) { y2 = 1; }
  23397. _super.call(this);
  23398. this.x1 = x1;
  23399. this.y1 = y1;
  23400. this.x2 = x2;
  23401. this.y2 = y2;
  23402. }
  23403. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23404. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23405. };
  23406. return BezierCurveEase;
  23407. })(EasingFunction);
  23408. BABYLON.BezierCurveEase = BezierCurveEase;
  23409. })(BABYLON || (BABYLON = {}));
  23410. var BABYLON;
  23411. (function (BABYLON) {
  23412. var Bone = (function (_super) {
  23413. __extends(Bone, _super);
  23414. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23415. _super.call(this, name, skeleton.getScene());
  23416. this.name = name;
  23417. this.children = new Array();
  23418. this.animations = new Array();
  23419. this._worldTransform = new BABYLON.Matrix();
  23420. this._absoluteTransform = new BABYLON.Matrix();
  23421. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23422. this._skeleton = skeleton;
  23423. this._matrix = matrix;
  23424. this._baseMatrix = matrix;
  23425. this._restPose = restPose ? restPose : matrix.clone();
  23426. skeleton.bones.push(this);
  23427. if (parentBone) {
  23428. this._parent = parentBone;
  23429. parentBone.children.push(this);
  23430. }
  23431. else {
  23432. this._parent = null;
  23433. }
  23434. this._updateDifferenceMatrix();
  23435. }
  23436. // Members
  23437. Bone.prototype.getParent = function () {
  23438. return this._parent;
  23439. };
  23440. Bone.prototype.getLocalMatrix = function () {
  23441. return this._matrix;
  23442. };
  23443. Bone.prototype.getBaseMatrix = function () {
  23444. return this._baseMatrix;
  23445. };
  23446. Bone.prototype.getRestPose = function () {
  23447. return this._restPose;
  23448. };
  23449. Bone.prototype.returnToRest = function () {
  23450. this.updateMatrix(this._restPose.clone());
  23451. };
  23452. Bone.prototype.getWorldMatrix = function () {
  23453. return this._worldTransform;
  23454. };
  23455. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23456. return this._invertedAbsoluteTransform;
  23457. };
  23458. Bone.prototype.getAbsoluteTransform = function () {
  23459. return this._absoluteTransform;
  23460. };
  23461. // Methods
  23462. Bone.prototype.updateMatrix = function (matrix) {
  23463. this._baseMatrix = matrix.clone();
  23464. this._matrix = matrix.clone();
  23465. this._skeleton._markAsDirty();
  23466. this._updateDifferenceMatrix();
  23467. };
  23468. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23469. if (!rootMatrix) {
  23470. rootMatrix = this._baseMatrix;
  23471. }
  23472. if (this._parent) {
  23473. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23474. }
  23475. else {
  23476. this._absoluteTransform.copyFrom(rootMatrix);
  23477. }
  23478. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23479. for (var index = 0; index < this.children.length; index++) {
  23480. this.children[index]._updateDifferenceMatrix();
  23481. }
  23482. };
  23483. Bone.prototype.markAsDirty = function () {
  23484. this._currentRenderId++;
  23485. this._skeleton._markAsDirty();
  23486. };
  23487. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23488. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23489. // all animation may be coming from a library skeleton, so may need to create animation
  23490. if (this.animations.length === 0) {
  23491. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23492. this.animations[0].setKeys([{}]);
  23493. }
  23494. // get animation info / verify there is such a range from the source bone
  23495. var sourceRange = source.animations[0].getRange(rangeName);
  23496. if (!sourceRange) {
  23497. return false;
  23498. }
  23499. var from = sourceRange.from;
  23500. var to = sourceRange.to;
  23501. var sourceKeys = source.animations[0].getKeys();
  23502. // rescaling prep
  23503. var sourceBoneLength = source.length;
  23504. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23505. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23506. var destKeys = this.animations[0].getKeys();
  23507. // loop vars declaration / initialization
  23508. var orig;
  23509. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23510. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23511. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23512. var mat;
  23513. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23514. orig = sourceKeys[key];
  23515. if (orig.frame >= from && orig.frame <= to) {
  23516. if (scalingReqd) {
  23517. orig.value.decompose(origScale, origRotation, origTranslation);
  23518. origTranslation.scaleInPlace(ratio);
  23519. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23520. }
  23521. else {
  23522. mat = orig.value;
  23523. }
  23524. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23525. }
  23526. }
  23527. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23528. return true;
  23529. };
  23530. return Bone;
  23531. })(BABYLON.Node);
  23532. BABYLON.Bone = Bone;
  23533. })(BABYLON || (BABYLON = {}));
  23534. var BABYLON;
  23535. (function (BABYLON) {
  23536. var Skeleton = (function () {
  23537. function Skeleton(name, id, scene) {
  23538. this.name = name;
  23539. this.id = id;
  23540. this.bones = new Array();
  23541. this.needInitialSkinMatrix = false;
  23542. this._isDirty = true;
  23543. this._meshesWithPoseMatrix = new Array();
  23544. this._identity = BABYLON.Matrix.Identity();
  23545. this._ranges = {};
  23546. this.bones = [];
  23547. this._scene = scene;
  23548. scene.skeletons.push(this);
  23549. this.prepare();
  23550. //make sure it will recalculate the matrix next time prepare is called.
  23551. this._isDirty = true;
  23552. }
  23553. // Members
  23554. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23555. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23556. return mesh._bonesTransformMatrices;
  23557. }
  23558. return this._transformMatrices;
  23559. };
  23560. Skeleton.prototype.getScene = function () {
  23561. return this._scene;
  23562. };
  23563. // Methods
  23564. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23565. // check name not already in use
  23566. if (!this._ranges[name]) {
  23567. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23568. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23569. if (this.bones[i].animations[0]) {
  23570. this.bones[i].animations[0].createRange(name, from, to);
  23571. }
  23572. }
  23573. }
  23574. };
  23575. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23576. if (deleteFrames === void 0) { deleteFrames = true; }
  23577. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23578. if (this.bones[i].animations[0]) {
  23579. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23580. }
  23581. }
  23582. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23583. };
  23584. Skeleton.prototype.getAnimationRange = function (name) {
  23585. return this._ranges[name];
  23586. };
  23587. /**
  23588. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23589. */
  23590. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23591. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23592. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23593. return false;
  23594. }
  23595. var ret = true;
  23596. var frameOffset = this._getHighestAnimationFrame() + 1;
  23597. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23598. var boneDict = {};
  23599. var sourceBones = source.bones;
  23600. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23601. boneDict[sourceBones[i].name] = sourceBones[i];
  23602. }
  23603. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23604. var boneName = this.bones[i].name;
  23605. var sourceBone = boneDict[boneName];
  23606. if (sourceBone) {
  23607. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23608. }
  23609. else {
  23610. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23611. ret = false;
  23612. }
  23613. }
  23614. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23615. var range = source.getAnimationRange(name);
  23616. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23617. return ret;
  23618. };
  23619. Skeleton.prototype.returnToRest = function () {
  23620. for (var index = 0; index < this.bones.length; index++) {
  23621. this.bones[index].returnToRest();
  23622. }
  23623. };
  23624. Skeleton.prototype._getHighestAnimationFrame = function () {
  23625. var ret = 0;
  23626. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23627. if (this.bones[i].animations[0]) {
  23628. var highest = this.bones[i].animations[0].getHighestFrame();
  23629. if (ret < highest) {
  23630. ret = highest;
  23631. }
  23632. }
  23633. }
  23634. return ret;
  23635. };
  23636. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23637. var range = this.getAnimationRange(name);
  23638. if (!range) {
  23639. return null;
  23640. }
  23641. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23642. };
  23643. Skeleton.prototype._markAsDirty = function () {
  23644. this._isDirty = true;
  23645. };
  23646. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23647. this._meshesWithPoseMatrix.push(mesh);
  23648. };
  23649. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23650. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23651. if (index > -1) {
  23652. this._meshesWithPoseMatrix.splice(index, 1);
  23653. }
  23654. };
  23655. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23656. for (var index = 0; index < this.bones.length; index++) {
  23657. var bone = this.bones[index];
  23658. var parentBone = bone.getParent();
  23659. if (parentBone) {
  23660. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23661. }
  23662. else {
  23663. if (initialSkinMatrix) {
  23664. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23665. }
  23666. else {
  23667. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23668. }
  23669. }
  23670. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23671. }
  23672. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23673. };
  23674. Skeleton.prototype.prepare = function () {
  23675. if (!this._isDirty) {
  23676. return;
  23677. }
  23678. if (this.needInitialSkinMatrix) {
  23679. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23680. var mesh = this._meshesWithPoseMatrix[index];
  23681. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23682. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23683. }
  23684. var poseMatrix = mesh.getPoseMatrix();
  23685. // Prepare bones
  23686. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23687. var bone = this.bones[boneIndex];
  23688. if (!bone.getParent()) {
  23689. var matrix = bone.getBaseMatrix();
  23690. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23691. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23692. }
  23693. }
  23694. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23695. }
  23696. }
  23697. else {
  23698. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23699. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23700. }
  23701. this._computeTransformMatrices(this._transformMatrices, null);
  23702. }
  23703. this._isDirty = false;
  23704. this._scene._activeBones += this.bones.length;
  23705. };
  23706. Skeleton.prototype.getAnimatables = function () {
  23707. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23708. this._animatables = [];
  23709. for (var index = 0; index < this.bones.length; index++) {
  23710. this._animatables.push(this.bones[index]);
  23711. }
  23712. }
  23713. return this._animatables;
  23714. };
  23715. Skeleton.prototype.clone = function (name, id) {
  23716. var result = new Skeleton(name, id || name, this._scene);
  23717. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23718. for (var index = 0; index < this.bones.length; index++) {
  23719. var source = this.bones[index];
  23720. var parentBone = null;
  23721. if (source.getParent()) {
  23722. var parentIndex = this.bones.indexOf(source.getParent());
  23723. parentBone = result.bones[parentIndex];
  23724. }
  23725. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23726. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23727. }
  23728. if (this._ranges) {
  23729. result._ranges = {};
  23730. for (var rangeName in this._ranges) {
  23731. result._ranges[rangeName] = this._ranges[rangeName].clone();
  23732. }
  23733. }
  23734. result.prepare();
  23735. return result;
  23736. };
  23737. Skeleton.prototype.dispose = function () {
  23738. this._meshesWithPoseMatrix = [];
  23739. // Animations
  23740. this.getScene().stopAnimation(this);
  23741. // Remove from scene
  23742. this.getScene().removeSkeleton(this);
  23743. };
  23744. Skeleton.prototype.serialize = function () {
  23745. var serializationObject = {};
  23746. serializationObject.name = this.name;
  23747. serializationObject.id = this.id;
  23748. serializationObject.bones = [];
  23749. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23750. for (var index = 0; index < this.bones.length; index++) {
  23751. var bone = this.bones[index];
  23752. var serializedBone = {
  23753. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23754. name: bone.name,
  23755. matrix: bone.getLocalMatrix().toArray(),
  23756. rest: bone.getRestPose().toArray()
  23757. };
  23758. serializationObject.bones.push(serializedBone);
  23759. if (bone.length) {
  23760. serializedBone.length = bone.length;
  23761. }
  23762. if (bone.animations && bone.animations.length > 0) {
  23763. serializedBone.animation = bone.animations[0].serialize();
  23764. }
  23765. serializationObject.ranges = [];
  23766. for (var name in this._ranges) {
  23767. var range = {};
  23768. range.name = name;
  23769. range.from = this._ranges[name].from;
  23770. range.to = this._ranges[name].to;
  23771. serializationObject.ranges.push(range);
  23772. }
  23773. }
  23774. return serializationObject;
  23775. };
  23776. Skeleton.Parse = function (parsedSkeleton, scene) {
  23777. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23778. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23779. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23780. var parsedBone = parsedSkeleton.bones[index];
  23781. var parentBone = null;
  23782. if (parsedBone.parentBoneIndex > -1) {
  23783. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23784. }
  23785. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23786. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23787. if (parsedBone.length) {
  23788. bone.length = parsedBone.length;
  23789. }
  23790. if (parsedBone.animation) {
  23791. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23792. }
  23793. }
  23794. // placed after bones, so createAnimationRange can cascade down
  23795. if (parsedSkeleton.ranges) {
  23796. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23797. var data = parsedSkeleton.ranges[index];
  23798. skeleton.createAnimationRange(data.name, data.from, data.to);
  23799. }
  23800. }
  23801. return skeleton;
  23802. };
  23803. return Skeleton;
  23804. })();
  23805. BABYLON.Skeleton = Skeleton;
  23806. })(BABYLON || (BABYLON = {}));
  23807. var BABYLON;
  23808. (function (BABYLON) {
  23809. var PostProcess = (function () {
  23810. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23813. this.name = name;
  23814. this.width = -1;
  23815. this.height = -1;
  23816. this._reusable = false;
  23817. this._textures = new BABYLON.SmartArray(2);
  23818. this._currentRenderTextureInd = 0;
  23819. if (camera != null) {
  23820. this._camera = camera;
  23821. this._scene = camera.getScene();
  23822. camera.attachPostProcess(this);
  23823. this._engine = this._scene.getEngine();
  23824. }
  23825. else {
  23826. this._engine = engine;
  23827. }
  23828. this._renderRatio = ratio;
  23829. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23830. this._reusable = reusable || false;
  23831. this._textureType = textureType;
  23832. this._samplers = samplers || [];
  23833. this._samplers.push("textureSampler");
  23834. this._fragmentUrl = fragmentUrl;
  23835. this._parameters = parameters || [];
  23836. this.updateEffect(defines);
  23837. }
  23838. PostProcess.prototype.updateEffect = function (defines) {
  23839. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23840. };
  23841. PostProcess.prototype.isReusable = function () {
  23842. return this._reusable;
  23843. };
  23844. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23845. camera = camera || this._camera;
  23846. var scene = camera.getScene();
  23847. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23848. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23849. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23850. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23851. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23852. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23853. if (this._textures.length > 0) {
  23854. for (var i = 0; i < this._textures.length; i++) {
  23855. this._engine._releaseTexture(this._textures.data[i]);
  23856. }
  23857. this._textures.reset();
  23858. }
  23859. this.width = desiredWidth;
  23860. this.height = desiredHeight;
  23861. 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 }));
  23862. if (this._reusable) {
  23863. 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 }));
  23864. }
  23865. if (this.onSizeChanged) {
  23866. this.onSizeChanged();
  23867. }
  23868. }
  23869. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23870. if (this.onActivate) {
  23871. this.onActivate(camera);
  23872. }
  23873. // Clear
  23874. if (this.clearColor) {
  23875. this._engine.clear(this.clearColor, true, true);
  23876. }
  23877. else {
  23878. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23879. }
  23880. if (this._reusable) {
  23881. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23882. }
  23883. };
  23884. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23885. get: function () {
  23886. return this._effect.isSupported;
  23887. },
  23888. enumerable: true,
  23889. configurable: true
  23890. });
  23891. PostProcess.prototype.apply = function () {
  23892. // Check
  23893. if (!this._effect.isReady())
  23894. return null;
  23895. // States
  23896. this._engine.enableEffect(this._effect);
  23897. this._engine.setState(false);
  23898. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23899. this._engine.setDepthBuffer(false);
  23900. this._engine.setDepthWrite(false);
  23901. // Texture
  23902. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23903. // Parameters
  23904. if (this.onApply) {
  23905. this.onApply(this._effect);
  23906. }
  23907. return this._effect;
  23908. };
  23909. PostProcess.prototype.dispose = function (camera) {
  23910. camera = camera || this._camera;
  23911. if (this._textures.length > 0) {
  23912. for (var i = 0; i < this._textures.length; i++) {
  23913. this._engine._releaseTexture(this._textures.data[i]);
  23914. }
  23915. this._textures.reset();
  23916. }
  23917. if (!camera) {
  23918. return;
  23919. }
  23920. camera.detachPostProcess(this);
  23921. var index = camera._postProcesses.indexOf(this);
  23922. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23923. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23924. }
  23925. };
  23926. return PostProcess;
  23927. })();
  23928. BABYLON.PostProcess = PostProcess;
  23929. })(BABYLON || (BABYLON = {}));
  23930. var BABYLON;
  23931. (function (BABYLON) {
  23932. var PostProcessManager = (function () {
  23933. function PostProcessManager(scene) {
  23934. this._vertexDeclaration = [2];
  23935. this._vertexStrideSize = 2 * 4;
  23936. this._scene = scene;
  23937. }
  23938. PostProcessManager.prototype._prepareBuffers = function () {
  23939. if (this._vertexBuffer) {
  23940. return;
  23941. }
  23942. // VBO
  23943. var vertices = [];
  23944. vertices.push(1, 1);
  23945. vertices.push(-1, 1);
  23946. vertices.push(-1, -1);
  23947. vertices.push(1, -1);
  23948. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23949. // Indices
  23950. var indices = [];
  23951. indices.push(0);
  23952. indices.push(1);
  23953. indices.push(2);
  23954. indices.push(0);
  23955. indices.push(2);
  23956. indices.push(3);
  23957. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23958. };
  23959. // Methods
  23960. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23961. var postProcesses = this._scene.activeCamera._postProcesses;
  23962. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23963. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23964. return false;
  23965. }
  23966. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23967. return true;
  23968. };
  23969. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23970. var engine = this._scene.getEngine();
  23971. for (var index = 0; index < postProcesses.length; index++) {
  23972. if (index < postProcesses.length - 1) {
  23973. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23974. }
  23975. else {
  23976. if (targetTexture) {
  23977. engine.bindFramebuffer(targetTexture);
  23978. }
  23979. else {
  23980. engine.restoreDefaultFramebuffer();
  23981. }
  23982. }
  23983. var pp = postProcesses[index];
  23984. var effect = pp.apply();
  23985. if (effect) {
  23986. if (pp.onBeforeRender) {
  23987. pp.onBeforeRender(effect);
  23988. }
  23989. // VBOs
  23990. this._prepareBuffers();
  23991. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23992. // Draw order
  23993. engine.draw(true, 0, 6);
  23994. if (pp.onAfterRender) {
  23995. pp.onAfterRender(effect);
  23996. }
  23997. }
  23998. }
  23999. // Restore depth buffer
  24000. engine.setDepthBuffer(true);
  24001. engine.setDepthWrite(true);
  24002. };
  24003. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  24004. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  24005. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  24006. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  24007. return;
  24008. }
  24009. var engine = this._scene.getEngine();
  24010. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  24011. if (index < postProcessesTakenIndices.length - 1) {
  24012. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  24013. }
  24014. else {
  24015. if (targetTexture) {
  24016. engine.bindFramebuffer(targetTexture, faceIndex);
  24017. }
  24018. else {
  24019. engine.restoreDefaultFramebuffer();
  24020. }
  24021. }
  24022. if (doNotPresent) {
  24023. break;
  24024. }
  24025. var pp = postProcesses[postProcessesTakenIndices[index]];
  24026. var effect = pp.apply();
  24027. if (effect) {
  24028. if (pp.onBeforeRender) {
  24029. pp.onBeforeRender(effect);
  24030. }
  24031. // VBOs
  24032. this._prepareBuffers();
  24033. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24034. // Draw order
  24035. engine.draw(true, 0, 6);
  24036. if (pp.onAfterRender) {
  24037. pp.onAfterRender(effect);
  24038. }
  24039. }
  24040. }
  24041. // Restore depth buffer
  24042. engine.setDepthBuffer(true);
  24043. engine.setDepthWrite(true);
  24044. };
  24045. PostProcessManager.prototype.dispose = function () {
  24046. if (this._vertexBuffer) {
  24047. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24048. this._vertexBuffer = null;
  24049. }
  24050. if (this._indexBuffer) {
  24051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24052. this._indexBuffer = null;
  24053. }
  24054. };
  24055. return PostProcessManager;
  24056. })();
  24057. BABYLON.PostProcessManager = PostProcessManager;
  24058. })(BABYLON || (BABYLON = {}));
  24059. var BABYLON;
  24060. (function (BABYLON) {
  24061. var PassPostProcess = (function (_super) {
  24062. __extends(PassPostProcess, _super);
  24063. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24064. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  24065. }
  24066. return PassPostProcess;
  24067. })(BABYLON.PostProcess);
  24068. BABYLON.PassPostProcess = PassPostProcess;
  24069. })(BABYLON || (BABYLON = {}));
  24070. var BABYLON;
  24071. (function (BABYLON) {
  24072. var PhysicsJoint = (function () {
  24073. function PhysicsJoint(type, jointData) {
  24074. this.type = type;
  24075. this.jointData = jointData;
  24076. jointData.nativeParams = jointData.nativeParams || {};
  24077. }
  24078. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  24079. get: function () {
  24080. return this._physicsJoint;
  24081. },
  24082. set: function (newJoint) {
  24083. if (this._physicsJoint) {
  24084. }
  24085. this._physicsJoint = newJoint;
  24086. },
  24087. enumerable: true,
  24088. configurable: true
  24089. });
  24090. //TODO check if the native joints are the same
  24091. //Joint Types
  24092. PhysicsJoint.DistanceJoint = 0;
  24093. PhysicsJoint.HingeJoint = 1;
  24094. PhysicsJoint.BallAndSocketJoint = 2;
  24095. PhysicsJoint.WheelJoint = 3;
  24096. PhysicsJoint.SliderJoint = 4;
  24097. //OIMO
  24098. PhysicsJoint.PrismaticJoint = 5;
  24099. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  24100. PhysicsJoint.UniversalJoint = 6;
  24101. PhysicsJoint.Hinge2Joint = 7;
  24102. //Cannon
  24103. //Similar to a Ball-Joint. Different in params
  24104. //TODO check!!
  24105. PhysicsJoint.PointToPointJoint = 8;
  24106. //Cannon only at the moment
  24107. PhysicsJoint.SpringJoint = 9;
  24108. return PhysicsJoint;
  24109. })();
  24110. BABYLON.PhysicsJoint = PhysicsJoint;
  24111. })(BABYLON || (BABYLON = {}));
  24112. var BABYLON;
  24113. (function (BABYLON) {
  24114. var PhysicsImpostor = (function () {
  24115. function PhysicsImpostor(_mesh, type, _options) {
  24116. var _this = this;
  24117. if (_options === void 0) { _options = { mass: 0 }; }
  24118. this._mesh = _mesh;
  24119. this.type = type;
  24120. this._options = _options;
  24121. this._bodyUpdateRequired = false;
  24122. this._onBeforePhysicsStepCallbacks = new Array();
  24123. this._onAfterPhysicsStepCallbacks = new Array();
  24124. this._onPhysicsCollideCallbacks = [];
  24125. this._deltaPosition = BABYLON.Vector3.Zero();
  24126. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  24127. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  24128. /**
  24129. * this function is executed by the physics engine.
  24130. */
  24131. this.beforeStep = function () {
  24132. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  24133. //conjugate deltaRotation
  24134. if (_this._deltaRotationConjugated) {
  24135. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  24136. }
  24137. else {
  24138. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  24139. }
  24140. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  24141. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  24142. func(_this);
  24143. });
  24144. };
  24145. /**
  24146. * this function is executed by the physics engine.
  24147. */
  24148. this.afterStep = function () {
  24149. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  24150. func(_this);
  24151. });
  24152. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  24153. _this.mesh.position.addInPlace(_this._deltaPosition);
  24154. if (_this._deltaRotation) {
  24155. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  24156. }
  24157. };
  24158. //event and body object due to cannon's event-based architecture.
  24159. this.onCollide = function (e) {
  24160. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  24161. if (otherImpostor) {
  24162. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  24163. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  24164. }).forEach(function (obj) {
  24165. obj.callback(_this, otherImpostor);
  24166. });
  24167. }
  24168. };
  24169. //default options params
  24170. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24171. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24172. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24173. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24174. this._joints = [];
  24175. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24176. if (!this._mesh.parent) {
  24177. this._init();
  24178. }
  24179. }
  24180. /**
  24181. * This function will completly initialize this impostor.
  24182. * It will create a new body - but only if this mesh has no parent.
  24183. * If it has, this impostor will not be used other than to define the impostor
  24184. * of the child mesh.
  24185. */
  24186. PhysicsImpostor.prototype._init = function () {
  24187. this._physicsEngine.removeImpostor(this);
  24188. this.physicsBody = null;
  24189. this._parent = this._parent || this._getPhysicsParent();
  24190. if (!this.parent) {
  24191. this._physicsEngine.addImpostor(this);
  24192. }
  24193. };
  24194. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24195. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24196. var parentMesh = this.mesh.parent;
  24197. return parentMesh.getPhysicsImpostor();
  24198. }
  24199. return;
  24200. };
  24201. /**
  24202. * Should a new body be generated.
  24203. */
  24204. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24205. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24206. };
  24207. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24208. this.forceUpdate();
  24209. };
  24210. /**
  24211. * Force a regeneration of this or the parent's impostor's body.
  24212. * Use under cautious - This will remove all joints already implemented.
  24213. */
  24214. PhysicsImpostor.prototype.forceUpdate = function () {
  24215. this._init();
  24216. if (this.parent) {
  24217. this.parent.forceUpdate();
  24218. }
  24219. };
  24220. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24221. get: function () {
  24222. return this._mesh;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24228. /**
  24229. * Gets the body that holds this impostor. Either its own, or its parent.
  24230. */
  24231. get: function () {
  24232. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24233. },
  24234. /**
  24235. * Set the physics body. Used mainly by the physics engine/plugin
  24236. */
  24237. set: function (physicsBody) {
  24238. if (this._physicsBody) {
  24239. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24240. }
  24241. this._physicsBody = physicsBody;
  24242. this.resetUpdateFlags();
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24248. get: function () {
  24249. return this._parent;
  24250. },
  24251. enumerable: true,
  24252. configurable: true
  24253. });
  24254. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24255. this._bodyUpdateRequired = false;
  24256. };
  24257. /**
  24258. * Get a specific parametes from the options parameter.
  24259. */
  24260. PhysicsImpostor.prototype.getParam = function (paramName) {
  24261. return this._options[paramName];
  24262. };
  24263. /**
  24264. * Sets a specific parameter in the options given to the physics plugin
  24265. */
  24266. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24267. this._options[paramName] = value;
  24268. this._bodyUpdateRequired = true;
  24269. };
  24270. /**
  24271. * Specifically change the body's mass option. Won't recreate the physics body object
  24272. */
  24273. PhysicsImpostor.prototype.setMass = function (mass) {
  24274. if (this.getParam("mass") !== mass) {
  24275. this.setParam("mass", mass);
  24276. }
  24277. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  24278. };
  24279. /**
  24280. * Set the body's linear velocity.
  24281. */
  24282. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  24283. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  24284. };
  24285. /**
  24286. * Set the body's linear velocity.
  24287. */
  24288. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  24289. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  24290. };
  24291. /**
  24292. * Execute a function with the physics plugin native code.
  24293. * Provide a function the will have two variables - the world object and the physics body object.
  24294. */
  24295. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24296. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24297. };
  24298. /**
  24299. * Register a function that will be executed before the physics world is stepping forward.
  24300. */
  24301. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24302. this._onBeforePhysicsStepCallbacks.push(func);
  24303. };
  24304. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24305. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24306. if (index > -1) {
  24307. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24308. }
  24309. else {
  24310. BABYLON.Tools.Warn("Function to remove was not found");
  24311. }
  24312. };
  24313. /**
  24314. * Register a function that will be executed after the physics step
  24315. */
  24316. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24317. this._onAfterPhysicsStepCallbacks.push(func);
  24318. };
  24319. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24320. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24321. if (index > -1) {
  24322. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24323. }
  24324. else {
  24325. BABYLON.Tools.Warn("Function to remove was not found");
  24326. }
  24327. };
  24328. /**
  24329. * register a function that will be executed when this impostor collides against a different body.
  24330. */
  24331. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24332. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24333. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  24334. };
  24335. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24336. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24337. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  24338. if (index > -1) {
  24339. this._onPhysicsCollideCallbacks.splice(index, 1);
  24340. }
  24341. else {
  24342. BABYLON.Tools.Warn("Function to remove was not found");
  24343. }
  24344. };
  24345. /**
  24346. * Apply a force
  24347. */
  24348. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24349. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24350. };
  24351. /**
  24352. * Apply an impulse
  24353. */
  24354. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24355. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24356. };
  24357. /**
  24358. * A help function to create a joint.
  24359. */
  24360. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24361. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24362. this.addJoint(otherImpostor, joint);
  24363. };
  24364. /**
  24365. * Add a joint to this impostor with a different impostor.
  24366. */
  24367. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24368. this._joints.push({
  24369. otherImpostor: otherImpostor,
  24370. joint: joint
  24371. });
  24372. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24373. };
  24374. /**
  24375. * Will keep this body still, in a sleep mode.
  24376. */
  24377. PhysicsImpostor.prototype.sleep = function () {
  24378. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  24379. };
  24380. /**
  24381. * Wake the body up.
  24382. */
  24383. PhysicsImpostor.prototype.wakeUp = function () {
  24384. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  24385. };
  24386. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24387. if (disposeChildren === void 0) { disposeChildren = true; }
  24388. this.physicsBody = null;
  24389. if (this.parent) {
  24390. this.parent.forceUpdate();
  24391. }
  24392. else {
  24393. this.mesh.getChildMeshes().forEach(function (mesh) {
  24394. if (mesh.physicsImpostor) {
  24395. if (disposeChildren) {
  24396. mesh.physicsImpostor.dispose();
  24397. mesh.physicsImpostor = null;
  24398. }
  24399. }
  24400. });
  24401. }
  24402. };
  24403. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24404. this._deltaPosition.copyFrom(position);
  24405. };
  24406. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24407. if (!this._deltaRotation) {
  24408. this._deltaRotation = new BABYLON.Quaternion();
  24409. }
  24410. this._deltaRotation.copyFrom(rotation);
  24411. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  24412. };
  24413. //Impostor types
  24414. PhysicsImpostor.NoImpostor = 0;
  24415. PhysicsImpostor.SphereImpostor = 1;
  24416. PhysicsImpostor.BoxImpostor = 2;
  24417. PhysicsImpostor.PlaneImpostor = 3;
  24418. PhysicsImpostor.MeshImpostor = 4;
  24419. PhysicsImpostor.CapsuleImpostor = 5;
  24420. PhysicsImpostor.ConeImpostor = 6;
  24421. PhysicsImpostor.CylinderImpostor = 7;
  24422. PhysicsImpostor.ConvexHullImpostor = 8;
  24423. PhysicsImpostor.HeightmapImpostor = 9;
  24424. return PhysicsImpostor;
  24425. })();
  24426. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24427. })(BABYLON || (BABYLON = {}));
  24428. var BABYLON;
  24429. (function (BABYLON) {
  24430. var PhysicsEngine = (function () {
  24431. function PhysicsEngine(gravity, _physicsPlugin) {
  24432. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24433. this._physicsPlugin = _physicsPlugin;
  24434. //new methods and parameters
  24435. this._impostors = [];
  24436. this._joints = [];
  24437. if (!this._physicsPlugin.isSupported()) {
  24438. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24439. + "Please make sure it is included.");
  24440. }
  24441. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24442. this.setGravity(gravity);
  24443. this.setTimeStep();
  24444. }
  24445. PhysicsEngine.prototype.setGravity = function (gravity) {
  24446. this.gravity = gravity;
  24447. this._physicsPlugin.setGravity(this.gravity);
  24448. };
  24449. /**
  24450. * Set the time step of the physics engine.
  24451. * default is 1/60.
  24452. * To slow it down, enter 1/600 for example.
  24453. * To speed it up, 1/30
  24454. */
  24455. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  24456. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  24457. this._physicsPlugin.setTimeStep(newTimeStep);
  24458. };
  24459. PhysicsEngine.prototype.dispose = function () {
  24460. this._impostors.forEach(function (impostor) {
  24461. impostor.dispose();
  24462. });
  24463. this._physicsPlugin.dispose();
  24464. };
  24465. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24466. return this._physicsPlugin.name;
  24467. };
  24468. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24469. this._impostors.push(impostor);
  24470. //if no parent, generate the body
  24471. if (!impostor.parent) {
  24472. this._physicsPlugin.generatePhysicsBody(impostor);
  24473. }
  24474. };
  24475. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24476. var index = this._impostors.indexOf(impostor);
  24477. if (index > -1) {
  24478. var removed = this._impostors.splice(index, 1);
  24479. //Is it needed?
  24480. if (removed.length) {
  24481. //this will also remove it from the world.
  24482. removed[0].physicsBody = null;
  24483. }
  24484. }
  24485. };
  24486. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24487. var impostorJoint = {
  24488. mainImpostor: mainImpostor,
  24489. connectedImpostor: connectedImpostor,
  24490. joint: joint
  24491. };
  24492. this._joints.push(impostorJoint);
  24493. this._physicsPlugin.generateJoint(impostorJoint);
  24494. };
  24495. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24496. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24497. return (impostorJoint.connectedImpostor === connectedImpostor
  24498. && impostorJoint.joint === joint
  24499. && impostorJoint.mainImpostor === mainImpostor);
  24500. });
  24501. if (matchingJoints.length) {
  24502. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24503. }
  24504. };
  24505. /**
  24506. * Called by the scene. no need to call it.
  24507. */
  24508. PhysicsEngine.prototype._step = function (delta) {
  24509. var _this = this;
  24510. //check if any mesh has no body / requires an update
  24511. this._impostors.forEach(function (impostor) {
  24512. if (impostor.isBodyInitRequired()) {
  24513. _this._physicsPlugin.generatePhysicsBody(impostor);
  24514. }
  24515. });
  24516. if (delta > 0.1) {
  24517. delta = 0.1;
  24518. }
  24519. else if (delta <= 0) {
  24520. delta = 1.0 / 60.0;
  24521. }
  24522. this._physicsPlugin.executeStep(delta, this._impostors);
  24523. };
  24524. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24525. return this._physicsPlugin;
  24526. };
  24527. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24528. for (var i = 0; i < this._impostors.length; ++i) {
  24529. if (this._impostors[i].physicsBody === body) {
  24530. return this._impostors[i];
  24531. }
  24532. }
  24533. };
  24534. // Statics, Legacy support.
  24535. /**
  24536. * @Deprecated
  24537. *
  24538. */
  24539. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24540. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24541. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24542. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24543. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24544. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24545. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24546. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24547. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24548. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24549. PhysicsEngine.Epsilon = 0.001;
  24550. return PhysicsEngine;
  24551. })();
  24552. BABYLON.PhysicsEngine = PhysicsEngine;
  24553. })(BABYLON || (BABYLON = {}));
  24554. var BABYLON;
  24555. (function (BABYLON) {
  24556. var VertexData = (function () {
  24557. function VertexData() {
  24558. }
  24559. VertexData.prototype.set = function (data, kind) {
  24560. switch (kind) {
  24561. case BABYLON.VertexBuffer.PositionKind:
  24562. this.positions = data;
  24563. break;
  24564. case BABYLON.VertexBuffer.NormalKind:
  24565. this.normals = data;
  24566. break;
  24567. case BABYLON.VertexBuffer.UVKind:
  24568. this.uvs = data;
  24569. break;
  24570. case BABYLON.VertexBuffer.UV2Kind:
  24571. this.uvs2 = data;
  24572. break;
  24573. case BABYLON.VertexBuffer.UV3Kind:
  24574. this.uvs3 = data;
  24575. break;
  24576. case BABYLON.VertexBuffer.UV4Kind:
  24577. this.uvs4 = data;
  24578. break;
  24579. case BABYLON.VertexBuffer.UV5Kind:
  24580. this.uvs5 = data;
  24581. break;
  24582. case BABYLON.VertexBuffer.UV6Kind:
  24583. this.uvs6 = data;
  24584. break;
  24585. case BABYLON.VertexBuffer.ColorKind:
  24586. this.colors = data;
  24587. break;
  24588. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24589. this.matricesIndices = data;
  24590. break;
  24591. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24592. this.matricesWeights = data;
  24593. break;
  24594. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24595. this.matricesIndicesExtra = data;
  24596. break;
  24597. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24598. this.matricesWeightsExtra = data;
  24599. break;
  24600. }
  24601. };
  24602. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24603. this._applyTo(mesh, updatable);
  24604. };
  24605. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24606. this._applyTo(geometry, updatable);
  24607. };
  24608. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24609. this._update(mesh);
  24610. };
  24611. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24612. this._update(geometry);
  24613. };
  24614. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24615. if (this.positions) {
  24616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24617. }
  24618. if (this.normals) {
  24619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24620. }
  24621. if (this.uvs) {
  24622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24623. }
  24624. if (this.uvs2) {
  24625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24626. }
  24627. if (this.uvs3) {
  24628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24629. }
  24630. if (this.uvs4) {
  24631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24632. }
  24633. if (this.uvs5) {
  24634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24635. }
  24636. if (this.uvs6) {
  24637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24638. }
  24639. if (this.colors) {
  24640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24641. }
  24642. if (this.matricesIndices) {
  24643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24644. }
  24645. if (this.matricesWeights) {
  24646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24647. }
  24648. if (this.matricesIndicesExtra) {
  24649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24650. }
  24651. if (this.matricesWeightsExtra) {
  24652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24653. }
  24654. if (this.indices) {
  24655. meshOrGeometry.setIndices(this.indices);
  24656. }
  24657. };
  24658. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24659. if (this.positions) {
  24660. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24661. }
  24662. if (this.normals) {
  24663. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24664. }
  24665. if (this.uvs) {
  24666. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24667. }
  24668. if (this.uvs2) {
  24669. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24670. }
  24671. if (this.uvs3) {
  24672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24673. }
  24674. if (this.uvs4) {
  24675. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24676. }
  24677. if (this.uvs5) {
  24678. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24679. }
  24680. if (this.uvs6) {
  24681. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24682. }
  24683. if (this.colors) {
  24684. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24685. }
  24686. if (this.matricesIndices) {
  24687. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24688. }
  24689. if (this.matricesWeights) {
  24690. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24691. }
  24692. if (this.matricesIndicesExtra) {
  24693. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24694. }
  24695. if (this.matricesWeightsExtra) {
  24696. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24697. }
  24698. if (this.indices) {
  24699. meshOrGeometry.setIndices(this.indices);
  24700. }
  24701. };
  24702. VertexData.prototype.transform = function (matrix) {
  24703. var transformed = BABYLON.Vector3.Zero();
  24704. var index;
  24705. if (this.positions) {
  24706. var position = BABYLON.Vector3.Zero();
  24707. for (index = 0; index < this.positions.length; index += 3) {
  24708. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24709. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24710. this.positions[index] = transformed.x;
  24711. this.positions[index + 1] = transformed.y;
  24712. this.positions[index + 2] = transformed.z;
  24713. }
  24714. }
  24715. if (this.normals) {
  24716. var normal = BABYLON.Vector3.Zero();
  24717. for (index = 0; index < this.normals.length; index += 3) {
  24718. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24719. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24720. this.normals[index] = transformed.x;
  24721. this.normals[index + 1] = transformed.y;
  24722. this.normals[index + 2] = transformed.z;
  24723. }
  24724. }
  24725. };
  24726. VertexData.prototype.merge = function (other) {
  24727. if (other.indices) {
  24728. if (!this.indices) {
  24729. this.indices = [];
  24730. }
  24731. var offset = this.positions ? this.positions.length / 3 : 0;
  24732. for (var index = 0; index < other.indices.length; index++) {
  24733. //TODO check type - if Int32Array!
  24734. this.indices.push(other.indices[index] + offset);
  24735. }
  24736. }
  24737. this.positions = this._mergeElement(this.positions, other.positions);
  24738. this.normals = this._mergeElement(this.normals, other.normals);
  24739. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24740. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24741. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24742. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24743. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24744. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24745. this.colors = this._mergeElement(this.colors, other.colors);
  24746. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24747. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24748. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24749. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24750. };
  24751. VertexData.prototype._mergeElement = function (source, other) {
  24752. if (!other)
  24753. return source;
  24754. if (!source)
  24755. return other;
  24756. var len = other.length + source.length;
  24757. var isSrcTypedArray = source instanceof Float32Array;
  24758. var isOthTypedArray = other instanceof Float32Array;
  24759. // use non-loop method when the source is Float32Array
  24760. if (isSrcTypedArray) {
  24761. var ret32 = new Float32Array(len);
  24762. ret32.set(source);
  24763. ret32.set(other, source.length);
  24764. return ret32;
  24765. }
  24766. else if (!isOthTypedArray) {
  24767. return source.concat(other);
  24768. }
  24769. else {
  24770. var ret = source.slice(0); // copy source to a separate array
  24771. for (var i = 0, len = other.length; i < len; i++) {
  24772. ret.push(other[i]);
  24773. }
  24774. return ret;
  24775. }
  24776. };
  24777. VertexData.prototype.serialize = function () {
  24778. var serializationObject = this.serialize();
  24779. if (this.positions) {
  24780. serializationObject.positions = this.positions;
  24781. }
  24782. if (this.normals) {
  24783. serializationObject.normals = this.normals;
  24784. }
  24785. if (this.uvs) {
  24786. serializationObject.uvs = this.uvs;
  24787. }
  24788. if (this.uvs2) {
  24789. serializationObject.uvs2 = this.uvs2;
  24790. }
  24791. if (this.uvs3) {
  24792. serializationObject.uvs3 = this.uvs3;
  24793. }
  24794. if (this.uvs4) {
  24795. serializationObject.uvs4 = this.uvs4;
  24796. }
  24797. if (this.uvs5) {
  24798. serializationObject.uvs5 = this.uvs5;
  24799. }
  24800. if (this.uvs6) {
  24801. serializationObject.uvs6 = this.uvs6;
  24802. }
  24803. if (this.colors) {
  24804. serializationObject.colors = this.colors;
  24805. }
  24806. if (this.matricesIndices) {
  24807. serializationObject.matricesIndices = this.matricesIndices;
  24808. serializationObject.matricesIndices._isExpanded = true;
  24809. }
  24810. if (this.matricesWeights) {
  24811. serializationObject.matricesWeights = this.matricesWeights;
  24812. }
  24813. if (this.matricesIndicesExtra) {
  24814. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24815. serializationObject.matricesIndicesExtra._isExpanded = true;
  24816. }
  24817. if (this.matricesWeightsExtra) {
  24818. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24819. }
  24820. serializationObject.indices = this.indices;
  24821. return serializationObject;
  24822. };
  24823. // Statics
  24824. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24825. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24826. };
  24827. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24828. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24829. };
  24830. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24831. var result = new VertexData();
  24832. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24833. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24834. }
  24835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24836. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24837. }
  24838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24839. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24840. }
  24841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24842. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24843. }
  24844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24845. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24846. }
  24847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24848. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24849. }
  24850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24851. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24852. }
  24853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24854. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24855. }
  24856. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24857. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24858. }
  24859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24860. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24861. }
  24862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24863. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24864. }
  24865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24866. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24867. }
  24868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24869. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24870. }
  24871. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24872. return result;
  24873. };
  24874. VertexData.CreateRibbon = function (options) {
  24875. var pathArray = options.pathArray;
  24876. var closeArray = options.closeArray || false;
  24877. var closePath = options.closePath || false;
  24878. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24879. var offset = options.offset || defaultOffset;
  24880. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24881. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24882. var positions = [];
  24883. var indices = [];
  24884. var normals = [];
  24885. var uvs = [];
  24886. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24887. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24888. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24889. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24890. var minlg; // minimal length among all paths from pathArray
  24891. var lg = []; // array of path lengths : nb of vertex per path
  24892. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24893. var p; // path iterator
  24894. var i; // point iterator
  24895. var j; // point iterator
  24896. // if single path in pathArray
  24897. if (pathArray.length < 2) {
  24898. var ar1 = [];
  24899. var ar2 = [];
  24900. for (i = 0; i < pathArray[0].length - offset; i++) {
  24901. ar1.push(pathArray[0][i]);
  24902. ar2.push(pathArray[0][i + offset]);
  24903. }
  24904. pathArray = [ar1, ar2];
  24905. }
  24906. // positions and horizontal distances (u)
  24907. var idc = 0;
  24908. var closePathCorr = (closePath) ? 1 : 0;
  24909. var path;
  24910. var l;
  24911. minlg = pathArray[0].length;
  24912. var vectlg;
  24913. var dist;
  24914. for (p = 0; p < pathArray.length; p++) {
  24915. uTotalDistance[p] = 0;
  24916. us[p] = [0];
  24917. path = pathArray[p];
  24918. l = path.length;
  24919. minlg = (minlg < l) ? minlg : l;
  24920. j = 0;
  24921. while (j < l) {
  24922. positions.push(path[j].x, path[j].y, path[j].z);
  24923. if (j > 0) {
  24924. vectlg = path[j].subtract(path[j - 1]).length();
  24925. dist = vectlg + uTotalDistance[p];
  24926. us[p].push(dist);
  24927. uTotalDistance[p] = dist;
  24928. }
  24929. j++;
  24930. }
  24931. if (closePath) {
  24932. j--;
  24933. positions.push(path[0].x, path[0].y, path[0].z);
  24934. vectlg = path[j].subtract(path[0]).length();
  24935. dist = vectlg + uTotalDistance[p];
  24936. us[p].push(dist);
  24937. uTotalDistance[p] = dist;
  24938. }
  24939. lg[p] = l + closePathCorr;
  24940. idx[p] = idc;
  24941. idc += (l + closePathCorr);
  24942. }
  24943. // vertical distances (v)
  24944. var path1;
  24945. var path2;
  24946. var vertex1;
  24947. var vertex2;
  24948. for (i = 0; i < minlg + closePathCorr; i++) {
  24949. vTotalDistance[i] = 0;
  24950. vs[i] = [0];
  24951. for (p = 0; p < pathArray.length - 1; p++) {
  24952. path1 = pathArray[p];
  24953. path2 = pathArray[p + 1];
  24954. if (i === minlg) {
  24955. vertex1 = path1[0];
  24956. vertex2 = path2[0];
  24957. }
  24958. else {
  24959. vertex1 = path1[i];
  24960. vertex2 = path2[i];
  24961. }
  24962. vectlg = vertex2.subtract(vertex1).length();
  24963. dist = vectlg + vTotalDistance[i];
  24964. vs[i].push(dist);
  24965. vTotalDistance[i] = dist;
  24966. }
  24967. if (closeArray) {
  24968. path1 = pathArray[p];
  24969. path2 = pathArray[0];
  24970. if (i === minlg) {
  24971. vertex2 = path2[0];
  24972. }
  24973. vectlg = vertex2.subtract(vertex1).length();
  24974. dist = vectlg + vTotalDistance[i];
  24975. vTotalDistance[i] = dist;
  24976. }
  24977. }
  24978. // uvs
  24979. var u;
  24980. var v;
  24981. for (p = 0; p < pathArray.length; p++) {
  24982. for (i = 0; i < minlg + closePathCorr; i++) {
  24983. u = us[p][i] / uTotalDistance[p];
  24984. v = vs[i][p] / vTotalDistance[i];
  24985. uvs.push(u, v);
  24986. }
  24987. }
  24988. // indices
  24989. p = 0; // path index
  24990. var pi = 0; // positions array index
  24991. var l1 = lg[p] - 1; // path1 length
  24992. var l2 = lg[p + 1] - 1; // path2 length
  24993. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24994. var shft = idx[1] - idx[0]; // shift
  24995. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24996. while (pi <= min && p < path1nb) {
  24997. // 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
  24998. indices.push(pi, pi + shft, pi + 1);
  24999. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25000. pi += 1;
  25001. if (pi === min) {
  25002. p++;
  25003. if (p === lg.length - 1) {
  25004. shft = idx[0] - idx[p];
  25005. l1 = lg[p] - 1;
  25006. l2 = lg[0] - 1;
  25007. }
  25008. else {
  25009. shft = idx[p + 1] - idx[p];
  25010. l1 = lg[p] - 1;
  25011. l2 = lg[p + 1] - 1;
  25012. }
  25013. pi = idx[p];
  25014. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25015. }
  25016. }
  25017. // normals
  25018. VertexData.ComputeNormals(positions, indices, normals);
  25019. if (closePath) {
  25020. var indexFirst = 0;
  25021. var indexLast = 0;
  25022. for (p = 0; p < pathArray.length; p++) {
  25023. indexFirst = idx[p] * 3;
  25024. if (p + 1 < pathArray.length) {
  25025. indexLast = (idx[p + 1] - 1) * 3;
  25026. }
  25027. else {
  25028. indexLast = normals.length - 3;
  25029. }
  25030. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25031. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25032. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25033. normals[indexLast] = normals[indexFirst];
  25034. normals[indexLast + 1] = normals[indexFirst + 1];
  25035. normals[indexLast + 2] = normals[indexFirst + 2];
  25036. }
  25037. }
  25038. // sides
  25039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25040. // Result
  25041. var vertexData = new VertexData();
  25042. vertexData.indices = indices;
  25043. vertexData.positions = positions;
  25044. vertexData.normals = normals;
  25045. vertexData.uvs = uvs;
  25046. if (closePath) {
  25047. vertexData._idx = idx;
  25048. }
  25049. return vertexData;
  25050. };
  25051. VertexData.CreateBox = function (options) {
  25052. var normalsSource = [
  25053. new BABYLON.Vector3(0, 0, 1),
  25054. new BABYLON.Vector3(0, 0, -1),
  25055. new BABYLON.Vector3(1, 0, 0),
  25056. new BABYLON.Vector3(-1, 0, 0),
  25057. new BABYLON.Vector3(0, 1, 0),
  25058. new BABYLON.Vector3(0, -1, 0)
  25059. ];
  25060. var indices = [];
  25061. var positions = [];
  25062. var normals = [];
  25063. var uvs = [];
  25064. var width = options.width || options.size || 1;
  25065. var height = options.height || options.size || 1;
  25066. var depth = options.depth || options.size || 1;
  25067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25068. var faceUV = options.faceUV || new Array(6);
  25069. var faceColors = options.faceColors;
  25070. var colors = [];
  25071. // default face colors and UV if undefined
  25072. for (var f = 0; f < 6; f++) {
  25073. if (faceUV[f] === undefined) {
  25074. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25075. }
  25076. if (faceColors && faceColors[f] === undefined) {
  25077. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25078. }
  25079. }
  25080. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25081. // Create each face in turn.
  25082. for (var index = 0; index < normalsSource.length; index++) {
  25083. var normal = normalsSource[index];
  25084. // Get two vectors perpendicular to the face normal and to each other.
  25085. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25086. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25087. // Six indices (two triangles) per face.
  25088. var verticesLength = positions.length / 3;
  25089. indices.push(verticesLength);
  25090. indices.push(verticesLength + 1);
  25091. indices.push(verticesLength + 2);
  25092. indices.push(verticesLength);
  25093. indices.push(verticesLength + 2);
  25094. indices.push(verticesLength + 3);
  25095. // Four vertices per face.
  25096. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25097. positions.push(vertex.x, vertex.y, vertex.z);
  25098. normals.push(normal.x, normal.y, normal.z);
  25099. uvs.push(faceUV[index].z, faceUV[index].w);
  25100. if (faceColors) {
  25101. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25102. }
  25103. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25104. positions.push(vertex.x, vertex.y, vertex.z);
  25105. normals.push(normal.x, normal.y, normal.z);
  25106. uvs.push(faceUV[index].x, faceUV[index].w);
  25107. if (faceColors) {
  25108. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25109. }
  25110. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25111. positions.push(vertex.x, vertex.y, vertex.z);
  25112. normals.push(normal.x, normal.y, normal.z);
  25113. uvs.push(faceUV[index].x, faceUV[index].y);
  25114. if (faceColors) {
  25115. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25116. }
  25117. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25118. positions.push(vertex.x, vertex.y, vertex.z);
  25119. normals.push(normal.x, normal.y, normal.z);
  25120. uvs.push(faceUV[index].z, faceUV[index].y);
  25121. if (faceColors) {
  25122. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25123. }
  25124. }
  25125. // sides
  25126. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25127. // Result
  25128. var vertexData = new VertexData();
  25129. vertexData.indices = indices;
  25130. vertexData.positions = positions;
  25131. vertexData.normals = normals;
  25132. vertexData.uvs = uvs;
  25133. if (faceColors) {
  25134. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25135. vertexData.colors = totalColors;
  25136. }
  25137. return vertexData;
  25138. };
  25139. VertexData.CreateSphere = function (options) {
  25140. var segments = options.segments || 32;
  25141. var diameterX = options.diameterX || options.diameter || 1;
  25142. var diameterY = options.diameterY || options.diameter || 1;
  25143. var diameterZ = options.diameterZ || options.diameter || 1;
  25144. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25145. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25146. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25147. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25148. var totalZRotationSteps = 2 + segments;
  25149. var totalYRotationSteps = 2 * totalZRotationSteps;
  25150. var indices = [];
  25151. var positions = [];
  25152. var normals = [];
  25153. var uvs = [];
  25154. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25155. var normalizedZ = zRotationStep / totalZRotationSteps;
  25156. var angleZ = normalizedZ * Math.PI * slice;
  25157. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25158. var normalizedY = yRotationStep / totalYRotationSteps;
  25159. var angleY = normalizedY * Math.PI * 2 * arc;
  25160. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25161. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25162. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25163. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25164. var vertex = complete.multiply(radius);
  25165. var normal = complete.divide(radius).normalize();
  25166. positions.push(vertex.x, vertex.y, vertex.z);
  25167. normals.push(normal.x, normal.y, normal.z);
  25168. uvs.push(normalizedY, normalizedZ);
  25169. }
  25170. if (zRotationStep > 0) {
  25171. var verticesCount = positions.length / 3;
  25172. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25173. indices.push((firstIndex));
  25174. indices.push((firstIndex + 1));
  25175. indices.push(firstIndex + totalYRotationSteps + 1);
  25176. indices.push((firstIndex + totalYRotationSteps + 1));
  25177. indices.push((firstIndex + 1));
  25178. indices.push((firstIndex + totalYRotationSteps + 2));
  25179. }
  25180. }
  25181. }
  25182. // Sides
  25183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25184. // Result
  25185. var vertexData = new VertexData();
  25186. vertexData.indices = indices;
  25187. vertexData.positions = positions;
  25188. vertexData.normals = normals;
  25189. vertexData.uvs = uvs;
  25190. return vertexData;
  25191. };
  25192. // Cylinder and cone
  25193. VertexData.CreateCylinder = function (options) {
  25194. var height = options.height || 2;
  25195. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25196. var diameterBottom = options.diameterBottom || options.diameter || 1;
  25197. var tessellation = options.tessellation || 24;
  25198. var subdivisions = options.subdivisions || 1;
  25199. var hasRings = options.hasRings;
  25200. var enclose = options.enclose;
  25201. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25203. var faceUV = options.faceUV || new Array(3);
  25204. var faceColors = options.faceColors;
  25205. // default face colors and UV if undefined
  25206. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25207. var ringNb = (hasRings) ? subdivisions : 1;
  25208. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25209. var f;
  25210. for (f = 0; f < surfaceNb; f++) {
  25211. if (faceColors && faceColors[f] === undefined) {
  25212. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25213. }
  25214. }
  25215. for (f = 0; f < surfaceNb; f++) {
  25216. if (faceUV && faceUV[f] === undefined) {
  25217. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25218. }
  25219. }
  25220. var indices = [];
  25221. var positions = [];
  25222. var normals = [];
  25223. var uvs = [];
  25224. var colors = [];
  25225. var angle_step = Math.PI * 2 * arc / tessellation;
  25226. var angle;
  25227. var h;
  25228. var radius;
  25229. var tan = (diameterBottom - diameterTop) / 2 / height;
  25230. var ringVertex = BABYLON.Vector3.Zero();
  25231. var ringNormal = BABYLON.Vector3.Zero();
  25232. var ringFirstVertex = BABYLON.Vector3.Zero();
  25233. var ringFirstNormal = BABYLON.Vector3.Zero();
  25234. var quadNormal = BABYLON.Vector3.Zero();
  25235. var Y = BABYLON.Axis.Y;
  25236. // positions, normals, uvs
  25237. var i;
  25238. var j;
  25239. var r;
  25240. var ringIdx = 1;
  25241. var s = 1; // surface index
  25242. var cs = 0;
  25243. var v = 0;
  25244. for (i = 0; i <= subdivisions; i++) {
  25245. h = i / subdivisions;
  25246. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25247. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25248. for (r = 0; r < ringIdx; r++) {
  25249. if (hasRings) {
  25250. s += r;
  25251. }
  25252. if (enclose) {
  25253. s += 2 * r;
  25254. }
  25255. for (j = 0; j <= tessellation; j++) {
  25256. angle = j * angle_step;
  25257. // position
  25258. ringVertex.x = Math.cos(-angle) * radius;
  25259. ringVertex.y = -height / 2 + h * height;
  25260. ringVertex.z = Math.sin(-angle) * radius;
  25261. // normal
  25262. if (diameterTop === 0 && i === subdivisions) {
  25263. // if no top cap, reuse former normals
  25264. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25265. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25266. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25267. }
  25268. else {
  25269. ringNormal.x = ringVertex.x;
  25270. ringNormal.z = ringVertex.z;
  25271. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25272. ringNormal.normalize();
  25273. }
  25274. // keep first ring vertex values for enclose
  25275. if (j === 0) {
  25276. ringFirstVertex.copyFrom(ringVertex);
  25277. ringFirstNormal.copyFrom(ringNormal);
  25278. }
  25279. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25280. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25281. if (hasRings) {
  25282. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25283. }
  25284. else {
  25285. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25286. }
  25287. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25288. if (faceColors) {
  25289. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25290. }
  25291. }
  25292. // if enclose, add four vertices and their dedicated normals
  25293. if (arc !== 1 && enclose) {
  25294. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25295. positions.push(0, ringVertex.y, 0);
  25296. positions.push(0, ringVertex.y, 0);
  25297. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25298. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25299. quadNormal.normalize();
  25300. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25301. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25302. quadNormal.normalize();
  25303. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25304. if (hasRings) {
  25305. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25306. }
  25307. else {
  25308. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25309. }
  25310. uvs.push(faceUV[s + 1].x, v);
  25311. uvs.push(faceUV[s + 1].z, v);
  25312. if (hasRings) {
  25313. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25314. }
  25315. else {
  25316. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25317. }
  25318. uvs.push(faceUV[s + 2].x, v);
  25319. uvs.push(faceUV[s + 2].z, v);
  25320. if (faceColors) {
  25321. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25322. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25323. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25324. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25325. }
  25326. }
  25327. if (cs !== s) {
  25328. cs = s;
  25329. }
  25330. }
  25331. }
  25332. // indices
  25333. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25334. var s;
  25335. i = 0;
  25336. for (s = 0; s < subdivisions; s++) {
  25337. for (j = 0; j < tessellation; j++) {
  25338. var i0 = i * (e + 1) + j;
  25339. var i1 = (i + 1) * (e + 1) + j;
  25340. var i2 = i * (e + 1) + (j + 1);
  25341. var i3 = (i + 1) * (e + 1) + (j + 1);
  25342. indices.push(i0, i1, i2);
  25343. indices.push(i3, i2, i1);
  25344. }
  25345. if (arc !== 1 && enclose) {
  25346. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25347. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25348. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25349. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25350. }
  25351. i = (hasRings) ? (i + 2) : (i + 1);
  25352. }
  25353. // Caps
  25354. var createCylinderCap = function (isTop) {
  25355. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25356. if (radius === 0) {
  25357. return;
  25358. }
  25359. // Cap positions, normals & uvs
  25360. var angle;
  25361. var circleVector;
  25362. var i;
  25363. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25364. var c;
  25365. if (faceColors) {
  25366. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25367. }
  25368. // cap center
  25369. var vbase = positions.length / 3;
  25370. var offset = isTop ? height / 2 : -height / 2;
  25371. var center = new BABYLON.Vector3(0, offset, 0);
  25372. positions.push(center.x, center.y, center.z);
  25373. normals.push(0, isTop ? 1 : -1, 0);
  25374. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25375. if (faceColors) {
  25376. colors.push(c.r, c.g, c.b, c.a);
  25377. }
  25378. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25379. for (i = 0; i <= tessellation; i++) {
  25380. angle = Math.PI * 2 * i * arc / tessellation;
  25381. var cos = Math.cos(-angle);
  25382. var sin = Math.sin(-angle);
  25383. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25384. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25385. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25386. normals.push(0, isTop ? 1 : -1, 0);
  25387. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25388. if (faceColors) {
  25389. colors.push(c.r, c.g, c.b, c.a);
  25390. }
  25391. }
  25392. // Cap indices
  25393. for (i = 0; i < tessellation; i++) {
  25394. if (!isTop) {
  25395. indices.push(vbase);
  25396. indices.push(vbase + (i + 1));
  25397. indices.push(vbase + (i + 2));
  25398. }
  25399. else {
  25400. indices.push(vbase);
  25401. indices.push(vbase + (i + 2));
  25402. indices.push(vbase + (i + 1));
  25403. }
  25404. }
  25405. };
  25406. // add caps to geometry
  25407. createCylinderCap(false);
  25408. createCylinderCap(true);
  25409. // Sides
  25410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25411. var vertexData = new VertexData();
  25412. vertexData.indices = indices;
  25413. vertexData.positions = positions;
  25414. vertexData.normals = normals;
  25415. vertexData.uvs = uvs;
  25416. if (faceColors) {
  25417. vertexData.colors = colors;
  25418. }
  25419. return vertexData;
  25420. };
  25421. VertexData.CreateTorus = function (options) {
  25422. var indices = [];
  25423. var positions = [];
  25424. var normals = [];
  25425. var uvs = [];
  25426. var diameter = options.diameter || 1;
  25427. var thickness = options.thickness || 0.5;
  25428. var tessellation = options.tessellation || 16;
  25429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25430. var stride = tessellation + 1;
  25431. for (var i = 0; i <= tessellation; i++) {
  25432. var u = i / tessellation;
  25433. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25434. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25435. for (var j = 0; j <= tessellation; j++) {
  25436. var v = 1 - j / tessellation;
  25437. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25438. var dx = Math.cos(innerAngle);
  25439. var dy = Math.sin(innerAngle);
  25440. // Create a vertex.
  25441. var normal = new BABYLON.Vector3(dx, dy, 0);
  25442. var position = normal.scale(thickness / 2);
  25443. var textureCoordinate = new BABYLON.Vector2(u, v);
  25444. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25445. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25446. positions.push(position.x, position.y, position.z);
  25447. normals.push(normal.x, normal.y, normal.z);
  25448. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25449. // And create indices for two triangles.
  25450. var nextI = (i + 1) % stride;
  25451. var nextJ = (j + 1) % stride;
  25452. indices.push(i * stride + j);
  25453. indices.push(i * stride + nextJ);
  25454. indices.push(nextI * stride + j);
  25455. indices.push(i * stride + nextJ);
  25456. indices.push(nextI * stride + nextJ);
  25457. indices.push(nextI * stride + j);
  25458. }
  25459. }
  25460. // Sides
  25461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25462. // Result
  25463. var vertexData = new VertexData();
  25464. vertexData.indices = indices;
  25465. vertexData.positions = positions;
  25466. vertexData.normals = normals;
  25467. vertexData.uvs = uvs;
  25468. return vertexData;
  25469. };
  25470. VertexData.CreateLineSystem = function (options) {
  25471. var indices = [];
  25472. var positions = [];
  25473. var lines = options.lines;
  25474. var idx = 0;
  25475. for (var l = 0; l < lines.length; l++) {
  25476. var points = lines[l];
  25477. for (var index = 0; index < points.length; index++) {
  25478. positions.push(points[index].x, points[index].y, points[index].z);
  25479. if (index > 0) {
  25480. indices.push(idx - 1);
  25481. indices.push(idx);
  25482. }
  25483. idx++;
  25484. }
  25485. }
  25486. var vertexData = new VertexData();
  25487. vertexData.indices = indices;
  25488. vertexData.positions = positions;
  25489. return vertexData;
  25490. };
  25491. VertexData.CreateDashedLines = function (options) {
  25492. var dashSize = options.dashSize || 3;
  25493. var gapSize = options.gapSize || 1;
  25494. var dashNb = options.dashNb || 200;
  25495. var points = options.points;
  25496. var positions = new Array();
  25497. var indices = new Array();
  25498. var curvect = BABYLON.Vector3.Zero();
  25499. var lg = 0;
  25500. var nb = 0;
  25501. var shft = 0;
  25502. var dashshft = 0;
  25503. var curshft = 0;
  25504. var idx = 0;
  25505. var i = 0;
  25506. for (i = 0; i < points.length - 1; i++) {
  25507. points[i + 1].subtractToRef(points[i], curvect);
  25508. lg += curvect.length();
  25509. }
  25510. shft = lg / dashNb;
  25511. dashshft = dashSize * shft / (dashSize + gapSize);
  25512. for (i = 0; i < points.length - 1; i++) {
  25513. points[i + 1].subtractToRef(points[i], curvect);
  25514. nb = Math.floor(curvect.length() / shft);
  25515. curvect.normalize();
  25516. for (var j = 0; j < nb; j++) {
  25517. curshft = shft * j;
  25518. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25519. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25520. indices.push(idx, idx + 1);
  25521. idx += 2;
  25522. }
  25523. }
  25524. // Result
  25525. var vertexData = new VertexData();
  25526. vertexData.positions = positions;
  25527. vertexData.indices = indices;
  25528. return vertexData;
  25529. };
  25530. VertexData.CreateGround = function (options) {
  25531. var indices = [];
  25532. var positions = [];
  25533. var normals = [];
  25534. var uvs = [];
  25535. var row, col;
  25536. var width = options.width || 1;
  25537. var height = options.height || 1;
  25538. var subdivisions = options.subdivisions || 1;
  25539. for (row = 0; row <= subdivisions; row++) {
  25540. for (col = 0; col <= subdivisions; col++) {
  25541. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25542. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25543. positions.push(position.x, position.y, position.z);
  25544. normals.push(normal.x, normal.y, normal.z);
  25545. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25546. }
  25547. }
  25548. for (row = 0; row < subdivisions; row++) {
  25549. for (col = 0; col < subdivisions; col++) {
  25550. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25551. indices.push(col + 1 + row * (subdivisions + 1));
  25552. indices.push(col + row * (subdivisions + 1));
  25553. indices.push(col + (row + 1) * (subdivisions + 1));
  25554. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25555. indices.push(col + row * (subdivisions + 1));
  25556. }
  25557. }
  25558. // Result
  25559. var vertexData = new VertexData();
  25560. vertexData.indices = indices;
  25561. vertexData.positions = positions;
  25562. vertexData.normals = normals;
  25563. vertexData.uvs = uvs;
  25564. return vertexData;
  25565. };
  25566. VertexData.CreateTiledGround = function (options) {
  25567. var xmin = options.xmin;
  25568. var zmin = options.zmin;
  25569. var xmax = options.xmax;
  25570. var zmax = options.zmax;
  25571. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25572. var precision = options.precision || { w: 1, h: 1 };
  25573. var indices = [];
  25574. var positions = [];
  25575. var normals = [];
  25576. var uvs = [];
  25577. var row, col, tileRow, tileCol;
  25578. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25579. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25580. precision.w = (precision.w < 1) ? 1 : precision.w;
  25581. precision.h = (precision.h < 1) ? 1 : precision.h;
  25582. var tileSize = {
  25583. 'w': (xmax - xmin) / subdivisions.w,
  25584. 'h': (zmax - zmin) / subdivisions.h
  25585. };
  25586. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25587. // Indices
  25588. var base = positions.length / 3;
  25589. var rowLength = precision.w + 1;
  25590. for (row = 0; row < precision.h; row++) {
  25591. for (col = 0; col < precision.w; col++) {
  25592. var square = [
  25593. base + col + row * rowLength,
  25594. base + (col + 1) + row * rowLength,
  25595. base + (col + 1) + (row + 1) * rowLength,
  25596. base + col + (row + 1) * rowLength
  25597. ];
  25598. indices.push(square[1]);
  25599. indices.push(square[2]);
  25600. indices.push(square[3]);
  25601. indices.push(square[0]);
  25602. indices.push(square[1]);
  25603. indices.push(square[3]);
  25604. }
  25605. }
  25606. // Position, normals and uvs
  25607. var position = BABYLON.Vector3.Zero();
  25608. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25609. for (row = 0; row <= precision.h; row++) {
  25610. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25611. for (col = 0; col <= precision.w; col++) {
  25612. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25613. position.y = 0;
  25614. positions.push(position.x, position.y, position.z);
  25615. normals.push(normal.x, normal.y, normal.z);
  25616. uvs.push(col / precision.w, row / precision.h);
  25617. }
  25618. }
  25619. }
  25620. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25621. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25622. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25623. }
  25624. }
  25625. // Result
  25626. var vertexData = new VertexData();
  25627. vertexData.indices = indices;
  25628. vertexData.positions = positions;
  25629. vertexData.normals = normals;
  25630. vertexData.uvs = uvs;
  25631. return vertexData;
  25632. };
  25633. VertexData.CreateGroundFromHeightMap = function (options) {
  25634. var indices = [];
  25635. var positions = [];
  25636. var normals = [];
  25637. var uvs = [];
  25638. var row, col;
  25639. // Vertices
  25640. for (row = 0; row <= options.subdivisions; row++) {
  25641. for (col = 0; col <= options.subdivisions; col++) {
  25642. 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));
  25643. // Compute height
  25644. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25645. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25646. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25647. var r = options.buffer[pos] / 255.0;
  25648. var g = options.buffer[pos + 1] / 255.0;
  25649. var b = options.buffer[pos + 2] / 255.0;
  25650. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25651. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25652. // Add vertex
  25653. positions.push(position.x, position.y, position.z);
  25654. normals.push(0, 0, 0);
  25655. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25656. }
  25657. }
  25658. // Indices
  25659. for (row = 0; row < options.subdivisions; row++) {
  25660. for (col = 0; col < options.subdivisions; col++) {
  25661. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25662. indices.push(col + 1 + row * (options.subdivisions + 1));
  25663. indices.push(col + row * (options.subdivisions + 1));
  25664. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25665. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25666. indices.push(col + row * (options.subdivisions + 1));
  25667. }
  25668. }
  25669. // Normals
  25670. VertexData.ComputeNormals(positions, indices, normals);
  25671. // Result
  25672. var vertexData = new VertexData();
  25673. vertexData.indices = indices;
  25674. vertexData.positions = positions;
  25675. vertexData.normals = normals;
  25676. vertexData.uvs = uvs;
  25677. return vertexData;
  25678. };
  25679. VertexData.CreatePlane = function (options) {
  25680. var indices = [];
  25681. var positions = [];
  25682. var normals = [];
  25683. var uvs = [];
  25684. var width = options.width || options.size || 1;
  25685. var height = options.height || options.size || 1;
  25686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25687. // Vertices
  25688. var halfWidth = width / 2.0;
  25689. var halfHeight = height / 2.0;
  25690. positions.push(-halfWidth, -halfHeight, 0);
  25691. normals.push(0, 0, -1.0);
  25692. uvs.push(0.0, 0.0);
  25693. positions.push(halfWidth, -halfHeight, 0);
  25694. normals.push(0, 0, -1.0);
  25695. uvs.push(1.0, 0.0);
  25696. positions.push(halfWidth, halfHeight, 0);
  25697. normals.push(0, 0, -1.0);
  25698. uvs.push(1.0, 1.0);
  25699. positions.push(-halfWidth, halfHeight, 0);
  25700. normals.push(0, 0, -1.0);
  25701. uvs.push(0.0, 1.0);
  25702. // Indices
  25703. indices.push(0);
  25704. indices.push(1);
  25705. indices.push(2);
  25706. indices.push(0);
  25707. indices.push(2);
  25708. indices.push(3);
  25709. // Sides
  25710. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25711. // Result
  25712. var vertexData = new VertexData();
  25713. vertexData.indices = indices;
  25714. vertexData.positions = positions;
  25715. vertexData.normals = normals;
  25716. vertexData.uvs = uvs;
  25717. return vertexData;
  25718. };
  25719. VertexData.CreateDisc = function (options) {
  25720. var positions = [];
  25721. var indices = [];
  25722. var normals = [];
  25723. var uvs = [];
  25724. var radius = options.radius || 0.5;
  25725. var tessellation = options.tessellation || 64;
  25726. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25727. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25728. // positions and uvs
  25729. positions.push(0, 0, 0); // disc center first
  25730. uvs.push(0.5, 0.5);
  25731. var theta = Math.PI * 2 * arc;
  25732. var step = theta / tessellation;
  25733. for (var a = 0; a < theta; a += step) {
  25734. var x = Math.cos(a);
  25735. var y = Math.sin(a);
  25736. var u = (x + 1) / 2;
  25737. var v = (1 - y) / 2;
  25738. positions.push(radius * x, radius * y, 0);
  25739. uvs.push(u, v);
  25740. }
  25741. if (arc === 1) {
  25742. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25743. uvs.push(uvs[2], uvs[3]);
  25744. }
  25745. //indices
  25746. var vertexNb = positions.length / 3;
  25747. for (var i = 1; i < vertexNb - 1; i++) {
  25748. indices.push(i + 1, 0, i);
  25749. }
  25750. // result
  25751. VertexData.ComputeNormals(positions, indices, normals);
  25752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25753. var vertexData = new VertexData();
  25754. vertexData.indices = indices;
  25755. vertexData.positions = positions;
  25756. vertexData.normals = normals;
  25757. vertexData.uvs = uvs;
  25758. return vertexData;
  25759. };
  25760. VertexData.CreateIcoSphere = function (options) {
  25761. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25762. var radius = options.radius || 1;
  25763. var flat = (options.flat === undefined) ? true : options.flat;
  25764. var subdivisions = options.subdivisions || 4;
  25765. var radiusX = options.radiusX || radius;
  25766. var radiusY = options.radiusY || radius;
  25767. var radiusZ = options.radiusZ || radius;
  25768. var t = (1 + Math.sqrt(5)) / 2;
  25769. // 12 vertex x,y,z
  25770. var ico_vertices = [
  25771. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25772. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25773. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25774. ];
  25775. // index of 3 vertex makes a face of icopshere
  25776. var ico_indices = [
  25777. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25778. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25779. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25780. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25781. ];
  25782. // vertex for uv have aliased position, not for UV
  25783. var vertices_unalias_id = [
  25784. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25785. // vertex alias
  25786. 0,
  25787. 2,
  25788. 3,
  25789. 3,
  25790. 3,
  25791. 4,
  25792. 7,
  25793. 8,
  25794. 9,
  25795. 9,
  25796. 10,
  25797. 11 // 23: B + 12
  25798. ];
  25799. // uv as integer step (not pixels !)
  25800. var ico_vertexuv = [
  25801. 5, 1, 3, 1, 6, 4, 0, 0,
  25802. 5, 3, 4, 2, 2, 2, 4, 0,
  25803. 2, 0, 1, 1, 6, 0, 6, 2,
  25804. // vertex alias (for same vertex on different faces)
  25805. 0, 4,
  25806. 3, 3,
  25807. 4, 4,
  25808. 3, 1,
  25809. 4, 2,
  25810. 4, 4,
  25811. 0, 2,
  25812. 1, 1,
  25813. 2, 2,
  25814. 3, 3,
  25815. 1, 3,
  25816. 2, 4 // 23: B + 12
  25817. ];
  25818. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25819. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25820. // First island of uv mapping
  25821. // v = 4h 3+ 2
  25822. // v = 3h 9+ 4
  25823. // v = 2h 9+ 5 B
  25824. // v = 1h 9 1 0
  25825. // v = 0h 3 8 7 A
  25826. // u = 0 1 2 3 4 5 6 *a
  25827. // Second island of uv mapping
  25828. // v = 4h 0+ B+ 4+
  25829. // v = 3h A+ 2+
  25830. // v = 2h 7+ 6 3+
  25831. // v = 1h 8+ 3+
  25832. // v = 0h
  25833. // u = 0 1 2 3 4 5 6 *a
  25834. // Face layout on texture UV mapping
  25835. // ============
  25836. // \ 4 /\ 16 / ======
  25837. // \ / \ / /\ 11 /
  25838. // \/ 7 \/ / \ /
  25839. // ======= / 10 \/
  25840. // /\ 17 /\ =======
  25841. // / \ / \ \ 15 /\
  25842. // / 8 \/ 12 \ \ / \
  25843. // ============ \/ 6 \
  25844. // \ 18 /\ ============
  25845. // \ / \ \ 5 /\ 0 /
  25846. // \/ 13 \ \ / \ /
  25847. // ======= \/ 1 \/
  25848. // =============
  25849. // /\ 19 /\ 2 /\
  25850. // / \ / \ / \
  25851. // / 14 \/ 9 \/ 3 \
  25852. // ===================
  25853. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25854. var ustep = 138 / 1024;
  25855. var vstep = 239 / 1024;
  25856. var uoffset = 60 / 1024;
  25857. var voffset = 26 / 1024;
  25858. // Second island should have margin, not to touch the first island
  25859. // avoid any borderline artefact in pixel rounding
  25860. var island_u_offset = -40 / 1024;
  25861. var island_v_offset = +20 / 1024;
  25862. // face is either island 0 or 1 :
  25863. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25864. var island = [
  25865. 0, 0, 0, 0, 1,
  25866. 0, 0, 1, 1, 0,
  25867. 0, 0, 1, 1, 0,
  25868. 0, 1, 1, 1, 0 // 15 - 19
  25869. ];
  25870. var indices = [];
  25871. var positions = [];
  25872. var normals = [];
  25873. var uvs = [];
  25874. var current_indice = 0;
  25875. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25876. var face_vertex_pos = new Array(3);
  25877. var face_vertex_uv = new Array(3);
  25878. var v012;
  25879. for (v012 = 0; v012 < 3; v012++) {
  25880. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25881. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25882. }
  25883. // create all with normals
  25884. for (var face = 0; face < 20; face++) {
  25885. // 3 vertex per face
  25886. for (v012 = 0; v012 < 3; v012++) {
  25887. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25888. var v_id = ico_indices[3 * face + v012];
  25889. // vertex have 3D position (x,y,z)
  25890. 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]);
  25891. // Normalize to get normal, then scale to radius
  25892. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25893. // uv Coordinates from vertex ID
  25894. 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);
  25895. }
  25896. // Subdivide the face (interpolate pos, norm, uv)
  25897. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25898. // - norm is linear interpolation of vertex corner normal
  25899. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25900. // - uv is linear interpolation
  25901. //
  25902. // Topology is as below for sub-divide by 2
  25903. // vertex shown as v0,v1,v2
  25904. // interp index is i1 to progress in range [v0,v1[
  25905. // interp index is i2 to progress in range [v0,v2[
  25906. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25907. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25908. //
  25909. //
  25910. // i2 v2
  25911. // ^ ^
  25912. // / / \
  25913. // / / \
  25914. // / / \
  25915. // / / (0,1) \
  25916. // / #---------\
  25917. // / / \ (0,0)'/ \
  25918. // / / \ / \
  25919. // / / \ / \
  25920. // / / (0,0) \ / (1,0) \
  25921. // / #---------#---------\
  25922. // v0 v1
  25923. //
  25924. // --------------------> i1
  25925. //
  25926. // interp of (i1,i2):
  25927. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25928. // along i1 : lerp(x0,x1, i1/(S-i2))
  25929. //
  25930. // centroid of triangle is needed to get help normal computation
  25931. // (c1,c2) are used for centroid location
  25932. var interp_vertex = function (i1, i2, c1, c2) {
  25933. // vertex is interpolated from
  25934. // - face_vertex_pos[0..2]
  25935. // - face_vertex_uv[0..2]
  25936. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25937. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25938. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25939. pos_interp.normalize();
  25940. var vertex_normal;
  25941. if (flat) {
  25942. // in flat mode, recalculate normal as face centroid normal
  25943. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25944. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25945. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25946. }
  25947. else {
  25948. // in smooth mode, recalculate normal from each single vertex position
  25949. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25950. }
  25951. // Vertex normal need correction due to X,Y,Z radius scaling
  25952. vertex_normal.x /= radiusX;
  25953. vertex_normal.y /= radiusY;
  25954. vertex_normal.z /= radiusZ;
  25955. vertex_normal.normalize();
  25956. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25957. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25958. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25959. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25960. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25961. uvs.push(uv_interp.x, uv_interp.y);
  25962. // push each vertex has member of a face
  25963. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25964. indices.push(current_indice);
  25965. current_indice++;
  25966. };
  25967. for (var i2 = 0; i2 < subdivisions; i2++) {
  25968. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25969. // face : (i1,i2) for /\ :
  25970. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25971. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25972. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25973. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25974. if (i1 + i2 + 1 < subdivisions) {
  25975. // face : (i1,i2)' for \/ :
  25976. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25977. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25978. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25979. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25980. }
  25981. }
  25982. }
  25983. }
  25984. // Sides
  25985. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25986. // Result
  25987. var vertexData = new VertexData();
  25988. vertexData.indices = indices;
  25989. vertexData.positions = positions;
  25990. vertexData.normals = normals;
  25991. vertexData.uvs = uvs;
  25992. return vertexData;
  25993. };
  25994. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25995. VertexData.CreatePolyhedron = function (options) {
  25996. // provided polyhedron types :
  25997. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25998. // 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)
  25999. var polyhedra = [];
  26000. 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]] };
  26001. 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]] };
  26002. polyhedra[2] = {
  26003. 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]],
  26004. 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]]
  26005. };
  26006. polyhedra[3] = {
  26007. 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]],
  26008. 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]]
  26009. };
  26010. polyhedra[4] = {
  26011. 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]],
  26012. 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]]
  26013. };
  26014. 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]] };
  26015. 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]] };
  26016. 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]] };
  26017. 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]] };
  26018. 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]] };
  26019. 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]] };
  26020. 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]] };
  26021. 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]] };
  26022. 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]] };
  26023. polyhedra[14] = {
  26024. 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]],
  26025. 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]]
  26026. };
  26027. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26028. var size = options.size;
  26029. var sizeX = options.sizeX || size || 1;
  26030. var sizeY = options.sizeY || size || 1;
  26031. var sizeZ = options.sizeZ || size || 1;
  26032. var data = options.custom || polyhedra[type];
  26033. var nbfaces = data.face.length;
  26034. var faceUV = options.faceUV || new Array(nbfaces);
  26035. var faceColors = options.faceColors;
  26036. var flat = (options.flat === undefined) ? true : options.flat;
  26037. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26038. var positions = [];
  26039. var indices = [];
  26040. var normals = [];
  26041. var uvs = [];
  26042. var colors = [];
  26043. var index = 0;
  26044. var faceIdx = 0; // face cursor in the array "indexes"
  26045. var indexes = [];
  26046. var i = 0;
  26047. var f = 0;
  26048. var u, v, ang, x, y, tmp;
  26049. // default face colors and UV if undefined
  26050. if (flat) {
  26051. for (f = 0; f < nbfaces; f++) {
  26052. if (faceColors && faceColors[f] === undefined) {
  26053. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26054. }
  26055. if (faceUV && faceUV[f] === undefined) {
  26056. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26057. }
  26058. }
  26059. }
  26060. if (!flat) {
  26061. for (i = 0; i < data.vertex.length; i++) {
  26062. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26063. uvs.push(0, 0);
  26064. }
  26065. for (f = 0; f < nbfaces; f++) {
  26066. for (i = 0; i < data.face[f].length - 2; i++) {
  26067. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26068. }
  26069. }
  26070. }
  26071. else {
  26072. for (f = 0; f < nbfaces; f++) {
  26073. var fl = data.face[f].length; // number of vertices of the current face
  26074. ang = 2 * Math.PI / fl;
  26075. x = 0.5 * Math.tan(ang / 2);
  26076. y = 0.5;
  26077. // positions, uvs, colors
  26078. for (i = 0; i < fl; i++) {
  26079. // positions
  26080. 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);
  26081. indexes.push(index);
  26082. index++;
  26083. // uvs
  26084. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26085. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26086. uvs.push(u, v);
  26087. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26088. y = x * Math.sin(ang) + y * Math.cos(ang);
  26089. x = tmp;
  26090. // colors
  26091. if (faceColors) {
  26092. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26093. }
  26094. }
  26095. // indices from indexes
  26096. for (i = 0; i < fl - 2; i++) {
  26097. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26098. }
  26099. faceIdx += fl;
  26100. }
  26101. }
  26102. VertexData.ComputeNormals(positions, indices, normals);
  26103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26104. var vertexData = new VertexData();
  26105. vertexData.positions = positions;
  26106. vertexData.indices = indices;
  26107. vertexData.normals = normals;
  26108. vertexData.uvs = uvs;
  26109. if (faceColors && flat) {
  26110. vertexData.colors = colors;
  26111. }
  26112. return vertexData;
  26113. };
  26114. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26115. VertexData.CreateTorusKnot = function (options) {
  26116. var indices = [];
  26117. var positions = [];
  26118. var normals = [];
  26119. var uvs = [];
  26120. var radius = options.radius || 2;
  26121. var tube = options.tube || 0.5;
  26122. var radialSegments = options.radialSegments || 32;
  26123. var tubularSegments = options.tubularSegments || 32;
  26124. var p = options.p || 2;
  26125. var q = options.q || 3;
  26126. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26127. // Helper
  26128. var getPos = function (angle) {
  26129. var cu = Math.cos(angle);
  26130. var su = Math.sin(angle);
  26131. var quOverP = q / p * angle;
  26132. var cs = Math.cos(quOverP);
  26133. var tx = radius * (2 + cs) * 0.5 * cu;
  26134. var ty = radius * (2 + cs) * su * 0.5;
  26135. var tz = radius * Math.sin(quOverP) * 0.5;
  26136. return new BABYLON.Vector3(tx, ty, tz);
  26137. };
  26138. // Vertices
  26139. var i;
  26140. var j;
  26141. for (i = 0; i <= radialSegments; i++) {
  26142. var modI = i % radialSegments;
  26143. var u = modI / radialSegments * 2 * p * Math.PI;
  26144. var p1 = getPos(u);
  26145. var p2 = getPos(u + 0.01);
  26146. var tang = p2.subtract(p1);
  26147. var n = p2.add(p1);
  26148. var bitan = BABYLON.Vector3.Cross(tang, n);
  26149. n = BABYLON.Vector3.Cross(bitan, tang);
  26150. bitan.normalize();
  26151. n.normalize();
  26152. for (j = 0; j < tubularSegments; j++) {
  26153. var modJ = j % tubularSegments;
  26154. var v = modJ / tubularSegments * 2 * Math.PI;
  26155. var cx = -tube * Math.cos(v);
  26156. var cy = tube * Math.sin(v);
  26157. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26158. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26159. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26160. uvs.push(i / radialSegments);
  26161. uvs.push(j / tubularSegments);
  26162. }
  26163. }
  26164. for (i = 0; i < radialSegments; i++) {
  26165. for (j = 0; j < tubularSegments; j++) {
  26166. var jNext = (j + 1) % tubularSegments;
  26167. var a = i * tubularSegments + j;
  26168. var b = (i + 1) * tubularSegments + j;
  26169. var c = (i + 1) * tubularSegments + jNext;
  26170. var d = i * tubularSegments + jNext;
  26171. indices.push(d);
  26172. indices.push(b);
  26173. indices.push(a);
  26174. indices.push(d);
  26175. indices.push(c);
  26176. indices.push(b);
  26177. }
  26178. }
  26179. // Normals
  26180. VertexData.ComputeNormals(positions, indices, normals);
  26181. // Sides
  26182. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26183. // Result
  26184. var vertexData = new VertexData();
  26185. vertexData.indices = indices;
  26186. vertexData.positions = positions;
  26187. vertexData.normals = normals;
  26188. vertexData.uvs = uvs;
  26189. return vertexData;
  26190. };
  26191. // Tools
  26192. /**
  26193. * @param {any} - positions (number[] or Float32Array)
  26194. * @param {any} - indices (number[] or Uint16Array)
  26195. * @param {any} - normals (number[] or Float32Array)
  26196. */
  26197. VertexData.ComputeNormals = function (positions, indices, normals) {
  26198. var index = 0;
  26199. var p1p2x = 0.0;
  26200. var p1p2y = 0.0;
  26201. var p1p2z = 0.0;
  26202. var p3p2x = 0.0;
  26203. var p3p2y = 0.0;
  26204. var p3p2z = 0.0;
  26205. var faceNormalx = 0.0;
  26206. var faceNormaly = 0.0;
  26207. var faceNormalz = 0.0;
  26208. var length = 0.0;
  26209. var i1 = 0;
  26210. var i2 = 0;
  26211. var i3 = 0;
  26212. for (index = 0; index < positions.length; index++) {
  26213. normals[index] = 0.0;
  26214. }
  26215. // indice triplet = 1 face
  26216. var nbFaces = indices.length / 3;
  26217. for (index = 0; index < nbFaces; index++) {
  26218. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26219. i2 = indices[index * 3 + 1];
  26220. i3 = indices[index * 3 + 2];
  26221. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26222. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26223. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26224. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26225. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26226. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26227. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26228. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26229. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26230. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26231. length = (length === 0) ? 1.0 : length;
  26232. faceNormalx /= length; // normalize this normal
  26233. faceNormaly /= length;
  26234. faceNormalz /= length;
  26235. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26236. normals[i1 * 3 + 1] += faceNormaly;
  26237. normals[i1 * 3 + 2] += faceNormalz;
  26238. normals[i2 * 3] += faceNormalx;
  26239. normals[i2 * 3 + 1] += faceNormaly;
  26240. normals[i2 * 3 + 2] += faceNormalz;
  26241. normals[i3 * 3] += faceNormalx;
  26242. normals[i3 * 3 + 1] += faceNormaly;
  26243. normals[i3 * 3 + 2] += faceNormalz;
  26244. }
  26245. // last normalization of each normal
  26246. for (index = 0; index < normals.length / 3; index++) {
  26247. faceNormalx = normals[index * 3];
  26248. faceNormaly = normals[index * 3 + 1];
  26249. faceNormalz = normals[index * 3 + 2];
  26250. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26251. length = (length === 0) ? 1.0 : length;
  26252. faceNormalx /= length;
  26253. faceNormaly /= length;
  26254. faceNormalz /= length;
  26255. normals[index * 3] = faceNormalx;
  26256. normals[index * 3 + 1] = faceNormaly;
  26257. normals[index * 3 + 2] = faceNormalz;
  26258. }
  26259. };
  26260. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26261. var li = indices.length;
  26262. var ln = normals.length;
  26263. var i;
  26264. var n;
  26265. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26266. switch (sideOrientation) {
  26267. case BABYLON.Mesh.FRONTSIDE:
  26268. // nothing changed
  26269. break;
  26270. case BABYLON.Mesh.BACKSIDE:
  26271. var tmp;
  26272. // indices
  26273. for (i = 0; i < li; i += 3) {
  26274. tmp = indices[i];
  26275. indices[i] = indices[i + 2];
  26276. indices[i + 2] = tmp;
  26277. }
  26278. // normals
  26279. for (n = 0; n < ln; n++) {
  26280. normals[n] = -normals[n];
  26281. }
  26282. break;
  26283. case BABYLON.Mesh.DOUBLESIDE:
  26284. // positions
  26285. var lp = positions.length;
  26286. var l = lp / 3;
  26287. for (var p = 0; p < lp; p++) {
  26288. positions[lp + p] = positions[p];
  26289. }
  26290. // indices
  26291. for (i = 0; i < li; i += 3) {
  26292. indices[i + li] = indices[i + 2] + l;
  26293. indices[i + 1 + li] = indices[i + 1] + l;
  26294. indices[i + 2 + li] = indices[i] + l;
  26295. }
  26296. // normals
  26297. for (n = 0; n < ln; n++) {
  26298. normals[ln + n] = -normals[n];
  26299. }
  26300. // uvs
  26301. var lu = uvs.length;
  26302. for (var u = 0; u < lu; u++) {
  26303. uvs[u + lu] = uvs[u];
  26304. }
  26305. break;
  26306. }
  26307. };
  26308. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26309. var vertexData = new VertexData();
  26310. // positions
  26311. var positions = parsedVertexData.positions;
  26312. if (positions) {
  26313. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26314. }
  26315. // normals
  26316. var normals = parsedVertexData.normals;
  26317. if (normals) {
  26318. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26319. }
  26320. // uvs
  26321. var uvs = parsedVertexData.uvs;
  26322. if (uvs) {
  26323. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26324. }
  26325. // uv2s
  26326. var uv2s = parsedVertexData.uv2s;
  26327. if (uv2s) {
  26328. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26329. }
  26330. // uv3s
  26331. var uv3s = parsedVertexData.uv3s;
  26332. if (uv3s) {
  26333. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26334. }
  26335. // uv4s
  26336. var uv4s = parsedVertexData.uv4s;
  26337. if (uv4s) {
  26338. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26339. }
  26340. // uv5s
  26341. var uv5s = parsedVertexData.uv5s;
  26342. if (uv5s) {
  26343. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26344. }
  26345. // uv6s
  26346. var uv6s = parsedVertexData.uv6s;
  26347. if (uv6s) {
  26348. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26349. }
  26350. // colors
  26351. var colors = parsedVertexData.colors;
  26352. if (colors) {
  26353. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26354. }
  26355. // matricesIndices
  26356. var matricesIndices = parsedVertexData.matricesIndices;
  26357. if (matricesIndices) {
  26358. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26359. }
  26360. // matricesWeights
  26361. var matricesWeights = parsedVertexData.matricesWeights;
  26362. if (matricesWeights) {
  26363. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26364. }
  26365. // indices
  26366. var indices = parsedVertexData.indices;
  26367. if (indices) {
  26368. vertexData.indices = indices;
  26369. }
  26370. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26371. };
  26372. return VertexData;
  26373. })();
  26374. BABYLON.VertexData = VertexData;
  26375. })(BABYLON || (BABYLON = {}));
  26376. var BABYLON;
  26377. (function (BABYLON) {
  26378. var Tags = (function () {
  26379. function Tags() {
  26380. }
  26381. Tags.EnableFor = function (obj) {
  26382. obj._tags = obj._tags || {};
  26383. obj.hasTags = function () {
  26384. return Tags.HasTags(obj);
  26385. };
  26386. obj.addTags = function (tagsString) {
  26387. return Tags.AddTagsTo(obj, tagsString);
  26388. };
  26389. obj.removeTags = function (tagsString) {
  26390. return Tags.RemoveTagsFrom(obj, tagsString);
  26391. };
  26392. obj.matchesTagsQuery = function (tagsQuery) {
  26393. return Tags.MatchesQuery(obj, tagsQuery);
  26394. };
  26395. };
  26396. Tags.DisableFor = function (obj) {
  26397. delete obj._tags;
  26398. delete obj.hasTags;
  26399. delete obj.addTags;
  26400. delete obj.removeTags;
  26401. delete obj.matchesTagsQuery;
  26402. };
  26403. Tags.HasTags = function (obj) {
  26404. if (!obj._tags) {
  26405. return false;
  26406. }
  26407. return !BABYLON.Tools.IsEmpty(obj._tags);
  26408. };
  26409. Tags.GetTags = function (obj, asString) {
  26410. if (asString === void 0) { asString = true; }
  26411. if (!obj._tags) {
  26412. return null;
  26413. }
  26414. if (asString) {
  26415. var tagsArray = [];
  26416. for (var tag in obj._tags) {
  26417. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26418. tagsArray.push(tag);
  26419. }
  26420. }
  26421. return tagsArray.join(" ");
  26422. }
  26423. else {
  26424. return obj._tags;
  26425. }
  26426. };
  26427. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26428. // a tag cannot start with '||', '&&', and '!'
  26429. // it cannot contain whitespaces
  26430. Tags.AddTagsTo = function (obj, tagsString) {
  26431. if (!tagsString) {
  26432. return;
  26433. }
  26434. if (typeof tagsString !== "string") {
  26435. return;
  26436. }
  26437. var tags = tagsString.split(" ");
  26438. for (var t in tags) {
  26439. Tags._AddTagTo(obj, tags[t]);
  26440. }
  26441. };
  26442. Tags._AddTagTo = function (obj, tag) {
  26443. tag = tag.trim();
  26444. if (tag === "" || tag === "true" || tag === "false") {
  26445. return;
  26446. }
  26447. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26448. return;
  26449. }
  26450. Tags.EnableFor(obj);
  26451. obj._tags[tag] = true;
  26452. };
  26453. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26454. if (!Tags.HasTags(obj)) {
  26455. return;
  26456. }
  26457. var tags = tagsString.split(" ");
  26458. for (var t in tags) {
  26459. Tags._RemoveTagFrom(obj, tags[t]);
  26460. }
  26461. };
  26462. Tags._RemoveTagFrom = function (obj, tag) {
  26463. delete obj._tags[tag];
  26464. };
  26465. Tags.MatchesQuery = function (obj, tagsQuery) {
  26466. if (tagsQuery === undefined) {
  26467. return true;
  26468. }
  26469. if (tagsQuery === "") {
  26470. return Tags.HasTags(obj);
  26471. }
  26472. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26473. };
  26474. return Tags;
  26475. })();
  26476. BABYLON.Tags = Tags;
  26477. })(BABYLON || (BABYLON = {}));
  26478. var BABYLON;
  26479. (function (BABYLON) {
  26480. var Internals;
  26481. (function (Internals) {
  26482. var AndOrNotEvaluator = (function () {
  26483. function AndOrNotEvaluator() {
  26484. }
  26485. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26486. if (!query.match(/\([^\(\)]*\)/g)) {
  26487. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26488. }
  26489. else {
  26490. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26491. // remove parenthesis
  26492. r = r.slice(1, r.length - 1);
  26493. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26494. });
  26495. }
  26496. if (query === "true") {
  26497. return true;
  26498. }
  26499. if (query === "false") {
  26500. return false;
  26501. }
  26502. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26503. };
  26504. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26505. evaluateCallback = evaluateCallback || (function (r) {
  26506. return r === "true" ? true : false;
  26507. });
  26508. var result;
  26509. var or = parenthesisContent.split("||");
  26510. for (var i in or) {
  26511. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26512. var and = ori.split("&&");
  26513. if (and.length > 1) {
  26514. for (var j = 0; j < and.length; ++j) {
  26515. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26516. if (andj !== "true" && andj !== "false") {
  26517. if (andj[0] === "!") {
  26518. result = !evaluateCallback(andj.substring(1));
  26519. }
  26520. else {
  26521. result = evaluateCallback(andj);
  26522. }
  26523. }
  26524. else {
  26525. result = andj === "true" ? true : false;
  26526. }
  26527. if (!result) {
  26528. ori = "false";
  26529. break;
  26530. }
  26531. }
  26532. }
  26533. if (result || ori === "true") {
  26534. result = true;
  26535. break;
  26536. }
  26537. // result equals false (or undefined)
  26538. if (ori !== "true" && ori !== "false") {
  26539. if (ori[0] === "!") {
  26540. result = !evaluateCallback(ori.substring(1));
  26541. }
  26542. else {
  26543. result = evaluateCallback(ori);
  26544. }
  26545. }
  26546. else {
  26547. result = ori === "true" ? true : false;
  26548. }
  26549. }
  26550. // the whole parenthesis scope is replaced by 'true' or 'false'
  26551. return result ? "true" : "false";
  26552. };
  26553. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26554. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26555. // remove whitespaces
  26556. r = r.replace(/[\s]/g, function () { return ""; });
  26557. return r.length % 2 ? "!" : "";
  26558. });
  26559. booleanString = booleanString.trim();
  26560. if (booleanString === "!true") {
  26561. booleanString = "false";
  26562. }
  26563. else if (booleanString === "!false") {
  26564. booleanString = "true";
  26565. }
  26566. return booleanString;
  26567. };
  26568. return AndOrNotEvaluator;
  26569. })();
  26570. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26571. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26572. })(BABYLON || (BABYLON = {}));
  26573. var BABYLON;
  26574. (function (BABYLON) {
  26575. var PostProcessRenderPass = (function () {
  26576. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26577. this._enabled = true;
  26578. this._refCount = 0;
  26579. this._name = name;
  26580. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26581. this.setRenderList(renderList);
  26582. this._renderTexture.onBeforeRender = beforeRender;
  26583. this._renderTexture.onAfterRender = afterRender;
  26584. this._scene = scene;
  26585. this._renderList = renderList;
  26586. }
  26587. // private
  26588. PostProcessRenderPass.prototype._incRefCount = function () {
  26589. if (this._refCount === 0) {
  26590. this._scene.customRenderTargets.push(this._renderTexture);
  26591. }
  26592. return ++this._refCount;
  26593. };
  26594. PostProcessRenderPass.prototype._decRefCount = function () {
  26595. this._refCount--;
  26596. if (this._refCount <= 0) {
  26597. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26598. }
  26599. return this._refCount;
  26600. };
  26601. PostProcessRenderPass.prototype._update = function () {
  26602. this.setRenderList(this._renderList);
  26603. };
  26604. // public
  26605. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26606. this._renderTexture.renderList = renderList;
  26607. };
  26608. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26609. return this._renderTexture;
  26610. };
  26611. return PostProcessRenderPass;
  26612. })();
  26613. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26614. })(BABYLON || (BABYLON = {}));
  26615. var BABYLON;
  26616. (function (BABYLON) {
  26617. var PostProcessRenderEffect = (function () {
  26618. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26619. this._engine = engine;
  26620. this._name = name;
  26621. this._singleInstance = singleInstance || true;
  26622. this._getPostProcess = getPostProcess;
  26623. this._cameras = [];
  26624. this._indicesForCamera = [];
  26625. this._postProcesses = {};
  26626. this._renderPasses = {};
  26627. this._renderEffectAsPasses = {};
  26628. }
  26629. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26630. get: function () {
  26631. for (var index in this._postProcesses) {
  26632. if (!this._postProcesses[index].isSupported) {
  26633. return false;
  26634. }
  26635. }
  26636. return true;
  26637. },
  26638. enumerable: true,
  26639. configurable: true
  26640. });
  26641. PostProcessRenderEffect.prototype._update = function () {
  26642. for (var renderPassName in this._renderPasses) {
  26643. this._renderPasses[renderPassName]._update();
  26644. }
  26645. };
  26646. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26647. this._renderPasses[renderPass._name] = renderPass;
  26648. this._linkParameters();
  26649. };
  26650. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26651. delete this._renderPasses[renderPass._name];
  26652. this._linkParameters();
  26653. };
  26654. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26655. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26656. this._linkParameters();
  26657. };
  26658. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26659. for (var renderPassName in this._renderPasses) {
  26660. if (renderPassName === passName) {
  26661. return this._renderPasses[passName];
  26662. }
  26663. }
  26664. };
  26665. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26666. this._renderPasses = {};
  26667. this._linkParameters();
  26668. };
  26669. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26670. var cameraKey;
  26671. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26672. for (var i = 0; i < _cam.length; i++) {
  26673. var camera = _cam[i];
  26674. var cameraName = camera.name;
  26675. if (this._singleInstance) {
  26676. cameraKey = 0;
  26677. }
  26678. else {
  26679. cameraKey = cameraName;
  26680. }
  26681. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26682. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26683. if (!this._indicesForCamera[cameraName]) {
  26684. this._indicesForCamera[cameraName] = [];
  26685. }
  26686. this._indicesForCamera[cameraName].push(index);
  26687. if (this._cameras.indexOf(camera) === -1) {
  26688. this._cameras[cameraName] = camera;
  26689. }
  26690. for (var passName in this._renderPasses) {
  26691. this._renderPasses[passName]._incRefCount();
  26692. }
  26693. }
  26694. this._linkParameters();
  26695. };
  26696. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26697. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26698. for (var i = 0; i < _cam.length; i++) {
  26699. var camera = _cam[i];
  26700. var cameraName = camera.name;
  26701. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26702. var index = this._cameras.indexOf(cameraName);
  26703. this._indicesForCamera.splice(index, 1);
  26704. this._cameras.splice(index, 1);
  26705. for (var passName in this._renderPasses) {
  26706. this._renderPasses[passName]._decRefCount();
  26707. }
  26708. }
  26709. };
  26710. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26711. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26712. for (var i = 0; i < _cam.length; i++) {
  26713. var camera = _cam[i];
  26714. var cameraName = camera.name;
  26715. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26716. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26717. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26718. }
  26719. }
  26720. for (var passName in this._renderPasses) {
  26721. this._renderPasses[passName]._incRefCount();
  26722. }
  26723. }
  26724. };
  26725. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26726. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26727. for (var i = 0; i < _cam.length; i++) {
  26728. var camera = _cam[i];
  26729. var cameraName = camera.Name;
  26730. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26731. for (var passName in this._renderPasses) {
  26732. this._renderPasses[passName]._decRefCount();
  26733. }
  26734. }
  26735. };
  26736. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26737. if (this._singleInstance) {
  26738. return this._postProcesses[0];
  26739. }
  26740. else {
  26741. return this._postProcesses[camera.name];
  26742. }
  26743. };
  26744. PostProcessRenderEffect.prototype._linkParameters = function () {
  26745. var _this = this;
  26746. for (var index in this._postProcesses) {
  26747. if (this.applyParameters) {
  26748. this.applyParameters(this._postProcesses[index]);
  26749. }
  26750. this._postProcesses[index].onBeforeRender = function (effect) {
  26751. _this._linkTextures(effect);
  26752. };
  26753. }
  26754. };
  26755. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26756. for (var renderPassName in this._renderPasses) {
  26757. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26758. }
  26759. for (var renderEffectName in this._renderEffectAsPasses) {
  26760. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26761. }
  26762. };
  26763. return PostProcessRenderEffect;
  26764. })();
  26765. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26766. })(BABYLON || (BABYLON = {}));
  26767. var BABYLON;
  26768. (function (BABYLON) {
  26769. var PostProcessRenderPipeline = (function () {
  26770. function PostProcessRenderPipeline(engine, name) {
  26771. this._engine = engine;
  26772. this._name = name;
  26773. this._renderEffects = {};
  26774. this._renderEffectsForIsolatedPass = {};
  26775. this._cameras = [];
  26776. }
  26777. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26778. get: function () {
  26779. for (var renderEffectName in this._renderEffects) {
  26780. if (!this._renderEffects[renderEffectName].isSupported) {
  26781. return false;
  26782. }
  26783. }
  26784. return true;
  26785. },
  26786. enumerable: true,
  26787. configurable: true
  26788. });
  26789. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26790. this._renderEffects[renderEffect._name] = renderEffect;
  26791. };
  26792. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26793. var renderEffects = this._renderEffects[renderEffectName];
  26794. if (!renderEffects) {
  26795. return;
  26796. }
  26797. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26798. };
  26799. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26800. var renderEffects = this._renderEffects[renderEffectName];
  26801. if (!renderEffects) {
  26802. return;
  26803. }
  26804. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26805. };
  26806. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26807. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26808. var indicesToDelete = [];
  26809. var i;
  26810. for (i = 0; i < _cam.length; i++) {
  26811. var camera = _cam[i];
  26812. var cameraName = camera.name;
  26813. if (this._cameras.indexOf(camera) === -1) {
  26814. this._cameras[cameraName] = camera;
  26815. }
  26816. else if (unique) {
  26817. indicesToDelete.push(i);
  26818. }
  26819. }
  26820. for (i = 0; i < indicesToDelete.length; i++) {
  26821. cameras.splice(indicesToDelete[i], 1);
  26822. }
  26823. for (var renderEffectName in this._renderEffects) {
  26824. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26825. }
  26826. };
  26827. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26828. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26829. for (var renderEffectName in this._renderEffects) {
  26830. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26831. }
  26832. for (var i = 0; i < _cam.length; i++) {
  26833. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26834. }
  26835. };
  26836. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26837. var _this = this;
  26838. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26839. var pass = null;
  26840. var renderEffectName;
  26841. for (renderEffectName in this._renderEffects) {
  26842. pass = this._renderEffects[renderEffectName].getPass(passName);
  26843. if (pass != null) {
  26844. break;
  26845. }
  26846. }
  26847. if (pass === null) {
  26848. return;
  26849. }
  26850. for (renderEffectName in this._renderEffects) {
  26851. this._renderEffects[renderEffectName]._disable(_cam);
  26852. }
  26853. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26854. for (var i = 0; i < _cam.length; i++) {
  26855. var camera = _cam[i];
  26856. var cameraName = camera.name;
  26857. 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); });
  26858. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26859. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26860. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26861. }
  26862. };
  26863. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26864. var _this = this;
  26865. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26866. for (var i = 0; i < _cam.length; i++) {
  26867. var camera = _cam[i];
  26868. var cameraName = camera.name;
  26869. 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); });
  26870. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26871. }
  26872. for (var renderEffectName in this._renderEffects) {
  26873. this._renderEffects[renderEffectName]._enable(_cam);
  26874. }
  26875. };
  26876. PostProcessRenderPipeline.prototype._update = function () {
  26877. for (var renderEffectName in this._renderEffects) {
  26878. this._renderEffects[renderEffectName]._update();
  26879. }
  26880. for (var i = 0; i < this._cameras.length; i++) {
  26881. var cameraName = this._cameras[i].name;
  26882. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26883. this._renderEffectsForIsolatedPass[cameraName]._update();
  26884. }
  26885. }
  26886. };
  26887. PostProcessRenderPipeline.prototype.dispose = function () {
  26888. // Must be implemented by children
  26889. };
  26890. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26891. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26892. return PostProcessRenderPipeline;
  26893. })();
  26894. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26895. })(BABYLON || (BABYLON = {}));
  26896. var BABYLON;
  26897. (function (BABYLON) {
  26898. var PostProcessRenderPipelineManager = (function () {
  26899. function PostProcessRenderPipelineManager() {
  26900. this._renderPipelines = {};
  26901. }
  26902. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26903. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26904. };
  26905. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26906. var renderPipeline = this._renderPipelines[renderPipelineName];
  26907. if (!renderPipeline) {
  26908. return;
  26909. }
  26910. renderPipeline._attachCameras(cameras, unique);
  26911. };
  26912. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26913. var renderPipeline = this._renderPipelines[renderPipelineName];
  26914. if (!renderPipeline) {
  26915. return;
  26916. }
  26917. renderPipeline._detachCameras(cameras);
  26918. };
  26919. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26920. var renderPipeline = this._renderPipelines[renderPipelineName];
  26921. if (!renderPipeline) {
  26922. return;
  26923. }
  26924. renderPipeline._enableEffect(renderEffectName, cameras);
  26925. };
  26926. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26927. var renderPipeline = this._renderPipelines[renderPipelineName];
  26928. if (!renderPipeline) {
  26929. return;
  26930. }
  26931. renderPipeline._disableEffect(renderEffectName, cameras);
  26932. };
  26933. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26934. var renderPipeline = this._renderPipelines[renderPipelineName];
  26935. if (!renderPipeline) {
  26936. return;
  26937. }
  26938. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26939. };
  26940. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26941. var renderPipeline = this._renderPipelines[renderPipelineName];
  26942. if (!renderPipeline) {
  26943. return;
  26944. }
  26945. renderPipeline._disableDisplayOnlyPass(cameras);
  26946. };
  26947. PostProcessRenderPipelineManager.prototype.update = function () {
  26948. for (var renderPipelineName in this._renderPipelines) {
  26949. var pipeline = this._renderPipelines[renderPipelineName];
  26950. if (!pipeline.isSupported) {
  26951. pipeline.dispose();
  26952. delete this._renderPipelines[renderPipelineName];
  26953. }
  26954. else {
  26955. pipeline._update();
  26956. }
  26957. }
  26958. };
  26959. return PostProcessRenderPipelineManager;
  26960. })();
  26961. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26962. })(BABYLON || (BABYLON = {}));
  26963. var BABYLON;
  26964. (function (BABYLON) {
  26965. var BoundingBoxRenderer = (function () {
  26966. function BoundingBoxRenderer(scene) {
  26967. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26968. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26969. this.showBackLines = true;
  26970. this.renderList = new BABYLON.SmartArray(32);
  26971. this._scene = scene;
  26972. }
  26973. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26974. if (this._colorShader) {
  26975. return;
  26976. }
  26977. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26978. attributes: ["position"],
  26979. uniforms: ["worldViewProjection", "color"]
  26980. });
  26981. var engine = this._scene.getEngine();
  26982. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26983. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26984. 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]);
  26985. };
  26986. BoundingBoxRenderer.prototype.reset = function () {
  26987. this.renderList.reset();
  26988. };
  26989. BoundingBoxRenderer.prototype.render = function () {
  26990. if (this.renderList.length === 0) {
  26991. return;
  26992. }
  26993. this._prepareRessources();
  26994. if (!this._colorShader.isReady()) {
  26995. return;
  26996. }
  26997. var engine = this._scene.getEngine();
  26998. engine.setDepthWrite(false);
  26999. this._colorShader._preBind();
  27000. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27001. var boundingBox = this.renderList.data[boundingBoxIndex];
  27002. var min = boundingBox.minimum;
  27003. var max = boundingBox.maximum;
  27004. var diff = max.subtract(min);
  27005. var median = min.add(diff.scale(0.5));
  27006. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27007. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27008. .multiply(boundingBox.getWorldMatrix());
  27009. // VBOs
  27010. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27011. if (this.showBackLines) {
  27012. // Back
  27013. engine.setDepthFunctionToGreaterOrEqual();
  27014. this._scene.resetCachedMaterial();
  27015. this._colorShader.setColor4("color", this.backColor.toColor4());
  27016. this._colorShader.bind(worldMatrix);
  27017. // Draw order
  27018. engine.draw(false, 0, 24);
  27019. }
  27020. // Front
  27021. engine.setDepthFunctionToLess();
  27022. this._scene.resetCachedMaterial();
  27023. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27024. this._colorShader.bind(worldMatrix);
  27025. // Draw order
  27026. engine.draw(false, 0, 24);
  27027. }
  27028. this._colorShader.unbind();
  27029. engine.setDepthFunctionToLessOrEqual();
  27030. engine.setDepthWrite(true);
  27031. };
  27032. BoundingBoxRenderer.prototype.dispose = function () {
  27033. if (!this._colorShader) {
  27034. return;
  27035. }
  27036. this._colorShader.dispose();
  27037. this._vb.dispose();
  27038. this._scene.getEngine()._releaseBuffer(this._ib);
  27039. };
  27040. return BoundingBoxRenderer;
  27041. })();
  27042. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27043. })(BABYLON || (BABYLON = {}));
  27044. var BABYLON;
  27045. (function (BABYLON) {
  27046. var Condition = (function () {
  27047. function Condition(actionManager) {
  27048. this._actionManager = actionManager;
  27049. }
  27050. Condition.prototype.isValid = function () {
  27051. return true;
  27052. };
  27053. Condition.prototype._getProperty = function (propertyPath) {
  27054. return this._actionManager._getProperty(propertyPath);
  27055. };
  27056. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27057. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27058. };
  27059. return Condition;
  27060. })();
  27061. BABYLON.Condition = Condition;
  27062. var ValueCondition = (function (_super) {
  27063. __extends(ValueCondition, _super);
  27064. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27065. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27066. _super.call(this, actionManager);
  27067. this.propertyPath = propertyPath;
  27068. this.value = value;
  27069. this.operator = operator;
  27070. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27071. this._property = this._getProperty(this.propertyPath);
  27072. }
  27073. Object.defineProperty(ValueCondition, "IsEqual", {
  27074. get: function () {
  27075. return ValueCondition._IsEqual;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. Object.defineProperty(ValueCondition, "IsDifferent", {
  27081. get: function () {
  27082. return ValueCondition._IsDifferent;
  27083. },
  27084. enumerable: true,
  27085. configurable: true
  27086. });
  27087. Object.defineProperty(ValueCondition, "IsGreater", {
  27088. get: function () {
  27089. return ValueCondition._IsGreater;
  27090. },
  27091. enumerable: true,
  27092. configurable: true
  27093. });
  27094. Object.defineProperty(ValueCondition, "IsLesser", {
  27095. get: function () {
  27096. return ValueCondition._IsLesser;
  27097. },
  27098. enumerable: true,
  27099. configurable: true
  27100. });
  27101. // Methods
  27102. ValueCondition.prototype.isValid = function () {
  27103. switch (this.operator) {
  27104. case ValueCondition.IsGreater:
  27105. return this._target[this._property] > this.value;
  27106. case ValueCondition.IsLesser:
  27107. return this._target[this._property] < this.value;
  27108. case ValueCondition.IsEqual:
  27109. case ValueCondition.IsDifferent:
  27110. var check;
  27111. if (this.value.equals) {
  27112. check = this.value.equals(this._target[this._property]);
  27113. }
  27114. else {
  27115. check = this.value === this._target[this._property];
  27116. }
  27117. return this.operator === ValueCondition.IsEqual ? check : !check;
  27118. }
  27119. return false;
  27120. };
  27121. // Statics
  27122. ValueCondition._IsEqual = 0;
  27123. ValueCondition._IsDifferent = 1;
  27124. ValueCondition._IsGreater = 2;
  27125. ValueCondition._IsLesser = 3;
  27126. return ValueCondition;
  27127. })(Condition);
  27128. BABYLON.ValueCondition = ValueCondition;
  27129. var PredicateCondition = (function (_super) {
  27130. __extends(PredicateCondition, _super);
  27131. function PredicateCondition(actionManager, predicate) {
  27132. _super.call(this, actionManager);
  27133. this.predicate = predicate;
  27134. }
  27135. PredicateCondition.prototype.isValid = function () {
  27136. return this.predicate();
  27137. };
  27138. return PredicateCondition;
  27139. })(Condition);
  27140. BABYLON.PredicateCondition = PredicateCondition;
  27141. var StateCondition = (function (_super) {
  27142. __extends(StateCondition, _super);
  27143. function StateCondition(actionManager, target, value) {
  27144. _super.call(this, actionManager);
  27145. this.value = value;
  27146. this._target = target;
  27147. }
  27148. // Methods
  27149. StateCondition.prototype.isValid = function () {
  27150. return this._target.state === this.value;
  27151. };
  27152. return StateCondition;
  27153. })(Condition);
  27154. BABYLON.StateCondition = StateCondition;
  27155. })(BABYLON || (BABYLON = {}));
  27156. var BABYLON;
  27157. (function (BABYLON) {
  27158. var Action = (function () {
  27159. function Action(triggerOptions, condition) {
  27160. this.triggerOptions = triggerOptions;
  27161. if (triggerOptions.parameter) {
  27162. this.trigger = triggerOptions.trigger;
  27163. this._triggerParameter = triggerOptions.parameter;
  27164. }
  27165. else {
  27166. this.trigger = triggerOptions;
  27167. }
  27168. this._nextActiveAction = this;
  27169. this._condition = condition;
  27170. }
  27171. // Methods
  27172. Action.prototype._prepare = function () {
  27173. };
  27174. Action.prototype.getTriggerParameter = function () {
  27175. return this._triggerParameter;
  27176. };
  27177. Action.prototype._executeCurrent = function (evt) {
  27178. if (this._nextActiveAction._condition) {
  27179. var condition = this._nextActiveAction._condition;
  27180. var currentRenderId = this._actionManager.getScene().getRenderId();
  27181. // We cache the current evaluation for the current frame
  27182. if (condition._evaluationId === currentRenderId) {
  27183. if (!condition._currentResult) {
  27184. return;
  27185. }
  27186. }
  27187. else {
  27188. condition._evaluationId = currentRenderId;
  27189. if (!condition.isValid()) {
  27190. condition._currentResult = false;
  27191. return;
  27192. }
  27193. condition._currentResult = true;
  27194. }
  27195. }
  27196. this._nextActiveAction.execute(evt);
  27197. this.skipToNextActiveAction();
  27198. };
  27199. Action.prototype.execute = function (evt) {
  27200. };
  27201. Action.prototype.skipToNextActiveAction = function () {
  27202. if (this._nextActiveAction._child) {
  27203. if (!this._nextActiveAction._child._actionManager) {
  27204. this._nextActiveAction._child._actionManager = this._actionManager;
  27205. }
  27206. this._nextActiveAction = this._nextActiveAction._child;
  27207. }
  27208. else {
  27209. this._nextActiveAction = this;
  27210. }
  27211. };
  27212. Action.prototype.then = function (action) {
  27213. this._child = action;
  27214. action._actionManager = this._actionManager;
  27215. action._prepare();
  27216. return action;
  27217. };
  27218. Action.prototype._getProperty = function (propertyPath) {
  27219. return this._actionManager._getProperty(propertyPath);
  27220. };
  27221. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27222. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27223. };
  27224. return Action;
  27225. })();
  27226. BABYLON.Action = Action;
  27227. })(BABYLON || (BABYLON = {}));
  27228. var BABYLON;
  27229. (function (BABYLON) {
  27230. /**
  27231. * ActionEvent is the event beint sent when an action is triggered.
  27232. */
  27233. var ActionEvent = (function () {
  27234. /**
  27235. * @constructor
  27236. * @param source The mesh or sprite that triggered the action.
  27237. * @param pointerX The X mouse cursor position at the time of the event
  27238. * @param pointerY The Y mouse cursor position at the time of the event
  27239. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27240. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27241. */
  27242. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27243. this.source = source;
  27244. this.pointerX = pointerX;
  27245. this.pointerY = pointerY;
  27246. this.meshUnderPointer = meshUnderPointer;
  27247. this.sourceEvent = sourceEvent;
  27248. this.additionalData = additionalData;
  27249. }
  27250. /**
  27251. * Helper function to auto-create an ActionEvent from a source mesh.
  27252. * @param source The source mesh that triggered the event
  27253. * @param evt {Event} The original (browser) event
  27254. */
  27255. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27256. var scene = source.getScene();
  27257. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27258. };
  27259. /**
  27260. * Helper function to auto-create an ActionEvent from a source mesh.
  27261. * @param source The source sprite that triggered the event
  27262. * @param scene Scene associated with the sprite
  27263. * @param evt {Event} The original (browser) event
  27264. */
  27265. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27266. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27267. };
  27268. /**
  27269. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27270. * @param scene the scene where the event occurred
  27271. * @param evt {Event} The original (browser) event
  27272. */
  27273. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27274. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27275. };
  27276. return ActionEvent;
  27277. })();
  27278. BABYLON.ActionEvent = ActionEvent;
  27279. /**
  27280. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27281. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27282. */
  27283. var ActionManager = (function () {
  27284. function ActionManager(scene) {
  27285. // Members
  27286. this.actions = new Array();
  27287. this._scene = scene;
  27288. scene._actionManagers.push(this);
  27289. }
  27290. Object.defineProperty(ActionManager, "NothingTrigger", {
  27291. get: function () {
  27292. return ActionManager._NothingTrigger;
  27293. },
  27294. enumerable: true,
  27295. configurable: true
  27296. });
  27297. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27298. get: function () {
  27299. return ActionManager._OnPickTrigger;
  27300. },
  27301. enumerable: true,
  27302. configurable: true
  27303. });
  27304. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27305. get: function () {
  27306. return ActionManager._OnLeftPickTrigger;
  27307. },
  27308. enumerable: true,
  27309. configurable: true
  27310. });
  27311. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27312. get: function () {
  27313. return ActionManager._OnRightPickTrigger;
  27314. },
  27315. enumerable: true,
  27316. configurable: true
  27317. });
  27318. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27319. get: function () {
  27320. return ActionManager._OnCenterPickTrigger;
  27321. },
  27322. enumerable: true,
  27323. configurable: true
  27324. });
  27325. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27326. get: function () {
  27327. return ActionManager._OnPickDownTrigger;
  27328. },
  27329. enumerable: true,
  27330. configurable: true
  27331. });
  27332. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27333. get: function () {
  27334. return ActionManager._OnPickUpTrigger;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27340. /// This trigger will only be raised if you also declared a OnPickDown
  27341. get: function () {
  27342. return ActionManager._OnPickOutTrigger;
  27343. },
  27344. enumerable: true,
  27345. configurable: true
  27346. });
  27347. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27348. get: function () {
  27349. return ActionManager._OnLongPressTrigger;
  27350. },
  27351. enumerable: true,
  27352. configurable: true
  27353. });
  27354. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27355. get: function () {
  27356. return ActionManager._OnPointerOverTrigger;
  27357. },
  27358. enumerable: true,
  27359. configurable: true
  27360. });
  27361. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27362. get: function () {
  27363. return ActionManager._OnPointerOutTrigger;
  27364. },
  27365. enumerable: true,
  27366. configurable: true
  27367. });
  27368. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27369. get: function () {
  27370. return ActionManager._OnEveryFrameTrigger;
  27371. },
  27372. enumerable: true,
  27373. configurable: true
  27374. });
  27375. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27376. get: function () {
  27377. return ActionManager._OnIntersectionEnterTrigger;
  27378. },
  27379. enumerable: true,
  27380. configurable: true
  27381. });
  27382. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27383. get: function () {
  27384. return ActionManager._OnIntersectionExitTrigger;
  27385. },
  27386. enumerable: true,
  27387. configurable: true
  27388. });
  27389. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27390. get: function () {
  27391. return ActionManager._OnKeyDownTrigger;
  27392. },
  27393. enumerable: true,
  27394. configurable: true
  27395. });
  27396. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27397. get: function () {
  27398. return ActionManager._OnKeyUpTrigger;
  27399. },
  27400. enumerable: true,
  27401. configurable: true
  27402. });
  27403. // Methods
  27404. ActionManager.prototype.dispose = function () {
  27405. var index = this._scene._actionManagers.indexOf(this);
  27406. if (index > -1) {
  27407. this._scene._actionManagers.splice(index, 1);
  27408. }
  27409. };
  27410. ActionManager.prototype.getScene = function () {
  27411. return this._scene;
  27412. };
  27413. /**
  27414. * Does this action manager handles actions of any of the given triggers
  27415. * @param {number[]} triggers - the triggers to be tested
  27416. * @return {boolean} whether one (or more) of the triggers is handeled
  27417. */
  27418. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27419. for (var index = 0; index < this.actions.length; index++) {
  27420. var action = this.actions[index];
  27421. if (triggers.indexOf(action.trigger) > -1) {
  27422. return true;
  27423. }
  27424. }
  27425. return false;
  27426. };
  27427. /**
  27428. * Does this action manager handles actions of a given trigger
  27429. * @param {number} trigger - the trigger to be tested
  27430. * @return {boolean} whether the trigger is handeled
  27431. */
  27432. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27433. for (var index = 0; index < this.actions.length; index++) {
  27434. var action = this.actions[index];
  27435. if (action.trigger === trigger) {
  27436. return true;
  27437. }
  27438. }
  27439. return false;
  27440. };
  27441. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27442. /**
  27443. * Does this action manager has pointer triggers
  27444. * @return {boolean} whether or not it has pointer triggers
  27445. */
  27446. get: function () {
  27447. for (var index = 0; index < this.actions.length; index++) {
  27448. var action = this.actions[index];
  27449. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27450. return true;
  27451. }
  27452. }
  27453. return false;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27459. /**
  27460. * Does this action manager has pick triggers
  27461. * @return {boolean} whether or not it has pick triggers
  27462. */
  27463. get: function () {
  27464. for (var index = 0; index < this.actions.length; index++) {
  27465. var action = this.actions[index];
  27466. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27467. return true;
  27468. }
  27469. }
  27470. return false;
  27471. },
  27472. enumerable: true,
  27473. configurable: true
  27474. });
  27475. /**
  27476. * Registers an action to this action manager
  27477. * @param {BABYLON.Action} action - the action to be registered
  27478. * @return {BABYLON.Action} the action amended (prepared) after registration
  27479. */
  27480. ActionManager.prototype.registerAction = function (action) {
  27481. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27482. if (this.getScene().actionManager !== this) {
  27483. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27484. return null;
  27485. }
  27486. }
  27487. this.actions.push(action);
  27488. action._actionManager = this;
  27489. action._prepare();
  27490. return action;
  27491. };
  27492. /**
  27493. * Process a specific trigger
  27494. * @param {number} trigger - the trigger to process
  27495. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27496. */
  27497. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27498. for (var index = 0; index < this.actions.length; index++) {
  27499. var action = this.actions[index];
  27500. if (action.trigger === trigger) {
  27501. if (trigger === ActionManager.OnKeyUpTrigger
  27502. || trigger === ActionManager.OnKeyDownTrigger) {
  27503. var parameter = action.getTriggerParameter();
  27504. if (parameter) {
  27505. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27506. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27507. if (actualkey !== parameter.toLowerCase()) {
  27508. continue;
  27509. }
  27510. }
  27511. }
  27512. action._executeCurrent(evt);
  27513. }
  27514. }
  27515. };
  27516. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27517. var properties = propertyPath.split(".");
  27518. for (var index = 0; index < properties.length - 1; index++) {
  27519. target = target[properties[index]];
  27520. }
  27521. return target;
  27522. };
  27523. ActionManager.prototype._getProperty = function (propertyPath) {
  27524. var properties = propertyPath.split(".");
  27525. return properties[properties.length - 1];
  27526. };
  27527. ActionManager.Parse = function (parsedActions, object, scene) {
  27528. var actionManager = new BABYLON.ActionManager(scene);
  27529. if (object === null)
  27530. scene.actionManager = actionManager;
  27531. else
  27532. object.actionManager = actionManager;
  27533. // instanciate a new object
  27534. var instanciate = function (name, params) {
  27535. var newInstance = Object.create(BABYLON[name].prototype);
  27536. newInstance.constructor.apply(newInstance, params);
  27537. return newInstance;
  27538. };
  27539. var parseParameter = function (name, value, target, propertyPath) {
  27540. if (propertyPath === null) {
  27541. // String, boolean or float
  27542. var floatValue = parseFloat(value);
  27543. if (value === "true" || value === "false")
  27544. return value === "true";
  27545. else
  27546. return isNaN(floatValue) ? value : floatValue;
  27547. }
  27548. var effectiveTarget = propertyPath.split(".");
  27549. var values = value.split(",");
  27550. // Get effective Target
  27551. for (var i = 0; i < effectiveTarget.length; i++) {
  27552. target = target[effectiveTarget[i]];
  27553. }
  27554. // Return appropriate value with its type
  27555. if (typeof (target) === "boolean")
  27556. return values[0] === "true";
  27557. if (typeof (target) === "string")
  27558. return values[0];
  27559. // Parameters with multiple values such as Vector3 etc.
  27560. var split = new Array();
  27561. for (var i = 0; i < values.length; i++)
  27562. split.push(parseFloat(values[i]));
  27563. if (target instanceof BABYLON.Vector3)
  27564. return BABYLON.Vector3.FromArray(split);
  27565. if (target instanceof BABYLON.Vector4)
  27566. return BABYLON.Vector4.FromArray(split);
  27567. if (target instanceof BABYLON.Color3)
  27568. return BABYLON.Color3.FromArray(split);
  27569. if (target instanceof BABYLON.Color4)
  27570. return BABYLON.Color4.FromArray(split);
  27571. return parseFloat(values[0]);
  27572. };
  27573. // traverse graph per trigger
  27574. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27575. if (combineArray === void 0) { combineArray = null; }
  27576. if (parsedAction.detached)
  27577. return;
  27578. var parameters = new Array();
  27579. var target = null;
  27580. var propertyPath = null;
  27581. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27582. // Parameters
  27583. if (parsedAction.type === 2)
  27584. parameters.push(actionManager);
  27585. else
  27586. parameters.push(trigger);
  27587. if (combine) {
  27588. var actions = new Array();
  27589. for (var j = 0; j < parsedAction.combine.length; j++) {
  27590. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27591. }
  27592. parameters.push(actions);
  27593. }
  27594. else {
  27595. for (var i = 0; i < parsedAction.properties.length; i++) {
  27596. var value = parsedAction.properties[i].value;
  27597. var name = parsedAction.properties[i].name;
  27598. var targetType = parsedAction.properties[i].targetType;
  27599. if (name === "target")
  27600. if (targetType !== null && targetType === "SceneProperties")
  27601. value = target = scene;
  27602. else
  27603. value = target = scene.getNodeByName(value);
  27604. else if (name === "parent")
  27605. value = scene.getNodeByName(value);
  27606. else if (name === "sound")
  27607. value = scene.getSoundByName(value);
  27608. else if (name !== "propertyPath") {
  27609. if (parsedAction.type === 2 && name === "operator")
  27610. value = BABYLON.ValueCondition[value];
  27611. else
  27612. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27613. }
  27614. else {
  27615. propertyPath = value;
  27616. }
  27617. parameters.push(value);
  27618. }
  27619. }
  27620. if (combineArray === null) {
  27621. parameters.push(condition);
  27622. }
  27623. else {
  27624. parameters.push(null);
  27625. }
  27626. // If interpolate value action
  27627. if (parsedAction.name === "InterpolateValueAction") {
  27628. var param = parameters[parameters.length - 2];
  27629. parameters[parameters.length - 1] = param;
  27630. parameters[parameters.length - 2] = condition;
  27631. }
  27632. // Action or condition(s) and not CombineAction
  27633. var newAction = instanciate(parsedAction.name, parameters);
  27634. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27635. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27636. if (action)
  27637. action.then(nothing);
  27638. else
  27639. actionManager.registerAction(nothing);
  27640. action = nothing;
  27641. }
  27642. if (combineArray === null) {
  27643. if (newAction instanceof BABYLON.Condition) {
  27644. condition = newAction;
  27645. newAction = action;
  27646. }
  27647. else {
  27648. condition = null;
  27649. if (action)
  27650. action.then(newAction);
  27651. else
  27652. actionManager.registerAction(newAction);
  27653. }
  27654. }
  27655. else {
  27656. combineArray.push(newAction);
  27657. }
  27658. for (var i = 0; i < parsedAction.children.length; i++)
  27659. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27660. };
  27661. // triggers
  27662. for (var i = 0; i < parsedActions.children.length; i++) {
  27663. var triggerParams;
  27664. var trigger = parsedActions.children[i];
  27665. if (trigger.properties.length > 0) {
  27666. var param = trigger.properties[0].value;
  27667. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27668. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27669. }
  27670. else
  27671. triggerParams = BABYLON.ActionManager[trigger.name];
  27672. for (var j = 0; j < trigger.children.length; j++) {
  27673. if (!trigger.detached)
  27674. traverse(trigger.children[j], triggerParams, null, null);
  27675. }
  27676. }
  27677. };
  27678. // Statics
  27679. ActionManager._NothingTrigger = 0;
  27680. ActionManager._OnPickTrigger = 1;
  27681. ActionManager._OnLeftPickTrigger = 2;
  27682. ActionManager._OnRightPickTrigger = 3;
  27683. ActionManager._OnCenterPickTrigger = 4;
  27684. ActionManager._OnPickDownTrigger = 5;
  27685. ActionManager._OnPickUpTrigger = 6;
  27686. ActionManager._OnLongPressTrigger = 7;
  27687. ActionManager._OnPointerOverTrigger = 8;
  27688. ActionManager._OnPointerOutTrigger = 9;
  27689. ActionManager._OnEveryFrameTrigger = 10;
  27690. ActionManager._OnIntersectionEnterTrigger = 11;
  27691. ActionManager._OnIntersectionExitTrigger = 12;
  27692. ActionManager._OnKeyDownTrigger = 13;
  27693. ActionManager._OnKeyUpTrigger = 14;
  27694. ActionManager._OnPickOutTrigger = 15;
  27695. ActionManager.DragMovementThreshold = 10; // in pixels
  27696. ActionManager.LongPressDelay = 500; // in milliseconds
  27697. return ActionManager;
  27698. })();
  27699. BABYLON.ActionManager = ActionManager;
  27700. })(BABYLON || (BABYLON = {}));
  27701. var BABYLON;
  27702. (function (BABYLON) {
  27703. var InterpolateValueAction = (function (_super) {
  27704. __extends(InterpolateValueAction, _super);
  27705. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27706. if (duration === void 0) { duration = 1000; }
  27707. _super.call(this, triggerOptions, condition);
  27708. this.propertyPath = propertyPath;
  27709. this.value = value;
  27710. this.duration = duration;
  27711. this.stopOtherAnimations = stopOtherAnimations;
  27712. this.onInterpolationDone = onInterpolationDone;
  27713. this._target = target;
  27714. }
  27715. InterpolateValueAction.prototype._prepare = function () {
  27716. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27717. this._property = this._getProperty(this.propertyPath);
  27718. };
  27719. InterpolateValueAction.prototype.execute = function () {
  27720. var scene = this._actionManager.getScene();
  27721. var keys = [
  27722. {
  27723. frame: 0,
  27724. value: this._target[this._property]
  27725. }, {
  27726. frame: 100,
  27727. value: this.value
  27728. }
  27729. ];
  27730. var dataType;
  27731. if (typeof this.value === "number") {
  27732. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27733. }
  27734. else if (this.value instanceof BABYLON.Color3) {
  27735. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27736. }
  27737. else if (this.value instanceof BABYLON.Vector3) {
  27738. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27739. }
  27740. else if (this.value instanceof BABYLON.Matrix) {
  27741. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27742. }
  27743. else if (this.value instanceof BABYLON.Quaternion) {
  27744. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27745. }
  27746. else {
  27747. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27748. return;
  27749. }
  27750. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27751. animation.setKeys(keys);
  27752. if (this.stopOtherAnimations) {
  27753. scene.stopAnimation(this._target);
  27754. }
  27755. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27756. };
  27757. return InterpolateValueAction;
  27758. })(BABYLON.Action);
  27759. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27760. })(BABYLON || (BABYLON = {}));
  27761. var BABYLON;
  27762. (function (BABYLON) {
  27763. var SwitchBooleanAction = (function (_super) {
  27764. __extends(SwitchBooleanAction, _super);
  27765. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27766. _super.call(this, triggerOptions, condition);
  27767. this.propertyPath = propertyPath;
  27768. this._target = target;
  27769. }
  27770. SwitchBooleanAction.prototype._prepare = function () {
  27771. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27772. this._property = this._getProperty(this.propertyPath);
  27773. };
  27774. SwitchBooleanAction.prototype.execute = function () {
  27775. this._target[this._property] = !this._target[this._property];
  27776. };
  27777. return SwitchBooleanAction;
  27778. })(BABYLON.Action);
  27779. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27780. var SetStateAction = (function (_super) {
  27781. __extends(SetStateAction, _super);
  27782. function SetStateAction(triggerOptions, target, value, condition) {
  27783. _super.call(this, triggerOptions, condition);
  27784. this.value = value;
  27785. this._target = target;
  27786. }
  27787. SetStateAction.prototype.execute = function () {
  27788. this._target.state = this.value;
  27789. };
  27790. return SetStateAction;
  27791. })(BABYLON.Action);
  27792. BABYLON.SetStateAction = SetStateAction;
  27793. var SetValueAction = (function (_super) {
  27794. __extends(SetValueAction, _super);
  27795. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27796. _super.call(this, triggerOptions, condition);
  27797. this.propertyPath = propertyPath;
  27798. this.value = value;
  27799. this._target = target;
  27800. }
  27801. SetValueAction.prototype._prepare = function () {
  27802. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27803. this._property = this._getProperty(this.propertyPath);
  27804. };
  27805. SetValueAction.prototype.execute = function () {
  27806. this._target[this._property] = this.value;
  27807. };
  27808. return SetValueAction;
  27809. })(BABYLON.Action);
  27810. BABYLON.SetValueAction = SetValueAction;
  27811. var IncrementValueAction = (function (_super) {
  27812. __extends(IncrementValueAction, _super);
  27813. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27814. _super.call(this, triggerOptions, condition);
  27815. this.propertyPath = propertyPath;
  27816. this.value = value;
  27817. this._target = target;
  27818. }
  27819. IncrementValueAction.prototype._prepare = function () {
  27820. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27821. this._property = this._getProperty(this.propertyPath);
  27822. if (typeof this._target[this._property] !== "number") {
  27823. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27824. }
  27825. };
  27826. IncrementValueAction.prototype.execute = function () {
  27827. this._target[this._property] += this.value;
  27828. };
  27829. return IncrementValueAction;
  27830. })(BABYLON.Action);
  27831. BABYLON.IncrementValueAction = IncrementValueAction;
  27832. var PlayAnimationAction = (function (_super) {
  27833. __extends(PlayAnimationAction, _super);
  27834. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27835. _super.call(this, triggerOptions, condition);
  27836. this.from = from;
  27837. this.to = to;
  27838. this.loop = loop;
  27839. this._target = target;
  27840. }
  27841. PlayAnimationAction.prototype._prepare = function () {
  27842. };
  27843. PlayAnimationAction.prototype.execute = function () {
  27844. var scene = this._actionManager.getScene();
  27845. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27846. };
  27847. return PlayAnimationAction;
  27848. })(BABYLON.Action);
  27849. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27850. var StopAnimationAction = (function (_super) {
  27851. __extends(StopAnimationAction, _super);
  27852. function StopAnimationAction(triggerOptions, target, condition) {
  27853. _super.call(this, triggerOptions, condition);
  27854. this._target = target;
  27855. }
  27856. StopAnimationAction.prototype._prepare = function () {
  27857. };
  27858. StopAnimationAction.prototype.execute = function () {
  27859. var scene = this._actionManager.getScene();
  27860. scene.stopAnimation(this._target);
  27861. };
  27862. return StopAnimationAction;
  27863. })(BABYLON.Action);
  27864. BABYLON.StopAnimationAction = StopAnimationAction;
  27865. var DoNothingAction = (function (_super) {
  27866. __extends(DoNothingAction, _super);
  27867. function DoNothingAction(triggerOptions, condition) {
  27868. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27869. _super.call(this, triggerOptions, condition);
  27870. }
  27871. DoNothingAction.prototype.execute = function () {
  27872. };
  27873. return DoNothingAction;
  27874. })(BABYLON.Action);
  27875. BABYLON.DoNothingAction = DoNothingAction;
  27876. var CombineAction = (function (_super) {
  27877. __extends(CombineAction, _super);
  27878. function CombineAction(triggerOptions, children, condition) {
  27879. _super.call(this, triggerOptions, condition);
  27880. this.children = children;
  27881. }
  27882. CombineAction.prototype._prepare = function () {
  27883. for (var index = 0; index < this.children.length; index++) {
  27884. this.children[index]._actionManager = this._actionManager;
  27885. this.children[index]._prepare();
  27886. }
  27887. };
  27888. CombineAction.prototype.execute = function (evt) {
  27889. for (var index = 0; index < this.children.length; index++) {
  27890. this.children[index].execute(evt);
  27891. }
  27892. };
  27893. return CombineAction;
  27894. })(BABYLON.Action);
  27895. BABYLON.CombineAction = CombineAction;
  27896. var ExecuteCodeAction = (function (_super) {
  27897. __extends(ExecuteCodeAction, _super);
  27898. function ExecuteCodeAction(triggerOptions, func, condition) {
  27899. _super.call(this, triggerOptions, condition);
  27900. this.func = func;
  27901. }
  27902. ExecuteCodeAction.prototype.execute = function (evt) {
  27903. this.func(evt);
  27904. };
  27905. return ExecuteCodeAction;
  27906. })(BABYLON.Action);
  27907. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27908. var SetParentAction = (function (_super) {
  27909. __extends(SetParentAction, _super);
  27910. function SetParentAction(triggerOptions, target, parent, condition) {
  27911. _super.call(this, triggerOptions, condition);
  27912. this._target = target;
  27913. this._parent = parent;
  27914. }
  27915. SetParentAction.prototype._prepare = function () {
  27916. };
  27917. SetParentAction.prototype.execute = function () {
  27918. if (this._target.parent === this._parent) {
  27919. return;
  27920. }
  27921. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27922. invertParentWorldMatrix.invert();
  27923. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27924. this._target.parent = this._parent;
  27925. };
  27926. return SetParentAction;
  27927. })(BABYLON.Action);
  27928. BABYLON.SetParentAction = SetParentAction;
  27929. var PlaySoundAction = (function (_super) {
  27930. __extends(PlaySoundAction, _super);
  27931. function PlaySoundAction(triggerOptions, sound, condition) {
  27932. _super.call(this, triggerOptions, condition);
  27933. this._sound = sound;
  27934. }
  27935. PlaySoundAction.prototype._prepare = function () {
  27936. };
  27937. PlaySoundAction.prototype.execute = function () {
  27938. if (this._sound !== undefined)
  27939. this._sound.play();
  27940. };
  27941. return PlaySoundAction;
  27942. })(BABYLON.Action);
  27943. BABYLON.PlaySoundAction = PlaySoundAction;
  27944. var StopSoundAction = (function (_super) {
  27945. __extends(StopSoundAction, _super);
  27946. function StopSoundAction(triggerOptions, sound, condition) {
  27947. _super.call(this, triggerOptions, condition);
  27948. this._sound = sound;
  27949. }
  27950. StopSoundAction.prototype._prepare = function () {
  27951. };
  27952. StopSoundAction.prototype.execute = function () {
  27953. if (this._sound !== undefined)
  27954. this._sound.stop();
  27955. };
  27956. return StopSoundAction;
  27957. })(BABYLON.Action);
  27958. BABYLON.StopSoundAction = StopSoundAction;
  27959. })(BABYLON || (BABYLON = {}));
  27960. var BABYLON;
  27961. (function (BABYLON) {
  27962. var Geometry = (function () {
  27963. function Geometry(id, scene, vertexData, updatable, mesh) {
  27964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27965. this._totalVertices = 0;
  27966. this._isDisposed = false;
  27967. this.id = id;
  27968. this._engine = scene.getEngine();
  27969. this._meshes = [];
  27970. this._scene = scene;
  27971. //Init vertex buffer cache
  27972. this._vertexBuffers = {};
  27973. this._indices = [];
  27974. // vertexData
  27975. if (vertexData) {
  27976. this.setAllVerticesData(vertexData, updatable);
  27977. }
  27978. else {
  27979. this._totalVertices = 0;
  27980. this._indices = [];
  27981. }
  27982. // applyToMesh
  27983. if (mesh) {
  27984. this.applyToMesh(mesh);
  27985. mesh.computeWorldMatrix(true);
  27986. }
  27987. }
  27988. Object.defineProperty(Geometry.prototype, "extend", {
  27989. get: function () {
  27990. return this._extend;
  27991. },
  27992. enumerable: true,
  27993. configurable: true
  27994. });
  27995. Geometry.prototype.getScene = function () {
  27996. return this._scene;
  27997. };
  27998. Geometry.prototype.getEngine = function () {
  27999. return this._engine;
  28000. };
  28001. Geometry.prototype.isReady = function () {
  28002. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28003. };
  28004. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28005. vertexData.applyToGeometry(this, updatable);
  28006. this.notifyUpdate();
  28007. };
  28008. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28009. if (this._vertexBuffers[kind]) {
  28010. this._vertexBuffers[kind].dispose();
  28011. }
  28012. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28013. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28014. stride = this._vertexBuffers[kind].getStrideSize();
  28015. this._totalVertices = data.length / stride;
  28016. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28017. var meshes = this._meshes;
  28018. var numOfMeshes = meshes.length;
  28019. for (var index = 0; index < numOfMeshes; index++) {
  28020. var mesh = meshes[index];
  28021. mesh._resetPointsArrayCache();
  28022. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28023. mesh._createGlobalSubMesh();
  28024. mesh.computeWorldMatrix(true);
  28025. }
  28026. }
  28027. this.notifyUpdate(kind);
  28028. };
  28029. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28030. var vertexBuffer = this.getVertexBuffer(kind);
  28031. if (!vertexBuffer) {
  28032. return;
  28033. }
  28034. vertexBuffer.updateDirectly(data, offset);
  28035. this.notifyUpdate(kind);
  28036. };
  28037. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28038. var vertexBuffer = this.getVertexBuffer(kind);
  28039. if (!vertexBuffer) {
  28040. return;
  28041. }
  28042. vertexBuffer.update(data);
  28043. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28044. var stride = vertexBuffer.getStrideSize();
  28045. this._totalVertices = data.length / stride;
  28046. if (updateExtends) {
  28047. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28048. }
  28049. var meshes = this._meshes;
  28050. var numOfMeshes = meshes.length;
  28051. for (var index = 0; index < numOfMeshes; index++) {
  28052. var mesh = meshes[index];
  28053. mesh._resetPointsArrayCache();
  28054. if (updateExtends) {
  28055. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28056. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28057. var subMesh = mesh.subMeshes[subIndex];
  28058. subMesh.refreshBoundingInfo();
  28059. }
  28060. }
  28061. }
  28062. }
  28063. this.notifyUpdate(kind);
  28064. };
  28065. Geometry.prototype.getTotalVertices = function () {
  28066. if (!this.isReady()) {
  28067. return 0;
  28068. }
  28069. return this._totalVertices;
  28070. };
  28071. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28072. var vertexBuffer = this.getVertexBuffer(kind);
  28073. if (!vertexBuffer) {
  28074. return null;
  28075. }
  28076. var orig = vertexBuffer.getData();
  28077. if (!copyWhenShared || this._meshes.length === 1) {
  28078. return orig;
  28079. }
  28080. else {
  28081. var len = orig.length;
  28082. var copy = [];
  28083. for (var i = 0; i < len; i++) {
  28084. copy.push(orig[i]);
  28085. }
  28086. return copy;
  28087. }
  28088. };
  28089. Geometry.prototype.getVertexBuffer = function (kind) {
  28090. if (!this.isReady()) {
  28091. return null;
  28092. }
  28093. return this._vertexBuffers[kind];
  28094. };
  28095. Geometry.prototype.getVertexBuffers = function () {
  28096. if (!this.isReady()) {
  28097. return null;
  28098. }
  28099. return this._vertexBuffers;
  28100. };
  28101. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28102. if (!this._vertexBuffers) {
  28103. if (this._delayInfo) {
  28104. return this._delayInfo.indexOf(kind) !== -1;
  28105. }
  28106. return false;
  28107. }
  28108. return this._vertexBuffers[kind] !== undefined;
  28109. };
  28110. Geometry.prototype.getVerticesDataKinds = function () {
  28111. var result = [];
  28112. var kind;
  28113. if (!this._vertexBuffers && this._delayInfo) {
  28114. for (kind in this._delayInfo) {
  28115. result.push(kind);
  28116. }
  28117. }
  28118. else {
  28119. for (kind in this._vertexBuffers) {
  28120. result.push(kind);
  28121. }
  28122. }
  28123. return result;
  28124. };
  28125. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28126. if (this._indexBuffer) {
  28127. this._engine._releaseBuffer(this._indexBuffer);
  28128. }
  28129. this._indices = indices;
  28130. if (this._meshes.length !== 0 && this._indices) {
  28131. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28132. }
  28133. if (totalVertices !== undefined) {
  28134. this._totalVertices = totalVertices;
  28135. }
  28136. var meshes = this._meshes;
  28137. var numOfMeshes = meshes.length;
  28138. for (var index = 0; index < numOfMeshes; index++) {
  28139. meshes[index]._createGlobalSubMesh();
  28140. }
  28141. this.notifyUpdate();
  28142. };
  28143. Geometry.prototype.getTotalIndices = function () {
  28144. if (!this.isReady()) {
  28145. return 0;
  28146. }
  28147. return this._indices.length;
  28148. };
  28149. Geometry.prototype.getIndices = function (copyWhenShared) {
  28150. if (!this.isReady()) {
  28151. return null;
  28152. }
  28153. var orig = this._indices;
  28154. if (!copyWhenShared || this._meshes.length === 1) {
  28155. return orig;
  28156. }
  28157. else {
  28158. var len = orig.length;
  28159. var copy = [];
  28160. for (var i = 0; i < len; i++) {
  28161. copy.push(orig[i]);
  28162. }
  28163. return copy;
  28164. }
  28165. };
  28166. Geometry.prototype.getIndexBuffer = function () {
  28167. if (!this.isReady()) {
  28168. return null;
  28169. }
  28170. return this._indexBuffer;
  28171. };
  28172. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28173. var meshes = this._meshes;
  28174. var index = meshes.indexOf(mesh);
  28175. if (index === -1) {
  28176. return;
  28177. }
  28178. for (var kind in this._vertexBuffers) {
  28179. this._vertexBuffers[kind].dispose();
  28180. }
  28181. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28182. this._indexBuffer = null;
  28183. }
  28184. meshes.splice(index, 1);
  28185. mesh._geometry = null;
  28186. if (meshes.length === 0 && shouldDispose) {
  28187. this.dispose();
  28188. }
  28189. };
  28190. Geometry.prototype.applyToMesh = function (mesh) {
  28191. if (mesh._geometry === this) {
  28192. return;
  28193. }
  28194. var previousGeometry = mesh._geometry;
  28195. if (previousGeometry) {
  28196. previousGeometry.releaseForMesh(mesh);
  28197. }
  28198. var meshes = this._meshes;
  28199. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28200. mesh._geometry = this;
  28201. this._scene.pushGeometry(this);
  28202. meshes.push(mesh);
  28203. if (this.isReady()) {
  28204. this._applyToMesh(mesh);
  28205. }
  28206. else {
  28207. mesh._boundingInfo = this._boundingInfo;
  28208. }
  28209. };
  28210. Geometry.prototype._applyToMesh = function (mesh) {
  28211. var numOfMeshes = this._meshes.length;
  28212. // vertexBuffers
  28213. for (var kind in this._vertexBuffers) {
  28214. if (numOfMeshes === 1) {
  28215. this._vertexBuffers[kind].create();
  28216. }
  28217. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28218. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28219. mesh._resetPointsArrayCache();
  28220. if (!this._extend) {
  28221. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28222. }
  28223. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28224. mesh._createGlobalSubMesh();
  28225. //bounding info was just created again, world matrix should be applied again.
  28226. mesh._updateBoundingInfo();
  28227. }
  28228. }
  28229. // indexBuffer
  28230. if (numOfMeshes === 1 && this._indices) {
  28231. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28232. }
  28233. if (this._indexBuffer) {
  28234. this._indexBuffer.references = numOfMeshes;
  28235. }
  28236. };
  28237. Geometry.prototype.notifyUpdate = function (kind) {
  28238. if (this.onGeometryUpdated) {
  28239. this.onGeometryUpdated(this, kind);
  28240. }
  28241. };
  28242. Geometry.prototype.load = function (scene, onLoaded) {
  28243. var _this = this;
  28244. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28245. return;
  28246. }
  28247. if (this.isReady()) {
  28248. if (onLoaded) {
  28249. onLoaded();
  28250. }
  28251. return;
  28252. }
  28253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28254. scene._addPendingData(this);
  28255. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28256. _this._delayLoadingFunction(JSON.parse(data), _this);
  28257. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28258. _this._delayInfo = [];
  28259. scene._removePendingData(_this);
  28260. var meshes = _this._meshes;
  28261. var numOfMeshes = meshes.length;
  28262. for (var index = 0; index < numOfMeshes; index++) {
  28263. _this._applyToMesh(meshes[index]);
  28264. }
  28265. if (onLoaded) {
  28266. onLoaded();
  28267. }
  28268. }, function () { }, scene.database);
  28269. };
  28270. Geometry.prototype.isDisposed = function () {
  28271. return this._isDisposed;
  28272. };
  28273. Geometry.prototype.dispose = function () {
  28274. var meshes = this._meshes;
  28275. var numOfMeshes = meshes.length;
  28276. var index;
  28277. for (index = 0; index < numOfMeshes; index++) {
  28278. this.releaseForMesh(meshes[index]);
  28279. }
  28280. this._meshes = [];
  28281. for (var kind in this._vertexBuffers) {
  28282. this._vertexBuffers[kind].dispose();
  28283. }
  28284. this._vertexBuffers = [];
  28285. this._totalVertices = 0;
  28286. if (this._indexBuffer) {
  28287. this._engine._releaseBuffer(this._indexBuffer);
  28288. }
  28289. this._indexBuffer = null;
  28290. this._indices = [];
  28291. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28292. this.delayLoadingFile = null;
  28293. this._delayLoadingFunction = null;
  28294. this._delayInfo = [];
  28295. this._boundingInfo = null;
  28296. this._scene.removeGeometry(this);
  28297. this._isDisposed = true;
  28298. };
  28299. Geometry.prototype.copy = function (id) {
  28300. var vertexData = new BABYLON.VertexData();
  28301. vertexData.indices = [];
  28302. var indices = this.getIndices();
  28303. for (var index = 0; index < indices.length; index++) {
  28304. vertexData.indices.push(indices[index]);
  28305. }
  28306. var updatable = false;
  28307. var stopChecking = false;
  28308. var kind;
  28309. for (kind in this._vertexBuffers) {
  28310. // using slice() to make a copy of the array and not just reference it
  28311. var data = this.getVerticesData(kind);
  28312. if (data instanceof Float32Array) {
  28313. vertexData.set(new Float32Array(data), kind);
  28314. }
  28315. else {
  28316. vertexData.set(data.slice(0), kind);
  28317. }
  28318. if (!stopChecking) {
  28319. updatable = this.getVertexBuffer(kind).isUpdatable();
  28320. stopChecking = !updatable;
  28321. }
  28322. }
  28323. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28324. geometry.delayLoadState = this.delayLoadState;
  28325. geometry.delayLoadingFile = this.delayLoadingFile;
  28326. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28327. for (kind in this._delayInfo) {
  28328. geometry._delayInfo = geometry._delayInfo || [];
  28329. geometry._delayInfo.push(kind);
  28330. }
  28331. // Bounding info
  28332. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28333. return geometry;
  28334. };
  28335. Geometry.prototype.serialize = function () {
  28336. var serializationObject = {};
  28337. serializationObject.id = this.id;
  28338. if (BABYLON.Tags.HasTags(this)) {
  28339. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28340. }
  28341. return serializationObject;
  28342. };
  28343. Geometry.prototype.serializeVerticeData = function () {
  28344. var serializationObject = this.serialize();
  28345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28346. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28347. }
  28348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28349. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28350. }
  28351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28352. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28353. }
  28354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28355. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28356. }
  28357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28358. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28359. }
  28360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28361. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28362. }
  28363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28364. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28365. }
  28366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28367. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28368. }
  28369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28370. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28371. }
  28372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28373. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28374. serializationObject.matricesIndices._isExpanded = true;
  28375. }
  28376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28377. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28378. }
  28379. serializationObject.indices = this.getIndices();
  28380. return serializationObject;
  28381. };
  28382. // Statics
  28383. Geometry.ExtractFromMesh = function (mesh, id) {
  28384. var geometry = mesh._geometry;
  28385. if (!geometry) {
  28386. return null;
  28387. }
  28388. return geometry.copy(id);
  28389. };
  28390. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28391. // be aware Math.random() could cause collisions
  28392. Geometry.RandomId = function () {
  28393. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28394. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28395. return v.toString(16);
  28396. });
  28397. };
  28398. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28399. var scene = mesh.getScene();
  28400. // Geometry
  28401. var geometryId = parsedGeometry.geometryId;
  28402. if (geometryId) {
  28403. var geometry = scene.getGeometryByID(geometryId);
  28404. if (geometry) {
  28405. geometry.applyToMesh(mesh);
  28406. }
  28407. }
  28408. else if (parsedGeometry instanceof ArrayBuffer) {
  28409. var binaryInfo = mesh._binaryInfo;
  28410. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28411. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28412. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28413. }
  28414. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28415. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28416. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28417. }
  28418. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28419. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28420. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28421. }
  28422. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28423. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28424. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28425. }
  28426. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28427. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28428. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28429. }
  28430. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28431. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28432. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28433. }
  28434. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28435. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28436. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28437. }
  28438. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28439. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28440. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28441. }
  28442. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28443. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28444. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28445. }
  28446. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28447. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28448. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28449. }
  28450. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28451. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28453. }
  28454. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28455. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28456. mesh.setIndices(indicesData);
  28457. }
  28458. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28459. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28460. mesh.subMeshes = [];
  28461. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28462. var materialIndex = subMeshesData[(i * 5) + 0];
  28463. var verticesStart = subMeshesData[(i * 5) + 1];
  28464. var verticesCount = subMeshesData[(i * 5) + 2];
  28465. var indexStart = subMeshesData[(i * 5) + 3];
  28466. var indexCount = subMeshesData[(i * 5) + 4];
  28467. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28468. }
  28469. }
  28470. }
  28471. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28472. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28473. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28474. if (parsedGeometry.uvs) {
  28475. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28476. }
  28477. if (parsedGeometry.uvs2) {
  28478. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28479. }
  28480. if (parsedGeometry.uvs3) {
  28481. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28482. }
  28483. if (parsedGeometry.uvs4) {
  28484. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28485. }
  28486. if (parsedGeometry.uvs5) {
  28487. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28488. }
  28489. if (parsedGeometry.uvs6) {
  28490. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28491. }
  28492. if (parsedGeometry.colors) {
  28493. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28494. }
  28495. if (parsedGeometry.matricesIndices) {
  28496. if (!parsedGeometry.matricesIndices._isExpanded) {
  28497. var floatIndices = [];
  28498. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28499. var matricesIndex = parsedGeometry.matricesIndices[i];
  28500. floatIndices.push(matricesIndex & 0x000000FF);
  28501. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28502. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28503. floatIndices.push(matricesIndex >> 24);
  28504. }
  28505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28506. }
  28507. else {
  28508. delete parsedGeometry.matricesIndices._isExpanded;
  28509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28510. }
  28511. }
  28512. if (parsedGeometry.matricesIndicesExtra) {
  28513. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28514. var floatIndices = [];
  28515. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28516. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28517. floatIndices.push(matricesIndex & 0x000000FF);
  28518. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28519. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28520. floatIndices.push(matricesIndex >> 24);
  28521. }
  28522. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28523. }
  28524. else {
  28525. delete parsedGeometry.matricesIndices._isExpanded;
  28526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28527. }
  28528. }
  28529. if (parsedGeometry.matricesWeights) {
  28530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28531. }
  28532. if (parsedGeometry.matricesWeightsExtra) {
  28533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28534. }
  28535. mesh.setIndices(parsedGeometry.indices);
  28536. }
  28537. // SubMeshes
  28538. if (parsedGeometry.subMeshes) {
  28539. mesh.subMeshes = [];
  28540. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28541. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28542. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28543. }
  28544. }
  28545. // Flat shading
  28546. if (mesh._shouldGenerateFlatShading) {
  28547. mesh.convertToFlatShadedMesh();
  28548. delete mesh._shouldGenerateFlatShading;
  28549. }
  28550. // Update
  28551. mesh.computeWorldMatrix(true);
  28552. // Octree
  28553. if (scene['_selectionOctree']) {
  28554. scene['_selectionOctree'].addMesh(mesh);
  28555. }
  28556. };
  28557. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28558. if (scene.getGeometryByID(parsedVertexData.id)) {
  28559. return null; // null since geometry could be something else than a box...
  28560. }
  28561. var geometry = new Geometry(parsedVertexData.id, scene);
  28562. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28563. if (parsedVertexData.delayLoadingFile) {
  28564. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28565. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28566. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28567. geometry._delayInfo = [];
  28568. if (parsedVertexData.hasUVs) {
  28569. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28570. }
  28571. if (parsedVertexData.hasUVs2) {
  28572. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28573. }
  28574. if (parsedVertexData.hasUVs3) {
  28575. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28576. }
  28577. if (parsedVertexData.hasUVs4) {
  28578. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28579. }
  28580. if (parsedVertexData.hasUVs5) {
  28581. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28582. }
  28583. if (parsedVertexData.hasUVs6) {
  28584. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28585. }
  28586. if (parsedVertexData.hasColors) {
  28587. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28588. }
  28589. if (parsedVertexData.hasMatricesIndices) {
  28590. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28591. }
  28592. if (parsedVertexData.hasMatricesWeights) {
  28593. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28594. }
  28595. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28596. }
  28597. else {
  28598. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28599. }
  28600. scene.pushGeometry(geometry, true);
  28601. return geometry;
  28602. };
  28603. return Geometry;
  28604. })();
  28605. BABYLON.Geometry = Geometry;
  28606. /////// Primitives //////////////////////////////////////////////
  28607. var Geometry;
  28608. (function (Geometry) {
  28609. var Primitives;
  28610. (function (Primitives) {
  28611. /// Abstract class
  28612. var _Primitive = (function (_super) {
  28613. __extends(_Primitive, _super);
  28614. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28615. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28616. this._canBeRegenerated = _canBeRegenerated;
  28617. this._beingRegenerated = true;
  28618. this.regenerate();
  28619. this._beingRegenerated = false;
  28620. }
  28621. _Primitive.prototype.canBeRegenerated = function () {
  28622. return this._canBeRegenerated;
  28623. };
  28624. _Primitive.prototype.regenerate = function () {
  28625. if (!this._canBeRegenerated) {
  28626. return;
  28627. }
  28628. this._beingRegenerated = true;
  28629. this.setAllVerticesData(this._regenerateVertexData(), false);
  28630. this._beingRegenerated = false;
  28631. };
  28632. _Primitive.prototype.asNewGeometry = function (id) {
  28633. return _super.prototype.copy.call(this, id);
  28634. };
  28635. // overrides
  28636. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28637. if (!this._beingRegenerated) {
  28638. return;
  28639. }
  28640. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28641. };
  28642. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28643. if (!this._beingRegenerated) {
  28644. return;
  28645. }
  28646. _super.prototype.setVerticesData.call(this, kind, data, false);
  28647. };
  28648. // to override
  28649. // protected
  28650. _Primitive.prototype._regenerateVertexData = function () {
  28651. throw new Error("Abstract method");
  28652. };
  28653. _Primitive.prototype.copy = function (id) {
  28654. throw new Error("Must be overriden in sub-classes.");
  28655. };
  28656. _Primitive.prototype.serialize = function () {
  28657. var serializationObject = _super.prototype.serialize.call(this);
  28658. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28659. return serializationObject;
  28660. };
  28661. return _Primitive;
  28662. })(Geometry);
  28663. Primitives._Primitive = _Primitive;
  28664. var Ribbon = (function (_super) {
  28665. __extends(Ribbon, _super);
  28666. // Members
  28667. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28669. _super.call(this, id, scene, canBeRegenerated, mesh);
  28670. this.pathArray = pathArray;
  28671. this.closeArray = closeArray;
  28672. this.closePath = closePath;
  28673. this.offset = offset;
  28674. this.side = side;
  28675. }
  28676. Ribbon.prototype._regenerateVertexData = function () {
  28677. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28678. };
  28679. Ribbon.prototype.copy = function (id) {
  28680. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28681. };
  28682. return Ribbon;
  28683. })(_Primitive);
  28684. Primitives.Ribbon = Ribbon;
  28685. var Box = (function (_super) {
  28686. __extends(Box, _super);
  28687. // Members
  28688. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28689. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28690. _super.call(this, id, scene, canBeRegenerated, mesh);
  28691. this.size = size;
  28692. this.side = side;
  28693. }
  28694. Box.prototype._regenerateVertexData = function () {
  28695. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28696. };
  28697. Box.prototype.copy = function (id) {
  28698. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28699. };
  28700. Box.prototype.serialize = function () {
  28701. var serializationObject = _super.prototype.serialize.call(this);
  28702. serializationObject.size = this.size;
  28703. return serializationObject;
  28704. };
  28705. Box.Parse = function (parsedBox, scene) {
  28706. if (scene.getGeometryByID(parsedBox.id)) {
  28707. return null; // null since geometry could be something else than a box...
  28708. }
  28709. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28710. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28711. scene.pushGeometry(box, true);
  28712. return box;
  28713. };
  28714. return Box;
  28715. })(_Primitive);
  28716. Primitives.Box = Box;
  28717. var Sphere = (function (_super) {
  28718. __extends(Sphere, _super);
  28719. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28720. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28721. _super.call(this, id, scene, canBeRegenerated, mesh);
  28722. this.segments = segments;
  28723. this.diameter = diameter;
  28724. this.side = side;
  28725. }
  28726. Sphere.prototype._regenerateVertexData = function () {
  28727. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28728. };
  28729. Sphere.prototype.copy = function (id) {
  28730. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28731. };
  28732. Sphere.prototype.serialize = function () {
  28733. var serializationObject = _super.prototype.serialize.call(this);
  28734. serializationObject.segments = this.segments;
  28735. serializationObject.diameter = this.diameter;
  28736. return serializationObject;
  28737. };
  28738. Sphere.Parse = function (parsedSphere, scene) {
  28739. if (scene.getGeometryByID(parsedSphere.id)) {
  28740. return null; // null since geometry could be something else than a sphere...
  28741. }
  28742. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28743. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28744. scene.pushGeometry(sphere, true);
  28745. return sphere;
  28746. };
  28747. return Sphere;
  28748. })(_Primitive);
  28749. Primitives.Sphere = Sphere;
  28750. var Disc = (function (_super) {
  28751. __extends(Disc, _super);
  28752. // Members
  28753. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28755. _super.call(this, id, scene, canBeRegenerated, mesh);
  28756. this.radius = radius;
  28757. this.tessellation = tessellation;
  28758. this.side = side;
  28759. }
  28760. Disc.prototype._regenerateVertexData = function () {
  28761. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28762. };
  28763. Disc.prototype.copy = function (id) {
  28764. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28765. };
  28766. return Disc;
  28767. })(_Primitive);
  28768. Primitives.Disc = Disc;
  28769. var Cylinder = (function (_super) {
  28770. __extends(Cylinder, _super);
  28771. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28772. if (subdivisions === void 0) { subdivisions = 1; }
  28773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28774. _super.call(this, id, scene, canBeRegenerated, mesh);
  28775. this.height = height;
  28776. this.diameterTop = diameterTop;
  28777. this.diameterBottom = diameterBottom;
  28778. this.tessellation = tessellation;
  28779. this.subdivisions = subdivisions;
  28780. this.side = side;
  28781. }
  28782. Cylinder.prototype._regenerateVertexData = function () {
  28783. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28784. };
  28785. Cylinder.prototype.copy = function (id) {
  28786. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28787. };
  28788. Cylinder.prototype.serialize = function () {
  28789. var serializationObject = _super.prototype.serialize.call(this);
  28790. serializationObject.height = this.height;
  28791. serializationObject.diameterTop = this.diameterTop;
  28792. serializationObject.diameterBottom = this.diameterBottom;
  28793. serializationObject.tessellation = this.tessellation;
  28794. return serializationObject;
  28795. };
  28796. Cylinder.Parse = function (parsedCylinder, scene) {
  28797. if (scene.getGeometryByID(parsedCylinder.id)) {
  28798. return null; // null since geometry could be something else than a cylinder...
  28799. }
  28800. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28801. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28802. scene.pushGeometry(cylinder, true);
  28803. return cylinder;
  28804. };
  28805. return Cylinder;
  28806. })(_Primitive);
  28807. Primitives.Cylinder = Cylinder;
  28808. var Torus = (function (_super) {
  28809. __extends(Torus, _super);
  28810. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28812. _super.call(this, id, scene, canBeRegenerated, mesh);
  28813. this.diameter = diameter;
  28814. this.thickness = thickness;
  28815. this.tessellation = tessellation;
  28816. this.side = side;
  28817. }
  28818. Torus.prototype._regenerateVertexData = function () {
  28819. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28820. };
  28821. Torus.prototype.copy = function (id) {
  28822. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28823. };
  28824. Torus.prototype.serialize = function () {
  28825. var serializationObject = _super.prototype.serialize.call(this);
  28826. serializationObject.diameter = this.diameter;
  28827. serializationObject.thickness = this.thickness;
  28828. serializationObject.tessellation = this.tessellation;
  28829. return serializationObject;
  28830. };
  28831. Torus.Parse = function (parsedTorus, scene) {
  28832. if (scene.getGeometryByID(parsedTorus.id)) {
  28833. return null; // null since geometry could be something else than a torus...
  28834. }
  28835. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28836. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28837. scene.pushGeometry(torus, true);
  28838. return torus;
  28839. };
  28840. return Torus;
  28841. })(_Primitive);
  28842. Primitives.Torus = Torus;
  28843. var Ground = (function (_super) {
  28844. __extends(Ground, _super);
  28845. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28846. _super.call(this, id, scene, canBeRegenerated, mesh);
  28847. this.width = width;
  28848. this.height = height;
  28849. this.subdivisions = subdivisions;
  28850. }
  28851. Ground.prototype._regenerateVertexData = function () {
  28852. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28853. };
  28854. Ground.prototype.copy = function (id) {
  28855. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28856. };
  28857. Ground.prototype.serialize = function () {
  28858. var serializationObject = _super.prototype.serialize.call(this);
  28859. serializationObject.width = this.width;
  28860. serializationObject.height = this.height;
  28861. serializationObject.subdivisions = this.subdivisions;
  28862. return serializationObject;
  28863. };
  28864. Ground.Parse = function (parsedGround, scene) {
  28865. if (scene.getGeometryByID(parsedGround.id)) {
  28866. return null; // null since geometry could be something else than a ground...
  28867. }
  28868. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28869. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28870. scene.pushGeometry(ground, true);
  28871. return ground;
  28872. };
  28873. return Ground;
  28874. })(_Primitive);
  28875. Primitives.Ground = Ground;
  28876. var TiledGround = (function (_super) {
  28877. __extends(TiledGround, _super);
  28878. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28879. _super.call(this, id, scene, canBeRegenerated, mesh);
  28880. this.xmin = xmin;
  28881. this.zmin = zmin;
  28882. this.xmax = xmax;
  28883. this.zmax = zmax;
  28884. this.subdivisions = subdivisions;
  28885. this.precision = precision;
  28886. }
  28887. TiledGround.prototype._regenerateVertexData = function () {
  28888. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28889. };
  28890. TiledGround.prototype.copy = function (id) {
  28891. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28892. };
  28893. return TiledGround;
  28894. })(_Primitive);
  28895. Primitives.TiledGround = TiledGround;
  28896. var Plane = (function (_super) {
  28897. __extends(Plane, _super);
  28898. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28900. _super.call(this, id, scene, canBeRegenerated, mesh);
  28901. this.size = size;
  28902. this.side = side;
  28903. }
  28904. Plane.prototype._regenerateVertexData = function () {
  28905. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28906. };
  28907. Plane.prototype.copy = function (id) {
  28908. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28909. };
  28910. Plane.prototype.serialize = function () {
  28911. var serializationObject = _super.prototype.serialize.call(this);
  28912. serializationObject.size = this.size;
  28913. return serializationObject;
  28914. };
  28915. Plane.Parse = function (parsedPlane, scene) {
  28916. if (scene.getGeometryByID(parsedPlane.id)) {
  28917. return null; // null since geometry could be something else than a ground...
  28918. }
  28919. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28920. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28921. scene.pushGeometry(plane, true);
  28922. return plane;
  28923. };
  28924. return Plane;
  28925. })(_Primitive);
  28926. Primitives.Plane = Plane;
  28927. var TorusKnot = (function (_super) {
  28928. __extends(TorusKnot, _super);
  28929. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28931. _super.call(this, id, scene, canBeRegenerated, mesh);
  28932. this.radius = radius;
  28933. this.tube = tube;
  28934. this.radialSegments = radialSegments;
  28935. this.tubularSegments = tubularSegments;
  28936. this.p = p;
  28937. this.q = q;
  28938. this.side = side;
  28939. }
  28940. TorusKnot.prototype._regenerateVertexData = function () {
  28941. 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 });
  28942. };
  28943. TorusKnot.prototype.copy = function (id) {
  28944. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28945. };
  28946. TorusKnot.prototype.serialize = function () {
  28947. var serializationObject = _super.prototype.serialize.call(this);
  28948. serializationObject.radius = this.radius;
  28949. serializationObject.tube = this.tube;
  28950. serializationObject.radialSegments = this.radialSegments;
  28951. serializationObject.tubularSegments = this.tubularSegments;
  28952. serializationObject.p = this.p;
  28953. serializationObject.q = this.q;
  28954. return serializationObject;
  28955. };
  28956. ;
  28957. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28958. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28959. return null; // null since geometry could be something else than a ground...
  28960. }
  28961. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28962. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28963. scene.pushGeometry(torusKnot, true);
  28964. return torusKnot;
  28965. };
  28966. return TorusKnot;
  28967. })(_Primitive);
  28968. Primitives.TorusKnot = TorusKnot;
  28969. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28970. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28971. })(BABYLON || (BABYLON = {}));
  28972. var BABYLON;
  28973. (function (BABYLON) {
  28974. var GroundMesh = (function (_super) {
  28975. __extends(GroundMesh, _super);
  28976. function GroundMesh(name, scene) {
  28977. _super.call(this, name, scene);
  28978. this.generateOctree = false;
  28979. this._worldInverse = new BABYLON.Matrix();
  28980. }
  28981. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28982. get: function () {
  28983. return this._subdivisions;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28989. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28990. this._subdivisions = chunksCount;
  28991. this.subdivide(this._subdivisions);
  28992. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28993. };
  28994. /**
  28995. * Returns a height (y) value in the Worl system :
  28996. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28997. * Returns the ground y position if (x, z) are outside the ground surface.
  28998. * Not pertinent if the ground is rotated.
  28999. */
  29000. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29001. // express x and y in the ground local system
  29002. x -= this.position.x;
  29003. z -= this.position.z;
  29004. x /= this.scaling.x;
  29005. z /= this.scaling.z;
  29006. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  29007. return this.position.y;
  29008. }
  29009. if (!this._heightQuads || this._heightQuads.length == 0) {
  29010. this._initHeightQuads();
  29011. this._computeHeightQuads();
  29012. }
  29013. var facet = this._getFacetAt(x, z);
  29014. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  29015. // return y in the World system
  29016. return y * this.scaling.y + this.position.y;
  29017. };
  29018. /**
  29019. * Returns a normalized vector (Vector3) orthogonal to the ground
  29020. * at the ground coordinates (x, z) expressed in the World system.
  29021. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  29022. * Not pertinent if the ground is rotated.
  29023. */
  29024. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  29025. var normal = new BABYLON.Vector3(0, 1, 0);
  29026. this.getNormalAtCoordinatesToRef(x, z, normal);
  29027. return normal;
  29028. };
  29029. /**
  29030. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  29031. * at the ground coordinates (x, z) expressed in the World system.
  29032. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  29033. * Not pertinent if the ground is rotated.
  29034. */
  29035. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  29036. // express x and y in the ground local system
  29037. x -= this.position.x;
  29038. z -= this.position.z;
  29039. x /= this.scaling.x;
  29040. z /= this.scaling.z;
  29041. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  29042. return;
  29043. }
  29044. if (!this._heightQuads || this._heightQuads.length == 0) {
  29045. this._initHeightQuads();
  29046. this._computeHeightQuads();
  29047. }
  29048. var facet = this._getFacetAt(x, z);
  29049. ref.x = facet.x;
  29050. ref.y = facet.y;
  29051. ref.z = facet.z;
  29052. };
  29053. /**
  29054. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  29055. * if the ground has been updated.
  29056. * This can be used in the render loop
  29057. */
  29058. GroundMesh.prototype.updateCoordinateHeights = function () {
  29059. if (!this._heightQuads || this._heightQuads.length == 0) {
  29060. this._initHeightQuads();
  29061. }
  29062. this._computeHeightQuads();
  29063. };
  29064. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  29065. GroundMesh.prototype._getFacetAt = function (x, z) {
  29066. // retrieve col and row from x, z coordinates in the ground local system
  29067. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  29068. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  29069. var quad = this._heightQuads[row * this._subdivisions + col];
  29070. var facet;
  29071. if (z < quad.slope.x * x + quad.slope.y) {
  29072. facet = quad.facet1;
  29073. }
  29074. else {
  29075. facet = quad.facet2;
  29076. }
  29077. return facet;
  29078. };
  29079. // Creates and populates the heightMap array with "facet" elements :
  29080. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  29081. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29082. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29083. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29084. GroundMesh.prototype._initHeightQuads = function () {
  29085. this._heightQuads = new Array();
  29086. for (var row = 0; row < this._subdivisions; row++) {
  29087. for (var col = 0; col < this._subdivisions; col++) {
  29088. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  29089. this._heightQuads[row * this._subdivisions + col] = quad;
  29090. }
  29091. }
  29092. };
  29093. // Compute each quad element values and update the the heightMap array :
  29094. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29095. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29096. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29097. GroundMesh.prototype._computeHeightQuads = function () {
  29098. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29099. var v1 = BABYLON.Tmp.Vector3[0];
  29100. var v2 = BABYLON.Tmp.Vector3[1];
  29101. var v3 = BABYLON.Tmp.Vector3[2];
  29102. var v4 = BABYLON.Tmp.Vector3[3];
  29103. var v1v2 = BABYLON.Tmp.Vector3[4];
  29104. var v1v3 = BABYLON.Tmp.Vector3[5];
  29105. var v1v4 = BABYLON.Tmp.Vector3[6];
  29106. var norm1 = BABYLON.Tmp.Vector3[7];
  29107. var norm2 = BABYLON.Tmp.Vector3[8];
  29108. var i = 0;
  29109. var j = 0;
  29110. var k = 0;
  29111. var cd = 0; // 2D slope coefficient : z = cd * x + h
  29112. var h = 0;
  29113. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  29114. var d2 = 0;
  29115. for (var row = 0; row < this._subdivisions; row++) {
  29116. for (var col = 0; col < this._subdivisions; col++) {
  29117. i = col * 3;
  29118. j = row * (this._subdivisions + 1) * 3;
  29119. k = (row + 1) * (this._subdivisions + 1) * 3;
  29120. v1.x = positions[j + i];
  29121. v1.y = positions[j + i + 1];
  29122. v1.z = positions[j + i + 2];
  29123. v2.x = positions[j + i + 3];
  29124. v2.y = positions[j + i + 4];
  29125. v2.z = positions[j + i + 5];
  29126. v3.x = positions[k + i];
  29127. v3.y = positions[k + i + 1];
  29128. v3.z = positions[k + i + 2];
  29129. v4.x = positions[k + i + 3];
  29130. v4.y = positions[k + i + 4];
  29131. v4.z = positions[k + i + 5];
  29132. // 2D slope V1V4
  29133. cd = (v4.z - v1.z) / (v4.x - v1.x);
  29134. h = v1.z - cd * v1.x; // v1 belongs to the slope
  29135. // facet equations :
  29136. // we compute each facet normal vector
  29137. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  29138. // we compute the value d by applying the equation to v1 which belongs to the plane
  29139. // then we store the facet equation in a Vector4
  29140. v2.subtractToRef(v1, v1v2);
  29141. v3.subtractToRef(v1, v1v3);
  29142. v4.subtractToRef(v1, v1v4);
  29143. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  29144. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  29145. norm1.normalize();
  29146. norm2.normalize();
  29147. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  29148. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  29149. var quad = this._heightQuads[row * this._subdivisions + col];
  29150. quad.slope.copyFromFloats(cd, h);
  29151. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  29152. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  29153. }
  29154. }
  29155. };
  29156. return GroundMesh;
  29157. })(BABYLON.Mesh);
  29158. BABYLON.GroundMesh = GroundMesh;
  29159. })(BABYLON || (BABYLON = {}));
  29160. var BABYLON;
  29161. (function (BABYLON) {
  29162. var LinesMesh = (function (_super) {
  29163. __extends(LinesMesh, _super);
  29164. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29165. if (parent === void 0) { parent = null; }
  29166. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29167. this.color = new BABYLON.Color3(1, 1, 1);
  29168. this.alpha = 1;
  29169. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29170. attributes: ["position"],
  29171. uniforms: ["worldViewProjection", "color"],
  29172. needAlphaBlending: true
  29173. });
  29174. }
  29175. Object.defineProperty(LinesMesh.prototype, "material", {
  29176. get: function () {
  29177. return this._colorShader;
  29178. },
  29179. enumerable: true,
  29180. configurable: true
  29181. });
  29182. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29183. get: function () {
  29184. return false;
  29185. },
  29186. enumerable: true,
  29187. configurable: true
  29188. });
  29189. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29190. get: function () {
  29191. return false;
  29192. },
  29193. enumerable: true,
  29194. configurable: true
  29195. });
  29196. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29197. var engine = this.getScene().getEngine();
  29198. var indexToBind = this._geometry.getIndexBuffer();
  29199. // VBOs
  29200. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29201. // Color
  29202. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29203. };
  29204. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29205. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29206. return;
  29207. }
  29208. var engine = this.getScene().getEngine();
  29209. // Draw order
  29210. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29211. };
  29212. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29213. return null;
  29214. };
  29215. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29216. this._colorShader.dispose();
  29217. _super.prototype.dispose.call(this, doNotRecurse);
  29218. };
  29219. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29220. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29221. };
  29222. return LinesMesh;
  29223. })(BABYLON.Mesh);
  29224. BABYLON.LinesMesh = LinesMesh;
  29225. })(BABYLON || (BABYLON = {}));
  29226. var BABYLON;
  29227. (function (BABYLON) {
  29228. var DebugLayer = (function () {
  29229. function DebugLayer(scene) {
  29230. var _this = this;
  29231. this._transformationMatrix = BABYLON.Matrix.Identity();
  29232. this._enabled = false;
  29233. this._labelsEnabled = false;
  29234. this._displayStatistics = true;
  29235. this._displayTree = false;
  29236. this._displayLogs = false;
  29237. this._skeletonViewers = new Array();
  29238. this._identityMatrix = BABYLON.Matrix.Identity();
  29239. this.axisRatio = 0.02;
  29240. this.accentColor = "orange";
  29241. this._scene = scene;
  29242. this._syncPositions = function () {
  29243. var engine = _this._scene.getEngine();
  29244. var canvasRect = engine.getRenderingCanvasClientRect();
  29245. if (_this._showUI) {
  29246. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29247. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29248. _this._statsDiv.style.width = "400px";
  29249. _this._statsDiv.style.height = "auto";
  29250. _this._statsSubsetDiv.style.maxHeight = "240px";
  29251. _this._optionsDiv.style.left = "0px";
  29252. _this._optionsDiv.style.top = "10px";
  29253. _this._optionsDiv.style.width = "200px";
  29254. _this._optionsDiv.style.height = "auto";
  29255. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29256. _this._logDiv.style.left = "0px";
  29257. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29258. _this._logDiv.style.width = "600px";
  29259. _this._logDiv.style.height = "160px";
  29260. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29261. _this._treeDiv.style.top = "10px";
  29262. _this._treeDiv.style.width = "300px";
  29263. _this._treeDiv.style.height = "auto";
  29264. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29265. }
  29266. _this._globalDiv.style.left = canvasRect.left + "px";
  29267. _this._globalDiv.style.top = canvasRect.top + "px";
  29268. _this._drawingCanvas.style.left = "0px";
  29269. _this._drawingCanvas.style.top = "0px";
  29270. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29271. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29272. var devicePixelRatio = window.devicePixelRatio || 1;
  29273. var context = _this._drawingContext;
  29274. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29275. context.mozBackingStorePixelRatio ||
  29276. context.msBackingStorePixelRatio ||
  29277. context.oBackingStorePixelRatio ||
  29278. context.backingStorePixelRatio || 1;
  29279. _this._ratio = devicePixelRatio / backingStoreRatio;
  29280. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29281. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29282. };
  29283. this._onCanvasClick = function (evt) {
  29284. _this._clickPosition = {
  29285. x: evt.clientX * _this._ratio,
  29286. y: evt.clientY * _this._ratio
  29287. };
  29288. };
  29289. this._syncUI = function () {
  29290. if (_this._showUI) {
  29291. if (_this._displayStatistics) {
  29292. _this._displayStats();
  29293. _this._statsDiv.style.display = "";
  29294. }
  29295. else {
  29296. _this._statsDiv.style.display = "none";
  29297. }
  29298. if (_this._displayLogs) {
  29299. _this._logDiv.style.display = "";
  29300. }
  29301. else {
  29302. _this._logDiv.style.display = "none";
  29303. }
  29304. if (_this._displayTree) {
  29305. _this._treeDiv.style.display = "";
  29306. if (_this._needToRefreshMeshesTree) {
  29307. _this._needToRefreshMeshesTree = false;
  29308. _this._refreshMeshesTreeContent();
  29309. }
  29310. }
  29311. else {
  29312. _this._treeDiv.style.display = "none";
  29313. }
  29314. }
  29315. };
  29316. this._syncData = function () {
  29317. if (_this._labelsEnabled || !_this._showUI) {
  29318. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29319. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29320. var engine = _this._scene.getEngine();
  29321. var viewport = _this._camera.viewport;
  29322. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29323. // Meshes
  29324. var meshes = _this._camera.getActiveMeshes();
  29325. var index;
  29326. var projectedPosition;
  29327. for (index = 0; index < meshes.length; index++) {
  29328. var mesh = meshes.data[index];
  29329. var position = mesh.getBoundingInfo().boundingSphere.center;
  29330. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29331. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29332. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29333. }
  29334. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29335. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29336. }
  29337. }
  29338. // Cameras
  29339. var cameras = _this._scene.cameras;
  29340. for (index = 0; index < cameras.length; index++) {
  29341. var camera = cameras[index];
  29342. if (camera === _this._camera) {
  29343. continue;
  29344. }
  29345. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29346. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29347. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29348. _this._camera.detachControl(engine.getRenderingCanvas());
  29349. _this._camera = camera;
  29350. _this._camera.attachControl(engine.getRenderingCanvas());
  29351. }, function () { return "purple"; });
  29352. }
  29353. }
  29354. // Lights
  29355. var lights = _this._scene.lights;
  29356. for (index = 0; index < lights.length; index++) {
  29357. var light = lights[index];
  29358. if (light.position) {
  29359. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29360. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29361. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29362. light.setEnabled(!light.isEnabled());
  29363. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29364. }
  29365. }
  29366. }
  29367. }
  29368. _this._clickPosition = undefined;
  29369. };
  29370. }
  29371. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29372. while (this._treeSubsetDiv.hasChildNodes()) {
  29373. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29374. }
  29375. // Add meshes
  29376. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29377. sortedArray.sort(function (a, b) {
  29378. if (a.name === b.name) {
  29379. return 0;
  29380. }
  29381. return (a.name > b.name) ? 1 : -1;
  29382. });
  29383. for (var index = 0; index < sortedArray.length; index++) {
  29384. var mesh = sortedArray[index];
  29385. if (!mesh.isEnabled()) {
  29386. continue;
  29387. }
  29388. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29389. m.isVisible = element.checked;
  29390. }, mesh);
  29391. }
  29392. };
  29393. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29394. this._drawingContext.beginPath();
  29395. this._drawingContext.moveTo(zero.x, zero.y);
  29396. this._drawingContext.lineTo(unit.x, unit.y);
  29397. this._drawingContext.strokeStyle = color;
  29398. this._drawingContext.lineWidth = 4;
  29399. this._drawingContext.stroke();
  29400. this._drawingContext.font = "normal 14px Segoe UI";
  29401. this._drawingContext.fillStyle = color;
  29402. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29403. };
  29404. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29405. var position = mesh.getBoundingInfo().boundingSphere.center;
  29406. var worldMatrix = mesh.getWorldMatrix();
  29407. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29408. var unit = (unprojectedVector.subtract(position)).length();
  29409. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29410. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29411. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29412. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29413. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29414. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29415. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29416. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29417. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29418. };
  29419. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29420. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29421. this._drawingContext.font = "normal 12px Segoe UI";
  29422. var textMetrics = this._drawingContext.measureText(text);
  29423. var centerX = projectedPosition.x - textMetrics.width / 2;
  29424. var centerY = projectedPosition.y;
  29425. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29426. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29427. onClick();
  29428. }
  29429. this._drawingContext.beginPath();
  29430. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29431. this._drawingContext.fillStyle = getFillStyle();
  29432. this._drawingContext.globalAlpha = 0.5;
  29433. this._drawingContext.fill();
  29434. this._drawingContext.globalAlpha = 1.0;
  29435. this._drawingContext.strokeStyle = '#FFFFFF';
  29436. this._drawingContext.lineWidth = 1;
  29437. this._drawingContext.stroke();
  29438. this._drawingContext.fillStyle = "#FFFFFF";
  29439. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29440. this._drawingContext.beginPath();
  29441. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29442. this._drawingContext.fill();
  29443. }
  29444. };
  29445. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29446. if (!this._clickPosition) {
  29447. return false;
  29448. }
  29449. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29450. return false;
  29451. }
  29452. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29453. return false;
  29454. }
  29455. return true;
  29456. };
  29457. DebugLayer.prototype.isVisible = function () {
  29458. return this._enabled;
  29459. };
  29460. DebugLayer.prototype.hide = function () {
  29461. if (!this._enabled) {
  29462. return;
  29463. }
  29464. this._enabled = false;
  29465. var engine = this._scene.getEngine();
  29466. this._scene.unregisterBeforeRender(this._syncData);
  29467. this._scene.unregisterAfterRender(this._syncUI);
  29468. this._rootElement.removeChild(this._globalDiv);
  29469. this._scene.forceShowBoundingBoxes = false;
  29470. this._scene.forceWireframe = false;
  29471. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29472. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29473. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29474. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29475. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29476. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29477. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29478. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29479. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29480. this._scene.shadowsEnabled = true;
  29481. this._scene.particlesEnabled = true;
  29482. this._scene.postProcessesEnabled = true;
  29483. this._scene.collisionsEnabled = true;
  29484. this._scene.lightsEnabled = true;
  29485. this._scene.texturesEnabled = true;
  29486. this._scene.lensFlaresEnabled = true;
  29487. this._scene.proceduralTexturesEnabled = true;
  29488. this._scene.renderTargetsEnabled = true;
  29489. this._scene.probesEnabled = true;
  29490. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29491. this._clearSkeletonViewers();
  29492. };
  29493. DebugLayer.prototype._clearSkeletonViewers = function () {
  29494. for (var index = 0; index < this._skeletonViewers.length; index++) {
  29495. this._skeletonViewers[index].dispose();
  29496. }
  29497. this._skeletonViewers = [];
  29498. };
  29499. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29500. if (showUI === void 0) { showUI = true; }
  29501. if (camera === void 0) { camera = null; }
  29502. if (rootElement === void 0) { rootElement = null; }
  29503. if (this._enabled) {
  29504. return;
  29505. }
  29506. this._enabled = true;
  29507. if (camera) {
  29508. this._camera = camera;
  29509. }
  29510. else {
  29511. this._camera = this._scene.activeCamera;
  29512. }
  29513. this._showUI = showUI;
  29514. var engine = this._scene.getEngine();
  29515. this._globalDiv = document.createElement("div");
  29516. this._rootElement = rootElement || document.body;
  29517. this._rootElement.appendChild(this._globalDiv);
  29518. this._generateDOMelements();
  29519. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29520. this._syncPositions();
  29521. this._scene.registerBeforeRender(this._syncData);
  29522. this._scene.registerAfterRender(this._syncUI);
  29523. };
  29524. DebugLayer.prototype._clearLabels = function () {
  29525. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29526. for (var index = 0; index < this._scene.meshes.length; index++) {
  29527. var mesh = this._scene.meshes[index];
  29528. mesh.renderOverlay = false;
  29529. }
  29530. };
  29531. DebugLayer.prototype._generateheader = function (root, text) {
  29532. var header = document.createElement("div");
  29533. header.innerHTML = text + "&nbsp;";
  29534. header.style.textAlign = "right";
  29535. header.style.width = "100%";
  29536. header.style.color = "white";
  29537. header.style.backgroundColor = "Black";
  29538. header.style.padding = "5px 5px 4px 0px";
  29539. header.style.marginLeft = "-5px";
  29540. header.style.fontWeight = "bold";
  29541. root.appendChild(header);
  29542. };
  29543. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29544. var label = document.createElement("label");
  29545. label.innerHTML = title;
  29546. label.style.color = color;
  29547. root.appendChild(label);
  29548. root.appendChild(document.createElement("br"));
  29549. };
  29550. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29551. if (tag === void 0) { tag = null; }
  29552. var label = document.createElement("label");
  29553. var boundingBoxesCheckbox = document.createElement("input");
  29554. boundingBoxesCheckbox.type = "checkbox";
  29555. boundingBoxesCheckbox.checked = initialState;
  29556. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29557. task(evt.target, tag);
  29558. });
  29559. label.appendChild(boundingBoxesCheckbox);
  29560. var container = document.createElement("span");
  29561. var leftPart = document.createElement("span");
  29562. var rightPart = document.createElement("span");
  29563. rightPart.style.cssFloat = "right";
  29564. leftPart.innerHTML = leftTitle;
  29565. rightPart.innerHTML = rightTitle;
  29566. rightPart.style.fontSize = "12px";
  29567. rightPart.style.maxWidth = "200px";
  29568. container.appendChild(leftPart);
  29569. container.appendChild(rightPart);
  29570. label.appendChild(container);
  29571. root.appendChild(label);
  29572. root.appendChild(document.createElement("br"));
  29573. };
  29574. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29575. if (tag === void 0) { tag = null; }
  29576. var label = document.createElement("label");
  29577. var checkBox = document.createElement("input");
  29578. checkBox.type = "checkbox";
  29579. checkBox.checked = initialState;
  29580. checkBox.addEventListener("change", function (evt) {
  29581. task(evt.target, tag);
  29582. });
  29583. label.appendChild(checkBox);
  29584. label.appendChild(document.createTextNode(title));
  29585. root.appendChild(label);
  29586. root.appendChild(document.createElement("br"));
  29587. };
  29588. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29589. if (tag === void 0) { tag = null; }
  29590. var button = document.createElement("button");
  29591. button.innerHTML = title;
  29592. button.style.height = "24px";
  29593. button.style.width = "150px";
  29594. button.style.marginBottom = "5px";
  29595. button.style.color = "#444444";
  29596. button.style.border = "1px solid white";
  29597. button.className = "debugLayerButton";
  29598. button.addEventListener("click", function (evt) {
  29599. task(evt.target, tag);
  29600. });
  29601. root.appendChild(button);
  29602. root.appendChild(document.createElement("br"));
  29603. };
  29604. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29605. if (tag === void 0) { tag = null; }
  29606. var label = document.createElement("label");
  29607. var boundingBoxesRadio = document.createElement("input");
  29608. boundingBoxesRadio.type = "radio";
  29609. boundingBoxesRadio.name = name;
  29610. boundingBoxesRadio.checked = initialState;
  29611. boundingBoxesRadio.addEventListener("change", function (evt) {
  29612. task(evt.target, tag);
  29613. });
  29614. label.appendChild(boundingBoxesRadio);
  29615. label.appendChild(document.createTextNode(title));
  29616. root.appendChild(label);
  29617. root.appendChild(document.createElement("br"));
  29618. };
  29619. DebugLayer.prototype._generateDOMelements = function () {
  29620. var _this = this;
  29621. this._globalDiv.id = "DebugLayer";
  29622. this._globalDiv.style.position = "absolute";
  29623. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29624. this._globalDiv.style.fontSize = "14px";
  29625. this._globalDiv.style.color = "white";
  29626. // Drawing canvas
  29627. this._drawingCanvas = document.createElement("canvas");
  29628. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29629. this._drawingCanvas.style.position = "absolute";
  29630. this._drawingCanvas.style.pointerEvents = "none";
  29631. this._drawingCanvas.style.backgroundColor = "transparent";
  29632. this._drawingContext = this._drawingCanvas.getContext("2d");
  29633. this._globalDiv.appendChild(this._drawingCanvas);
  29634. if (this._showUI) {
  29635. var background = "rgba(128, 128, 128, 0.4)";
  29636. var border = "rgb(180, 180, 180) solid 1px";
  29637. // Stats
  29638. this._statsDiv = document.createElement("div");
  29639. this._statsDiv.id = "DebugLayerStats";
  29640. this._statsDiv.style.border = border;
  29641. this._statsDiv.style.position = "absolute";
  29642. this._statsDiv.style.background = background;
  29643. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29644. this._generateheader(this._statsDiv, "STATISTICS");
  29645. this._statsSubsetDiv = document.createElement("div");
  29646. this._statsSubsetDiv.style.paddingTop = "5px";
  29647. this._statsSubsetDiv.style.paddingBottom = "5px";
  29648. this._statsSubsetDiv.style.overflowY = "auto";
  29649. this._statsDiv.appendChild(this._statsSubsetDiv);
  29650. // Tree
  29651. this._treeDiv = document.createElement("div");
  29652. this._treeDiv.id = "DebugLayerTree";
  29653. this._treeDiv.style.border = border;
  29654. this._treeDiv.style.position = "absolute";
  29655. this._treeDiv.style.background = background;
  29656. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29657. this._treeDiv.style.display = "none";
  29658. this._generateheader(this._treeDiv, "MESHES TREE");
  29659. this._treeSubsetDiv = document.createElement("div");
  29660. this._treeSubsetDiv.style.paddingTop = "5px";
  29661. this._treeSubsetDiv.style.paddingRight = "5px";
  29662. this._treeSubsetDiv.style.overflowY = "auto";
  29663. this._treeSubsetDiv.style.maxHeight = "300px";
  29664. this._treeDiv.appendChild(this._treeSubsetDiv);
  29665. this._needToRefreshMeshesTree = true;
  29666. // Logs
  29667. this._logDiv = document.createElement("div");
  29668. this._logDiv.style.border = border;
  29669. this._logDiv.id = "DebugLayerLogs";
  29670. this._logDiv.style.position = "absolute";
  29671. this._logDiv.style.background = background;
  29672. this._logDiv.style.padding = "0px 0px 0px 5px";
  29673. this._logDiv.style.display = "none";
  29674. this._generateheader(this._logDiv, "LOGS");
  29675. this._logSubsetDiv = document.createElement("div");
  29676. this._logSubsetDiv.style.height = "127px";
  29677. this._logSubsetDiv.style.paddingTop = "5px";
  29678. this._logSubsetDiv.style.overflowY = "auto";
  29679. this._logSubsetDiv.style.fontSize = "12px";
  29680. this._logSubsetDiv.style.fontFamily = "consolas";
  29681. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29682. this._logDiv.appendChild(this._logSubsetDiv);
  29683. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29684. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29685. };
  29686. // Options
  29687. this._optionsDiv = document.createElement("div");
  29688. this._optionsDiv.id = "DebugLayerOptions";
  29689. this._optionsDiv.style.border = border;
  29690. this._optionsDiv.style.position = "absolute";
  29691. this._optionsDiv.style.background = background;
  29692. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29693. this._optionsDiv.style.overflowY = "auto";
  29694. this._generateheader(this._optionsDiv, "OPTIONS");
  29695. this._optionsSubsetDiv = document.createElement("div");
  29696. this._optionsSubsetDiv.style.paddingTop = "5px";
  29697. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29698. this._optionsSubsetDiv.style.overflowY = "auto";
  29699. this._optionsSubsetDiv.style.maxHeight = "200px";
  29700. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29701. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29702. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29703. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29704. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29705. _this._displayTree = element.checked;
  29706. _this._needToRefreshMeshesTree = true;
  29707. });
  29708. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29709. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29710. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29711. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29712. _this._labelsEnabled = element.checked;
  29713. if (!_this._labelsEnabled) {
  29714. _this._clearLabels();
  29715. }
  29716. });
  29717. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29718. if (element.checked) {
  29719. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29720. }
  29721. else {
  29722. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29723. }
  29724. });
  29725. ;
  29726. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29727. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29728. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29729. if (element.checked) {
  29730. _this._scene.forceWireframe = false;
  29731. _this._scene.forcePointsCloud = false;
  29732. }
  29733. });
  29734. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29735. if (element.checked) {
  29736. _this._scene.forceWireframe = true;
  29737. _this._scene.forcePointsCloud = false;
  29738. }
  29739. });
  29740. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29741. if (element.checked) {
  29742. _this._scene.forceWireframe = false;
  29743. _this._scene.forcePointsCloud = true;
  29744. }
  29745. });
  29746. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29747. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29748. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29749. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29750. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29751. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29752. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29753. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29754. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29755. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29756. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29757. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29758. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29759. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29760. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29761. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29762. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29763. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29764. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29765. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29766. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29767. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29768. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29769. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29770. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29771. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29772. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29773. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29774. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29775. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29776. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29777. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29778. if (element.checked) {
  29779. _this._scene.headphone = true;
  29780. }
  29781. });
  29782. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29783. if (element.checked) {
  29784. _this._scene.headphone = false;
  29785. }
  29786. });
  29787. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29788. _this._scene.audioEnabled = !element.checked;
  29789. });
  29790. }
  29791. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29792. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  29793. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  29794. if (!element.checked) {
  29795. _this._clearSkeletonViewers();
  29796. return;
  29797. }
  29798. for (var index = 0; index < _this._scene.meshes.length; index++) {
  29799. var mesh = _this._scene.meshes[index];
  29800. if (mesh.skeleton) {
  29801. var found = false;
  29802. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  29803. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  29804. found = true;
  29805. break;
  29806. }
  29807. }
  29808. if (found) {
  29809. continue;
  29810. }
  29811. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  29812. viewer.isEnabled = true;
  29813. _this._skeletonViewers.push(viewer);
  29814. }
  29815. }
  29816. });
  29817. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29818. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29819. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29820. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29821. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29822. if (_this._camera) {
  29823. console.log(_this._camera);
  29824. }
  29825. else {
  29826. console.warn("No camera defined, or debug layer created before camera creation!");
  29827. }
  29828. });
  29829. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29830. this._globalDiv.appendChild(this._statsDiv);
  29831. this._globalDiv.appendChild(this._logDiv);
  29832. this._globalDiv.appendChild(this._optionsDiv);
  29833. this._globalDiv.appendChild(this._treeDiv);
  29834. }
  29835. };
  29836. DebugLayer.prototype._displayStats = function () {
  29837. var scene = this._scene;
  29838. var engine = scene.getEngine();
  29839. var glInfo = engine.getGlInfo();
  29840. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29841. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29842. + "<b>Count</b><br>"
  29843. + "Total meshes: " + scene.meshes.length + "<br>"
  29844. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29845. + "Total materials: " + scene.materials.length + "<br>"
  29846. + "Total textures: " + scene.textures.length + "<br>"
  29847. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29848. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29849. + "Active bones: " + scene.getActiveBones() + "<br>"
  29850. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29851. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29852. + "<b>Duration</b><br>"
  29853. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29854. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29855. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29856. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29857. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29858. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29859. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29860. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29861. + "</div>"
  29862. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29863. + "<b>Extensions</b><br>"
  29864. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29865. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29866. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29867. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29868. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29869. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29870. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29871. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29872. + "</div><br>"
  29873. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29874. + "<b>Caps.</b><br>"
  29875. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29876. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29877. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29878. + "<b>Info</b><br>"
  29879. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29880. + glInfo.version + "<br>"
  29881. + "</div><br>"
  29882. + glInfo.renderer + "<br>";
  29883. if (this.customStatsFunction) {
  29884. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29885. }
  29886. };
  29887. return DebugLayer;
  29888. })();
  29889. BABYLON.DebugLayer = DebugLayer;
  29890. })(BABYLON || (BABYLON = {}));
  29891. var BABYLON;
  29892. (function (BABYLON) {
  29893. var DefaultLoadingScreen = (function () {
  29894. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29895. var _this = this;
  29896. if (_loadingText === void 0) { _loadingText = ""; }
  29897. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29898. this._renderingCanvas = _renderingCanvas;
  29899. this._loadingText = _loadingText;
  29900. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29901. // Resize
  29902. this._resizeLoadingUI = function () {
  29903. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29904. _this._loadingDiv.style.position = "absolute";
  29905. _this._loadingDiv.style.left = canvasRect.left + "px";
  29906. _this._loadingDiv.style.top = canvasRect.top + "px";
  29907. _this._loadingDiv.style.width = canvasRect.width + "px";
  29908. _this._loadingDiv.style.height = canvasRect.height + "px";
  29909. };
  29910. }
  29911. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29912. var _this = this;
  29913. if (this._loadingDiv) {
  29914. // Do not add a loading screen if there is already one
  29915. return;
  29916. }
  29917. this._loadingDiv = document.createElement("div");
  29918. this._loadingDiv.id = "babylonjsLoadingDiv";
  29919. this._loadingDiv.style.opacity = "0";
  29920. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29921. // Loading text
  29922. this._loadingTextDiv = document.createElement("div");
  29923. this._loadingTextDiv.style.position = "absolute";
  29924. this._loadingTextDiv.style.left = "0";
  29925. this._loadingTextDiv.style.top = "50%";
  29926. this._loadingTextDiv.style.marginTop = "80px";
  29927. this._loadingTextDiv.style.width = "100%";
  29928. this._loadingTextDiv.style.height = "20px";
  29929. this._loadingTextDiv.style.fontFamily = "Arial";
  29930. this._loadingTextDiv.style.fontSize = "14px";
  29931. this._loadingTextDiv.style.color = "white";
  29932. this._loadingTextDiv.style.textAlign = "center";
  29933. this._loadingTextDiv.innerHTML = "Loading";
  29934. this._loadingDiv.appendChild(this._loadingTextDiv);
  29935. //set the predefined text
  29936. this._loadingTextDiv.innerHTML = this._loadingText;
  29937. // Loading img
  29938. var imgBack = new Image();
  29939. 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==";
  29940. imgBack.style.position = "absolute";
  29941. imgBack.style.left = "50%";
  29942. imgBack.style.top = "50%";
  29943. imgBack.style.marginLeft = "-50px";
  29944. imgBack.style.marginTop = "-50px";
  29945. imgBack.style.transition = "transform 1.0s ease";
  29946. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29947. var deg = 360;
  29948. var onTransitionEnd = function () {
  29949. deg += 360;
  29950. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29951. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29952. };
  29953. imgBack.addEventListener("transitionend", onTransitionEnd);
  29954. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29955. this._loadingDiv.appendChild(imgBack);
  29956. // front image
  29957. var imgFront = new Image();
  29958. 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=";
  29959. imgFront.style.position = "absolute";
  29960. imgFront.style.left = "50%";
  29961. imgFront.style.top = "50%";
  29962. imgFront.style.marginLeft = "-50px";
  29963. imgFront.style.marginTop = "-50px";
  29964. this._loadingDiv.appendChild(imgFront);
  29965. this._resizeLoadingUI();
  29966. window.addEventListener("resize", this._resizeLoadingUI);
  29967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29968. document.body.appendChild(this._loadingDiv);
  29969. setTimeout(function () {
  29970. _this._loadingDiv.style.opacity = "1";
  29971. imgBack.style.transform = "rotateZ(360deg)";
  29972. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29973. }, 0);
  29974. };
  29975. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29976. var _this = this;
  29977. if (!this._loadingDiv) {
  29978. return;
  29979. }
  29980. var onTransitionEnd = function () {
  29981. if (!_this._loadingDiv) {
  29982. return;
  29983. }
  29984. document.body.removeChild(_this._loadingDiv);
  29985. window.removeEventListener("resize", _this._resizeLoadingUI);
  29986. _this._loadingDiv = null;
  29987. };
  29988. this._loadingDiv.style.opacity = "0";
  29989. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29990. };
  29991. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29992. set: function (text) {
  29993. this._loadingText = text;
  29994. if (this._loadingTextDiv) {
  29995. this._loadingTextDiv.innerHTML = this._loadingText;
  29996. }
  29997. },
  29998. enumerable: true,
  29999. configurable: true
  30000. });
  30001. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  30002. get: function () {
  30003. return this._loadingDivBackgroundColor;
  30004. },
  30005. set: function (color) {
  30006. this._loadingDivBackgroundColor = color;
  30007. if (!this._loadingDiv) {
  30008. return;
  30009. }
  30010. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  30011. },
  30012. enumerable: true,
  30013. configurable: true
  30014. });
  30015. return DefaultLoadingScreen;
  30016. })();
  30017. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  30018. })(BABYLON || (BABYLON = {}));
  30019. var BABYLON;
  30020. (function (BABYLON) {
  30021. var SIMDVector3 = (function () {
  30022. function SIMDVector3() {
  30023. }
  30024. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  30025. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  30026. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30027. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30028. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30029. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30030. 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));
  30031. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30032. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30033. };
  30034. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  30035. var v0 = SIMD.float32x4.splat(x);
  30036. var v1 = SIMD.float32x4.splat(y);
  30037. var v2 = SIMD.float32x4.splat(z);
  30038. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30039. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30040. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30041. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30042. 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));
  30043. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30044. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30045. };
  30046. return SIMDVector3;
  30047. })();
  30048. BABYLON.SIMDVector3 = SIMDVector3;
  30049. var SIMDMatrix = (function () {
  30050. function SIMDMatrix() {
  30051. }
  30052. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  30053. if (offset === void 0) { offset = 0; }
  30054. var tm = this.m;
  30055. var om = other.m;
  30056. var om0 = SIMD.float32x4.load(om, 0);
  30057. var om1 = SIMD.float32x4.load(om, 4);
  30058. var om2 = SIMD.float32x4.load(om, 8);
  30059. var om3 = SIMD.float32x4.load(om, 12);
  30060. var tm0 = SIMD.float32x4.load(tm, 0);
  30061. 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)))));
  30062. var tm1 = SIMD.float32x4.load(tm, 4);
  30063. 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)))));
  30064. var tm2 = SIMD.float32x4.load(tm, 8);
  30065. 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)))));
  30066. var tm3 = SIMD.float32x4.load(tm, 12);
  30067. 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)))));
  30068. };
  30069. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  30070. var src = this.m;
  30071. var dest = other.m;
  30072. var row0, row1, row2, row3;
  30073. var tmp1;
  30074. var minor0, minor1, minor2, minor3;
  30075. var det;
  30076. // Load the 4 rows
  30077. var src0 = SIMD.float32x4.load(src, 0);
  30078. var src1 = SIMD.float32x4.load(src, 4);
  30079. var src2 = SIMD.float32x4.load(src, 8);
  30080. var src3 = SIMD.float32x4.load(src, 12);
  30081. // Transpose the source matrix. Sort of. Not a true transpose operation
  30082. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30083. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30084. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  30085. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  30086. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30087. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30088. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  30089. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  30090. // This is a true transposition, but it will lead to an incorrect result
  30091. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30092. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30093. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30094. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30095. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30096. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30097. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30098. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30099. // ----
  30100. tmp1 = SIMD.float32x4.mul(row2, row3);
  30101. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30102. minor0 = SIMD.float32x4.mul(row1, tmp1);
  30103. minor1 = SIMD.float32x4.mul(row0, tmp1);
  30104. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30105. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  30106. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  30107. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  30108. // ----
  30109. tmp1 = SIMD.float32x4.mul(row1, row2);
  30110. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30111. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  30112. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30113. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30114. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30115. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30116. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30117. // ----
  30118. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30119. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30120. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30121. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30122. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30123. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30124. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30125. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30126. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30127. // ----
  30128. tmp1 = SIMD.float32x4.mul(row0, row1);
  30129. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30130. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30131. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30132. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30133. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30134. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30135. // ----
  30136. tmp1 = SIMD.float32x4.mul(row0, row3);
  30137. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30138. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30139. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30140. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30141. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30142. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30143. // ----
  30144. tmp1 = SIMD.float32x4.mul(row0, row2);
  30145. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30146. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30147. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30148. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30149. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30150. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30151. // Compute determinant
  30152. det = SIMD.float32x4.mul(row0, minor0);
  30153. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30154. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30155. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30156. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30157. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30158. // These shuffles aren't necessary if the faulty transposition is done
  30159. // up at the top of this function.
  30160. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30161. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30162. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30163. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30164. // Compute final values by multiplying with 1/det
  30165. minor0 = SIMD.float32x4.mul(det, minor0);
  30166. minor1 = SIMD.float32x4.mul(det, minor1);
  30167. minor2 = SIMD.float32x4.mul(det, minor2);
  30168. minor3 = SIMD.float32x4.mul(det, minor3);
  30169. SIMD.float32x4.store(dest, 0, minor0);
  30170. SIMD.float32x4.store(dest, 4, minor1);
  30171. SIMD.float32x4.store(dest, 8, minor2);
  30172. SIMD.float32x4.store(dest, 12, minor3);
  30173. return this;
  30174. };
  30175. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30176. var out = result.m;
  30177. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30178. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30179. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30180. // cc.kmVec3Subtract(f, pCenter, pEye);
  30181. var f = SIMD.float32x4.sub(center, eye);
  30182. // cc.kmVec3Normalize(f, f);
  30183. var tmp = SIMD.float32x4.mul(f, f);
  30184. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30185. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30186. // cc.kmVec3Assign(up, pUp);
  30187. // cc.kmVec3Normalize(up, up);
  30188. tmp = SIMD.float32x4.mul(up, up);
  30189. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30190. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30191. // cc.kmVec3Cross(s, f, up);
  30192. 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)));
  30193. // cc.kmVec3Normalize(s, s);
  30194. tmp = SIMD.float32x4.mul(s, s);
  30195. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30196. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30197. // cc.kmVec3Cross(u, s, f);
  30198. 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)));
  30199. // cc.kmVec3Normalize(s, s);
  30200. tmp = SIMD.float32x4.mul(s, s);
  30201. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30202. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30203. var zero = SIMD.float32x4.splat(0.0);
  30204. s = SIMD.float32x4.neg(s);
  30205. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30206. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30207. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30208. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30209. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30210. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30211. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30212. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30213. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30214. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30215. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30216. var b3 = SIMD.float32x4.neg(eye);
  30217. b3 = SIMD.float32x4.withW(b3, 1.0);
  30218. 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)))));
  30219. 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)))));
  30220. 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)))));
  30221. 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)))));
  30222. };
  30223. return SIMDMatrix;
  30224. })();
  30225. BABYLON.SIMDMatrix = SIMDMatrix;
  30226. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30227. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30228. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30229. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30230. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30231. var SIMDHelper = (function () {
  30232. function SIMDHelper() {
  30233. }
  30234. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30235. get: function () {
  30236. return SIMDHelper._isEnabled;
  30237. },
  30238. enumerable: true,
  30239. configurable: true
  30240. });
  30241. SIMDHelper.DisableSIMD = function () {
  30242. // Replace functions
  30243. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30244. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30245. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30246. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30248. SIMDHelper._isEnabled = false;
  30249. };
  30250. SIMDHelper.EnableSIMD = function () {
  30251. if (window.SIMD === undefined) {
  30252. return;
  30253. }
  30254. // Replace functions
  30255. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30256. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30257. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30258. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30259. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30260. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30261. get: function () { return this._data[0]; },
  30262. set: function (value) {
  30263. if (!this._data) {
  30264. this._data = new Float32Array(3);
  30265. }
  30266. this._data[0] = value;
  30267. }
  30268. });
  30269. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30270. get: function () { return this._data[1]; },
  30271. set: function (value) {
  30272. this._data[1] = value;
  30273. }
  30274. });
  30275. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30276. get: function () { return this._data[2]; },
  30277. set: function (value) {
  30278. this._data[2] = value;
  30279. }
  30280. });
  30281. SIMDHelper._isEnabled = true;
  30282. };
  30283. SIMDHelper._isEnabled = false;
  30284. return SIMDHelper;
  30285. })();
  30286. BABYLON.SIMDHelper = SIMDHelper;
  30287. })(BABYLON || (BABYLON = {}));
  30288. var BABYLON;
  30289. (function (BABYLON) {
  30290. var ShaderMaterial = (function (_super) {
  30291. __extends(ShaderMaterial, _super);
  30292. function ShaderMaterial(name, scene, shaderPath, options) {
  30293. _super.call(this, name, scene);
  30294. this._textures = {};
  30295. this._floats = {};
  30296. this._floatsArrays = {};
  30297. this._colors3 = {};
  30298. this._colors4 = {};
  30299. this._vectors2 = {};
  30300. this._vectors3 = {};
  30301. this._vectors4 = {};
  30302. this._matrices = {};
  30303. this._matrices3x3 = {};
  30304. this._matrices2x2 = {};
  30305. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30306. this._shaderPath = shaderPath;
  30307. options.needAlphaBlending = options.needAlphaBlending || false;
  30308. options.needAlphaTesting = options.needAlphaTesting || false;
  30309. options.attributes = options.attributes || ["position", "normal", "uv"];
  30310. options.uniforms = options.uniforms || ["worldViewProjection"];
  30311. options.samplers = options.samplers || [];
  30312. options.defines = options.defines || [];
  30313. this._options = options;
  30314. }
  30315. ShaderMaterial.prototype.needAlphaBlending = function () {
  30316. return this._options.needAlphaBlending;
  30317. };
  30318. ShaderMaterial.prototype.needAlphaTesting = function () {
  30319. return this._options.needAlphaTesting;
  30320. };
  30321. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30322. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30323. this._options.uniforms.push(uniformName);
  30324. }
  30325. };
  30326. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30327. if (this._options.samplers.indexOf(name) === -1) {
  30328. this._options.samplers.push(name);
  30329. }
  30330. this._textures[name] = texture;
  30331. return this;
  30332. };
  30333. ShaderMaterial.prototype.setFloat = function (name, value) {
  30334. this._checkUniform(name);
  30335. this._floats[name] = value;
  30336. return this;
  30337. };
  30338. ShaderMaterial.prototype.setFloats = function (name, value) {
  30339. this._checkUniform(name);
  30340. this._floatsArrays[name] = value;
  30341. return this;
  30342. };
  30343. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30344. this._checkUniform(name);
  30345. this._colors3[name] = value;
  30346. return this;
  30347. };
  30348. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30349. this._checkUniform(name);
  30350. this._colors4[name] = value;
  30351. return this;
  30352. };
  30353. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30354. this._checkUniform(name);
  30355. this._vectors2[name] = value;
  30356. return this;
  30357. };
  30358. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30359. this._checkUniform(name);
  30360. this._vectors3[name] = value;
  30361. return this;
  30362. };
  30363. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30364. this._checkUniform(name);
  30365. this._vectors4[name] = value;
  30366. return this;
  30367. };
  30368. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30369. this._checkUniform(name);
  30370. this._matrices[name] = value;
  30371. return this;
  30372. };
  30373. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30374. this._checkUniform(name);
  30375. this._matrices3x3[name] = value;
  30376. return this;
  30377. };
  30378. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30379. this._checkUniform(name);
  30380. this._matrices2x2[name] = value;
  30381. return this;
  30382. };
  30383. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30384. var scene = this.getScene();
  30385. var engine = scene.getEngine();
  30386. if (!this.checkReadyOnEveryCall) {
  30387. if (this._renderId === scene.getRenderId()) {
  30388. return true;
  30389. }
  30390. }
  30391. // Instances
  30392. var defines = [];
  30393. var fallbacks = new BABYLON.EffectFallbacks();
  30394. if (useInstances) {
  30395. defines.push("#define INSTANCES");
  30396. }
  30397. for (var index = 0; index < this._options.defines.length; index++) {
  30398. defines.push(this._options.defines[index]);
  30399. }
  30400. // Bones
  30401. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30402. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30403. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30404. fallbacks.addCPUSkinningFallback(0, mesh);
  30405. }
  30406. // Alpha test
  30407. if (engine.getAlphaTesting()) {
  30408. defines.push("#define ALPHATEST");
  30409. }
  30410. var previousEffect = this._effect;
  30411. var join = defines.join("\n");
  30412. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30413. if (!this._effect.isReady()) {
  30414. return false;
  30415. }
  30416. if (previousEffect !== this._effect) {
  30417. scene.resetCachedMaterial();
  30418. }
  30419. this._renderId = scene.getRenderId();
  30420. return true;
  30421. };
  30422. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30423. var scene = this.getScene();
  30424. if (this._options.uniforms.indexOf("world") !== -1) {
  30425. this._effect.setMatrix("world", world);
  30426. }
  30427. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30428. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30429. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30430. }
  30431. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30432. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30433. }
  30434. };
  30435. ShaderMaterial.prototype.bind = function (world, mesh) {
  30436. // Std values
  30437. this.bindOnlyWorldMatrix(world);
  30438. if (this.getScene().getCachedMaterial() !== this) {
  30439. if (this._options.uniforms.indexOf("view") !== -1) {
  30440. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30441. }
  30442. if (this._options.uniforms.indexOf("projection") !== -1) {
  30443. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30444. }
  30445. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30446. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30447. }
  30448. // Bones
  30449. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30450. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30451. }
  30452. // Texture
  30453. for (var name in this._textures) {
  30454. this._effect.setTexture(name, this._textures[name]);
  30455. }
  30456. // Float
  30457. for (name in this._floats) {
  30458. this._effect.setFloat(name, this._floats[name]);
  30459. }
  30460. // Float s
  30461. for (name in this._floatsArrays) {
  30462. this._effect.setArray(name, this._floatsArrays[name]);
  30463. }
  30464. // Color3
  30465. for (name in this._colors3) {
  30466. this._effect.setColor3(name, this._colors3[name]);
  30467. }
  30468. // Color4
  30469. for (name in this._colors4) {
  30470. var color = this._colors4[name];
  30471. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30472. }
  30473. // Vector2
  30474. for (name in this._vectors2) {
  30475. this._effect.setVector2(name, this._vectors2[name]);
  30476. }
  30477. // Vector3
  30478. for (name in this._vectors3) {
  30479. this._effect.setVector3(name, this._vectors3[name]);
  30480. }
  30481. // Vector4
  30482. for (name in this._vectors4) {
  30483. this._effect.setVector4(name, this._vectors4[name]);
  30484. }
  30485. // Matrix
  30486. for (name in this._matrices) {
  30487. this._effect.setMatrix(name, this._matrices[name]);
  30488. }
  30489. // Matrix 3x3
  30490. for (name in this._matrices3x3) {
  30491. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30492. }
  30493. // Matrix 2x2
  30494. for (name in this._matrices2x2) {
  30495. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30496. }
  30497. }
  30498. _super.prototype.bind.call(this, world, mesh);
  30499. };
  30500. ShaderMaterial.prototype.clone = function (name) {
  30501. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30502. return newShaderMaterial;
  30503. };
  30504. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30505. for (var name in this._textures) {
  30506. this._textures[name].dispose();
  30507. }
  30508. this._textures = {};
  30509. _super.prototype.dispose.call(this, forceDisposeEffect);
  30510. };
  30511. ShaderMaterial.prototype.serialize = function () {
  30512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30513. serializationObject.customType = "BABYLON.ShaderMaterial";
  30514. serializationObject.options = this._options;
  30515. serializationObject.shaderPath = this._shaderPath;
  30516. // Texture
  30517. serializationObject.textures = {};
  30518. for (var name in this._textures) {
  30519. serializationObject.textures[name] = this._textures[name].serialize();
  30520. }
  30521. // Float
  30522. serializationObject.floats = {};
  30523. for (name in this._floats) {
  30524. serializationObject.floats[name] = this._floats[name];
  30525. }
  30526. // Float s
  30527. serializationObject.floatArrays = {};
  30528. for (name in this._floatsArrays) {
  30529. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30530. }
  30531. // Color3
  30532. serializationObject.colors3 = {};
  30533. for (name in this._colors3) {
  30534. serializationObject.colors3[name] = this._colors3[name].asArray();
  30535. }
  30536. // Color4
  30537. serializationObject.colors4 = {};
  30538. for (name in this._colors4) {
  30539. serializationObject.colors4[name] = this._colors4[name].asArray();
  30540. }
  30541. // Vector2
  30542. serializationObject.vectors2 = {};
  30543. for (name in this._vectors2) {
  30544. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30545. }
  30546. // Vector3
  30547. serializationObject.vectors3 = {};
  30548. for (name in this._vectors3) {
  30549. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30550. }
  30551. // Vector4
  30552. serializationObject.vectors4 = {};
  30553. for (name in this._vectors4) {
  30554. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30555. }
  30556. // Matrix
  30557. serializationObject.matrices = {};
  30558. for (name in this._matrices) {
  30559. serializationObject.matrices[name] = this._matrices[name].asArray();
  30560. }
  30561. // Matrix 3x3
  30562. serializationObject.matrices3x3 = {};
  30563. for (name in this._matrices3x3) {
  30564. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30565. }
  30566. // Matrix 2x2
  30567. serializationObject.matrices2x2 = {};
  30568. for (name in this._matrices2x2) {
  30569. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30570. }
  30571. return serializationObject;
  30572. };
  30573. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30574. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30575. // Texture
  30576. for (var name in source.textures) {
  30577. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30578. }
  30579. // Float
  30580. for (name in source.floats) {
  30581. material.setFloat(name, source.floats[name]);
  30582. }
  30583. // Float s
  30584. for (name in source.floatsArrays) {
  30585. material.setFloats(name, source.floatsArrays[name]);
  30586. }
  30587. // Color3
  30588. for (name in source.colors3) {
  30589. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30590. }
  30591. // Color4
  30592. for (name in source.colors4) {
  30593. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30594. }
  30595. // Vector2
  30596. for (name in source.vectors2) {
  30597. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30598. }
  30599. // Vector3
  30600. for (name in source.vectors3) {
  30601. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30602. }
  30603. // Vector4
  30604. for (name in source.vectors4) {
  30605. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30606. }
  30607. // Matrix
  30608. for (name in source.matrices) {
  30609. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30610. }
  30611. // Matrix 3x3
  30612. for (name in source.matrices3x3) {
  30613. material.setMatrix3x3(name, source.matrices3x3[name]);
  30614. }
  30615. // Matrix 2x2
  30616. for (name in source.matrices2x2) {
  30617. material.setMatrix2x2(name, source.matrices2x2[name]);
  30618. }
  30619. return material;
  30620. };
  30621. return ShaderMaterial;
  30622. })(BABYLON.Material);
  30623. BABYLON.ShaderMaterial = ShaderMaterial;
  30624. })(BABYLON || (BABYLON = {}));
  30625. var BABYLON;
  30626. (function (BABYLON) {
  30627. var Internals;
  30628. (function (Internals) {
  30629. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30630. // All values and structures referenced from:
  30631. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30632. var DDS_MAGIC = 0x20534444;
  30633. 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;
  30634. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30635. 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;
  30636. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30637. function FourCCToInt32(value) {
  30638. return value.charCodeAt(0) +
  30639. (value.charCodeAt(1) << 8) +
  30640. (value.charCodeAt(2) << 16) +
  30641. (value.charCodeAt(3) << 24);
  30642. }
  30643. function Int32ToFourCC(value) {
  30644. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30645. }
  30646. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30647. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30648. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30649. var headerLengthInt = 31; // The header length in 32 bit ints
  30650. // Offsets into the header array
  30651. var off_magic = 0;
  30652. var off_size = 1;
  30653. var off_flags = 2;
  30654. var off_height = 3;
  30655. var off_width = 4;
  30656. var off_mipmapCount = 7;
  30657. var off_pfFlags = 20;
  30658. var off_pfFourCC = 21;
  30659. var off_RGBbpp = 22;
  30660. var off_RMask = 23;
  30661. var off_GMask = 24;
  30662. var off_BMask = 25;
  30663. var off_AMask = 26;
  30664. var off_caps1 = 27;
  30665. var off_caps2 = 28;
  30666. ;
  30667. var DDSTools = (function () {
  30668. function DDSTools() {
  30669. }
  30670. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30671. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30672. var mipmapCount = 1;
  30673. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30674. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30675. }
  30676. return {
  30677. width: header[off_width],
  30678. height: header[off_height],
  30679. mipmapCount: mipmapCount,
  30680. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30681. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30682. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30683. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30684. };
  30685. };
  30686. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30687. var byteArray = new Uint8Array(dataLength);
  30688. var srcData = new Uint8Array(arrayBuffer);
  30689. var index = 0;
  30690. for (var y = height - 1; y >= 0; y--) {
  30691. for (var x = 0; x < width; x++) {
  30692. var srcPos = dataOffset + (x + y * width) * 4;
  30693. byteArray[index + 2] = srcData[srcPos];
  30694. byteArray[index + 1] = srcData[srcPos + 1];
  30695. byteArray[index] = srcData[srcPos + 2];
  30696. byteArray[index + 3] = srcData[srcPos + 3];
  30697. index += 4;
  30698. }
  30699. }
  30700. return byteArray;
  30701. };
  30702. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30703. var byteArray = new Uint8Array(dataLength);
  30704. var srcData = new Uint8Array(arrayBuffer);
  30705. var index = 0;
  30706. for (var y = height - 1; y >= 0; y--) {
  30707. for (var x = 0; x < width; x++) {
  30708. var srcPos = dataOffset + (x + y * width) * 3;
  30709. byteArray[index + 2] = srcData[srcPos];
  30710. byteArray[index + 1] = srcData[srcPos + 1];
  30711. byteArray[index] = srcData[srcPos + 2];
  30712. index += 3;
  30713. }
  30714. }
  30715. return byteArray;
  30716. };
  30717. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30718. var byteArray = new Uint8Array(dataLength);
  30719. var srcData = new Uint8Array(arrayBuffer);
  30720. var index = 0;
  30721. for (var y = height - 1; y >= 0; y--) {
  30722. for (var x = 0; x < width; x++) {
  30723. var srcPos = dataOffset + (x + y * width);
  30724. byteArray[index] = srcData[srcPos];
  30725. index++;
  30726. }
  30727. }
  30728. return byteArray;
  30729. };
  30730. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30731. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30732. if (header[off_magic] != DDS_MAGIC) {
  30733. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30734. return;
  30735. }
  30736. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30737. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30738. return;
  30739. }
  30740. if (info.isFourCC) {
  30741. fourCC = header[off_pfFourCC];
  30742. switch (fourCC) {
  30743. case FOURCC_DXT1:
  30744. blockBytes = 8;
  30745. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30746. break;
  30747. case FOURCC_DXT3:
  30748. blockBytes = 16;
  30749. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30750. break;
  30751. case FOURCC_DXT5:
  30752. blockBytes = 16;
  30753. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30754. break;
  30755. default:
  30756. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30757. return;
  30758. }
  30759. }
  30760. mipmapCount = 1;
  30761. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30762. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30763. }
  30764. var bpp = header[off_RGBbpp];
  30765. for (var face = 0; face < faces; face++) {
  30766. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30767. width = header[off_width];
  30768. height = header[off_height];
  30769. dataOffset = header[off_size] + 4;
  30770. for (i = 0; i < mipmapCount; ++i) {
  30771. if (info.isRGB) {
  30772. if (bpp === 24) {
  30773. dataLength = width * height * 3;
  30774. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30775. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30776. }
  30777. else {
  30778. dataLength = width * height * 4;
  30779. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30780. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30781. }
  30782. }
  30783. else if (info.isLuminance) {
  30784. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30785. var unpaddedRowSize = width;
  30786. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30787. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30788. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30789. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30790. }
  30791. else {
  30792. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30793. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30794. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30795. }
  30796. dataOffset += dataLength;
  30797. width *= 0.5;
  30798. height *= 0.5;
  30799. width = Math.max(1.0, width);
  30800. height = Math.max(1.0, height);
  30801. }
  30802. }
  30803. };
  30804. return DDSTools;
  30805. })();
  30806. Internals.DDSTools = DDSTools;
  30807. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30808. })(BABYLON || (BABYLON = {}));
  30809. var BABYLON;
  30810. (function (BABYLON) {
  30811. var CannonJSPlugin = (function () {
  30812. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30813. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30814. if (iterations === void 0) { iterations = 10; }
  30815. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30816. this.name = "CannonJSPlugin";
  30817. this._physicsMaterials = [];
  30818. this._fixedTimeStep = 1 / 60;
  30819. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30820. this._currentCollisionGroup = 2;
  30821. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30822. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30823. this._tmpPosition = BABYLON.Vector3.Zero();
  30824. this._tmpQuaternion = new BABYLON.Quaternion();
  30825. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30826. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30827. this._tmpUnityRotation = new BABYLON.Quaternion();
  30828. if (!this.isSupported()) {
  30829. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30830. return;
  30831. }
  30832. this.world = new CANNON.World();
  30833. this.world.broadphase = new CANNON.NaiveBroadphase();
  30834. this.world.solver.iterations = iterations;
  30835. }
  30836. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30837. this.world.gravity.copy(gravity);
  30838. };
  30839. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  30840. this._fixedTimeStep = timeStep;
  30841. };
  30842. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30843. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  30844. };
  30845. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30846. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30847. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30848. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30849. };
  30850. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30851. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30852. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30853. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30854. };
  30855. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30856. //parent-child relationship. Does this impostor has a parent impostor?
  30857. if (impostor.parent) {
  30858. if (impostor.physicsBody) {
  30859. this.removePhysicsBody(impostor);
  30860. //TODO is that needed?
  30861. impostor.forceUpdate();
  30862. }
  30863. return;
  30864. }
  30865. //should a new body be created for this impostor?
  30866. if (impostor.isBodyInitRequired()) {
  30867. if (!impostor.mesh.rotationQuaternion) {
  30868. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30869. }
  30870. var shape = this._createShape(impostor);
  30871. //unregister events, if body is being changed
  30872. var oldBody = impostor.physicsBody;
  30873. if (oldBody) {
  30874. this.removePhysicsBody(impostor);
  30875. }
  30876. //create the body and material
  30877. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  30878. var bodyCreationObject = {
  30879. mass: impostor.getParam("mass"),
  30880. material: material
  30881. };
  30882. // A simple extend, in case native options were used.
  30883. var nativeOptions = impostor.getParam("nativeOptions");
  30884. for (var key in nativeOptions) {
  30885. if (nativeOptions.hasOwnProperty(key)) {
  30886. bodyCreationObject[key] = nativeOptions[key];
  30887. }
  30888. }
  30889. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30890. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30891. this.world.addEventListener("preStep", impostor.beforeStep);
  30892. this.world.addEventListener("postStep", impostor.afterStep);
  30893. impostor.physicsBody.addShape(shape);
  30894. this.world.add(impostor.physicsBody);
  30895. //try to keep the body moving in the right direction by taking old properties.
  30896. //Should be tested!
  30897. if (oldBody) {
  30898. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30899. impostor.physicsBody[param].copy(oldBody[param]);
  30900. });
  30901. }
  30902. this._processChildMeshes(impostor);
  30903. }
  30904. //now update the body's transformation
  30905. this._updatePhysicsBodyTransformation(impostor);
  30906. };
  30907. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30908. var _this = this;
  30909. var meshChildren = mainImpostor.mesh.getChildMeshes();
  30910. if (meshChildren.length) {
  30911. var processMesh = function (localPosition, mesh) {
  30912. var childImpostor = mesh.getPhysicsImpostor();
  30913. if (childImpostor) {
  30914. var parent = childImpostor.parent;
  30915. if (parent !== mainImpostor) {
  30916. var localPosition = mesh.position;
  30917. if (childImpostor.physicsBody) {
  30918. _this.removePhysicsBody(childImpostor);
  30919. childImpostor.physicsBody = null;
  30920. }
  30921. childImpostor.parent = mainImpostor;
  30922. childImpostor.resetUpdateFlags();
  30923. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30924. //Add the mass of the children.
  30925. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30926. }
  30927. }
  30928. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  30929. };
  30930. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30931. }
  30932. };
  30933. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30934. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30935. this.world.removeEventListener("preStep", impostor.beforeStep);
  30936. this.world.removeEventListener("postStep", impostor.afterStep);
  30937. this.world.remove(impostor.physicsBody);
  30938. };
  30939. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30942. if (!mainBody || !connectedBody) {
  30943. return;
  30944. }
  30945. var constraint;
  30946. var jointData = impostorJoint.joint.jointData;
  30947. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30948. var constraintData = {
  30949. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30950. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30951. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30952. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30953. maxForce: jointData.nativeParams.maxForce,
  30954. collideConnected: !!jointData.collision
  30955. };
  30956. //Not needed, Cannon has a collideConnected flag
  30957. /*if (!jointData.collision) {
  30958. //add 1st body to a collision group of its own, if it is not in 1
  30959. if (mainBody.collisionFilterGroup === 1) {
  30960. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30961. this._currentCollisionGroup <<= 1;
  30962. }
  30963. if (connectedBody.collisionFilterGroup === 1) {
  30964. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30965. this._currentCollisionGroup <<= 1;
  30966. }
  30967. //add their mask to the collisionFilterMask of each other:
  30968. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30969. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30970. }*/
  30971. switch (impostorJoint.joint.type) {
  30972. case BABYLON.PhysicsJoint.HingeJoint:
  30973. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30974. break;
  30975. case BABYLON.PhysicsJoint.DistanceJoint:
  30976. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30977. break;
  30978. case BABYLON.PhysicsJoint.SpringJoint:
  30979. var springData = jointData;
  30980. constraint = new CANNON.Spring(mainBody, connectedBody, {
  30981. restLength: springData.length,
  30982. stiffness: springData.stiffness,
  30983. damping: springData.damping,
  30984. localAnchorA: constraintData.pivotA,
  30985. localAnchorB: constraintData.pivotB
  30986. });
  30987. break;
  30988. default:
  30989. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30990. break;
  30991. }
  30992. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  30993. constraint.collideConnected = !!jointData.collision;
  30994. impostorJoint.joint.physicsJoint = constraint;
  30995. //don't add spring as constraint, as it is not one.
  30996. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  30997. this.world.addConstraint(constraint);
  30998. }
  30999. else {
  31000. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  31001. constraint.applyForce();
  31002. });
  31003. }
  31004. };
  31005. CannonJSPlugin.prototype.removeJoint = function (joint) {
  31006. //TODO
  31007. };
  31008. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  31009. var index;
  31010. var mat;
  31011. for (index = 0; index < this._physicsMaterials.length; index++) {
  31012. mat = this._physicsMaterials[index];
  31013. if (mat.friction === friction && mat.restitution === restitution) {
  31014. return mat;
  31015. }
  31016. }
  31017. var currentMat = new CANNON.Material("mat");
  31018. currentMat.friction = friction;
  31019. currentMat.restitution = restitution;
  31020. this._physicsMaterials.push(currentMat);
  31021. return currentMat;
  31022. };
  31023. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  31024. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  31025. };
  31026. CannonJSPlugin.prototype._createShape = function (impostor) {
  31027. var mesh = impostor.mesh;
  31028. //get the correct bounding box
  31029. var oldQuaternion = mesh.rotationQuaternion;
  31030. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31031. mesh.computeWorldMatrix(true);
  31032. var returnValue;
  31033. switch (impostor.type) {
  31034. case BABYLON.PhysicsEngine.SphereImpostor:
  31035. var bbox = mesh.getBoundingInfo().boundingBox;
  31036. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31037. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31038. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31039. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  31040. break;
  31041. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  31042. case BABYLON.PhysicsEngine.CylinderImpostor:
  31043. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  31044. case BABYLON.PhysicsEngine.BoxImpostor:
  31045. bbox = mesh.getBoundingInfo().boundingBox;
  31046. var min = bbox.minimumWorld;
  31047. var max = bbox.maximumWorld;
  31048. var box = max.subtract(min).scale(0.5);
  31049. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  31050. break;
  31051. case BABYLON.PhysicsEngine.PlaneImpostor:
  31052. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  31053. returnValue = new CANNON.Plane();
  31054. break;
  31055. case BABYLON.PhysicsEngine.MeshImpostor:
  31056. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31057. var rawFaces = mesh.getIndices();
  31058. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  31059. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  31060. break;
  31061. case BABYLON.PhysicsEngine.HeightmapImpostor:
  31062. returnValue = this._createHeightmap(mesh);
  31063. break;
  31064. }
  31065. mesh.rotationQuaternion = oldQuaternion;
  31066. return returnValue;
  31067. };
  31068. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  31069. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31070. var matrix = [];
  31071. //For now pointDepth will not be used and will be automatically calculated.
  31072. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  31073. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  31074. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  31075. var elementSize = dim * 2 / arraySize;
  31076. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  31077. for (var i = 0; i < pos.length; i = i + 3) {
  31078. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  31079. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  31080. var y = pos[i + 1] + minY;
  31081. if (!matrix[x]) {
  31082. matrix[x] = [];
  31083. }
  31084. if (!matrix[x][z]) {
  31085. matrix[x][z] = y;
  31086. }
  31087. matrix[x][z] = Math.max(y, matrix[x][z]);
  31088. }
  31089. for (var x = 0; x <= arraySize; ++x) {
  31090. if (!matrix[x]) {
  31091. var loc = 1;
  31092. while (!matrix[(x + loc) % arraySize]) {
  31093. loc++;
  31094. }
  31095. matrix[x] = matrix[(x + loc) % arraySize].slice();
  31096. }
  31097. for (var z = 0; z <= arraySize; ++z) {
  31098. if (!matrix[x][z]) {
  31099. var loc = 1;
  31100. var newValue;
  31101. while (newValue === undefined) {
  31102. newValue = matrix[x][(z + loc++) % arraySize];
  31103. }
  31104. matrix[x][z] = newValue;
  31105. }
  31106. }
  31107. }
  31108. var shape = new CANNON.Heightfield(matrix, {
  31109. elementSize: elementSize
  31110. });
  31111. //For future reference, needed for body transformation
  31112. shape.minY = minY;
  31113. return shape;
  31114. };
  31115. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  31116. var mesh = impostor.mesh;
  31117. //make sure it is updated...
  31118. impostor.mesh.computeWorldMatrix(true);
  31119. // The delta between the mesh position and the mesh bounding box center
  31120. var bbox = mesh.getBoundingInfo().boundingBox;
  31121. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  31122. var quaternion = mesh.rotationQuaternion;
  31123. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  31124. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31125. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31126. //-90 DEG in X, precalculated
  31127. quaternion = quaternion.multiply(this._minus90X);
  31128. //Invert! (Precalculated, 90 deg in X)
  31129. //No need to clone. this will never change.
  31130. impostor.setDeltaRotation(this._plus90X);
  31131. }
  31132. //If it is a heightfield, if should be centered.
  31133. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31134. //calculate the correct body position:
  31135. var rotationQuaternion = mesh.rotationQuaternion;
  31136. mesh.rotationQuaternion = this._tmpUnityRotation;
  31137. mesh.computeWorldMatrix(true);
  31138. //get original center with no rotation
  31139. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31140. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31141. //rotation is back
  31142. mesh.rotationQuaternion = rotationQuaternion;
  31143. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31144. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31145. mesh.setPivotMatrix(p);
  31146. mesh.computeWorldMatrix(true);
  31147. //calculate the translation
  31148. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31149. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31150. //add it inverted to the delta
  31151. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  31152. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31153. mesh.setPivotMatrix(oldPivot);
  31154. mesh.computeWorldMatrix(true);
  31155. }
  31156. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31157. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31158. this._tmpPosition.copyFrom(mesh.position);
  31159. }
  31160. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31161. //Now update the impostor object
  31162. impostor.physicsBody.position.copy(this._tmpPosition);
  31163. impostor.physicsBody.quaternion.copy(quaternion);
  31164. };
  31165. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31166. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31167. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31168. };
  31169. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31170. impostor.physicsBody.position.copy(newPosition);
  31171. impostor.physicsBody.quaternion.copy(newRotation);
  31172. };
  31173. CannonJSPlugin.prototype.isSupported = function () {
  31174. return window.CANNON !== undefined;
  31175. };
  31176. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31177. impostor.physicsBody.velocity.copy(velocity);
  31178. };
  31179. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31180. impostor.physicsBody.angularVelocity.copy(velocity);
  31181. };
  31182. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31183. impostor.physicsBody.mass = mass;
  31184. impostor.physicsBody.updateMassProperties();
  31185. };
  31186. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  31187. impostor.physicsBody.sleep();
  31188. };
  31189. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  31190. impostor.physicsBody.wakeUp();
  31191. };
  31192. CannonJSPlugin.prototype.dispose = function () {
  31193. //nothing to do, actually.
  31194. };
  31195. return CannonJSPlugin;
  31196. })();
  31197. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31198. })(BABYLON || (BABYLON = {}));
  31199. var BABYLON;
  31200. (function (BABYLON) {
  31201. var OimoJSPlugin = (function () {
  31202. function OimoJSPlugin(iterations) {
  31203. this.name = "OimoJSPlugin";
  31204. this._tmpImpostorsArray = [];
  31205. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31206. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31207. this.world.clear();
  31208. //making sure no stats are calculated
  31209. this.world.isNoStat = true;
  31210. }
  31211. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31212. this.world.gravity.copy(gravity);
  31213. };
  31214. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  31215. this.world.timeStep = timeStep;
  31216. };
  31217. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31218. var _this = this;
  31219. impostors.forEach(function (impostor) {
  31220. impostor.beforeStep();
  31221. });
  31222. this.world.step();
  31223. impostors.forEach(function (impostor) {
  31224. impostor.afterStep();
  31225. //update the ordered impostors array
  31226. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31227. });
  31228. //check for collisions
  31229. var contact = this.world.contacts;
  31230. while (contact !== null) {
  31231. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31232. contact = contact.next;
  31233. continue;
  31234. }
  31235. //is this body colliding with any other? get the impostor
  31236. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31237. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31238. if (!mainImpostor || !collidingImpostor) {
  31239. contact = contact.next;
  31240. continue;
  31241. }
  31242. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31243. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31244. contact = contact.next;
  31245. }
  31246. };
  31247. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31248. var mass = impostor.physicsBody.massInfo.mass;
  31249. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31250. };
  31251. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31252. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31253. this.applyImpulse(impostor, force, contactPoint);
  31254. };
  31255. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31256. var _this = this;
  31257. //parent-child relationship. Does this impostor has a parent impostor?
  31258. if (impostor.parent) {
  31259. if (impostor.physicsBody) {
  31260. this.removePhysicsBody(impostor);
  31261. //TODO is that needed?
  31262. impostor.forceUpdate();
  31263. }
  31264. return;
  31265. }
  31266. impostor.mesh.computeWorldMatrix(true);
  31267. if (impostor.isBodyInitRequired()) {
  31268. if (!impostor.mesh.rotationQuaternion) {
  31269. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31270. }
  31271. var bodyConfig = {
  31272. name: impostor.mesh.uniqueId,
  31273. //Oimo must have mass, also for static objects.
  31274. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31275. size: [],
  31276. type: [],
  31277. pos: [],
  31278. rot: [],
  31279. move: impostor.getParam("mass") !== 0,
  31280. //Supporting older versions of Oimo
  31281. world: this.world
  31282. };
  31283. var impostors = [impostor];
  31284. function addToArray(parent) {
  31285. parent.getChildMeshes().forEach(function (m) {
  31286. if (m.physicsImpostor) {
  31287. impostors.push(m.physicsImpostor);
  31288. m.physicsImpostor._init();
  31289. }
  31290. });
  31291. }
  31292. addToArray(impostor.mesh);
  31293. function checkWithEpsilon(value) {
  31294. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31295. }
  31296. impostors.forEach(function (i) {
  31297. //get the correct bounding box
  31298. var oldQuaternion = i.mesh.rotationQuaternion;
  31299. 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 });
  31300. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31301. i.mesh.computeWorldMatrix(true);
  31302. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31303. if (i === impostor) {
  31304. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31305. //Can also use Array.prototype.push.apply
  31306. bodyConfig.pos.push(bbox.center.x);
  31307. bodyConfig.pos.push(bbox.center.y);
  31308. bodyConfig.pos.push(bbox.center.z);
  31309. //tmp solution
  31310. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31311. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31312. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31313. }
  31314. else {
  31315. bodyConfig.pos.push(i.mesh.position.x);
  31316. bodyConfig.pos.push(i.mesh.position.y);
  31317. bodyConfig.pos.push(i.mesh.position.z);
  31318. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31319. bodyConfig.rot.push(0);
  31320. bodyConfig.rot.push(0);
  31321. bodyConfig.rot.push(0);
  31322. }
  31323. // register mesh
  31324. switch (i.type) {
  31325. case BABYLON.PhysicsEngine.SphereImpostor:
  31326. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31327. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31328. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31329. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31330. bodyConfig.type.push('sphere');
  31331. //due to the way oimo works with compounds, add 3 times
  31332. bodyConfig.size.push(size);
  31333. bodyConfig.size.push(size);
  31334. bodyConfig.size.push(size);
  31335. break;
  31336. case BABYLON.PhysicsEngine.PlaneImpostor:
  31337. //TODO Oimo now supports cylinder!
  31338. case BABYLON.PhysicsEngine.CylinderImpostor:
  31339. case BABYLON.PhysicsEngine.BoxImpostor:
  31340. default:
  31341. var min = bbox.minimumWorld;
  31342. var max = bbox.maximumWorld;
  31343. var box = max.subtract(min);
  31344. var sizeX = checkWithEpsilon(box.x);
  31345. var sizeY = checkWithEpsilon(box.y);
  31346. var sizeZ = checkWithEpsilon(box.z);
  31347. bodyConfig.type.push('box');
  31348. bodyConfig.size.push(sizeX);
  31349. bodyConfig.size.push(sizeY);
  31350. bodyConfig.size.push(sizeZ);
  31351. break;
  31352. }
  31353. //actually not needed, but hey...
  31354. i.mesh.rotationQuaternion = oldQuaternion;
  31355. });
  31356. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31357. }
  31358. else {
  31359. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31360. }
  31361. impostor.setDeltaPosition(this._tmpPositionVector);
  31362. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31363. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31364. };
  31365. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31366. //impostor.physicsBody.dispose();
  31367. //Same as : (older oimo versions)
  31368. this.world.removeRigidBody(impostor.physicsBody);
  31369. };
  31370. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31371. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31372. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31373. if (!mainBody || !connectedBody) {
  31374. return;
  31375. }
  31376. var jointData = impostorJoint.joint.jointData;
  31377. var options = jointData.nativeParams || {};
  31378. var type;
  31379. var nativeJointData = {
  31380. body1: mainBody,
  31381. body2: connectedBody,
  31382. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31383. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31384. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31385. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31386. min: options.min,
  31387. max: options.max,
  31388. collision: options.collision || jointData.collision,
  31389. spring: options.spring,
  31390. //supporting older version of Oimo
  31391. world: this.world
  31392. };
  31393. switch (impostorJoint.joint.type) {
  31394. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31395. type = "jointBall";
  31396. break;
  31397. case BABYLON.PhysicsJoint.SpringJoint:
  31398. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  31399. var springData = jointData;
  31400. nativeJointData.min = springData.length || nativeJointData.min;
  31401. //Max should also be set, just make sure it is at least min
  31402. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  31403. case BABYLON.PhysicsJoint.DistanceJoint:
  31404. type = "jointDistance";
  31405. nativeJointData.max = jointData.maxDistance;
  31406. break;
  31407. case BABYLON.PhysicsJoint.PrismaticJoint:
  31408. type = "jointPrisme";
  31409. break;
  31410. case BABYLON.PhysicsJoint.SliderJoint:
  31411. type = "jointSlide";
  31412. break;
  31413. case BABYLON.PhysicsJoint.WheelJoint:
  31414. type = "jointWheel";
  31415. break;
  31416. case BABYLON.PhysicsJoint.HingeJoint:
  31417. default:
  31418. type = "jointHinge";
  31419. break;
  31420. }
  31421. nativeJointData.type = type;
  31422. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31423. };
  31424. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31425. joint.joint.physicsJoint.dispose();
  31426. };
  31427. OimoJSPlugin.prototype.isSupported = function () {
  31428. return OIMO !== undefined;
  31429. };
  31430. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31431. if (!impostor.physicsBody.sleeping) {
  31432. //TODO check that
  31433. if (impostor.physicsBody.shapes.next) {
  31434. var parentShape = this._getLastShape(impostor.physicsBody);
  31435. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31436. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31437. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31438. }
  31439. else {
  31440. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31441. }
  31442. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31443. }
  31444. };
  31445. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31446. var body = impostor.physicsBody;
  31447. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31448. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31449. body.syncShapes();
  31450. body.awake();
  31451. };
  31452. OimoJSPlugin.prototype._getLastShape = function (body) {
  31453. var lastShape = body.shapes;
  31454. while (lastShape.next) {
  31455. lastShape = lastShape.next;
  31456. }
  31457. return lastShape;
  31458. };
  31459. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31460. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31461. };
  31462. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31463. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  31464. };
  31465. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31466. var staticBody = mass === 0;
  31467. //this will actually set the body's density and not its mass.
  31468. //But this is how oimo treats the mass variable.
  31469. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  31470. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  31471. };
  31472. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  31473. impostor.physicsBody.sleep();
  31474. };
  31475. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  31476. impostor.physicsBody.awake();
  31477. };
  31478. OimoJSPlugin.prototype.dispose = function () {
  31479. this.world.clear();
  31480. };
  31481. return OimoJSPlugin;
  31482. })();
  31483. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31484. })(BABYLON || (BABYLON = {}));
  31485. var BABYLON;
  31486. (function (BABYLON) {
  31487. var DisplayPassPostProcess = (function (_super) {
  31488. __extends(DisplayPassPostProcess, _super);
  31489. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31490. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31491. }
  31492. return DisplayPassPostProcess;
  31493. })(BABYLON.PostProcess);
  31494. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31495. })(BABYLON || (BABYLON = {}));
  31496. var BABYLON;
  31497. (function (BABYLON) {
  31498. var SimplificationSettings = (function () {
  31499. function SimplificationSettings(quality, distance, optimizeMesh) {
  31500. this.quality = quality;
  31501. this.distance = distance;
  31502. this.optimizeMesh = optimizeMesh;
  31503. }
  31504. return SimplificationSettings;
  31505. })();
  31506. BABYLON.SimplificationSettings = SimplificationSettings;
  31507. var SimplificationQueue = (function () {
  31508. function SimplificationQueue() {
  31509. this.running = false;
  31510. this._simplificationArray = [];
  31511. }
  31512. SimplificationQueue.prototype.addTask = function (task) {
  31513. this._simplificationArray.push(task);
  31514. };
  31515. SimplificationQueue.prototype.executeNext = function () {
  31516. var task = this._simplificationArray.pop();
  31517. if (task) {
  31518. this.running = true;
  31519. this.runSimplification(task);
  31520. }
  31521. else {
  31522. this.running = false;
  31523. }
  31524. };
  31525. SimplificationQueue.prototype.runSimplification = function (task) {
  31526. var _this = this;
  31527. if (task.parallelProcessing) {
  31528. //parallel simplifier
  31529. task.settings.forEach(function (setting) {
  31530. var simplifier = _this.getSimplifier(task);
  31531. simplifier.simplify(setting, function (newMesh) {
  31532. task.mesh.addLODLevel(setting.distance, newMesh);
  31533. newMesh.isVisible = true;
  31534. //check if it is the last
  31535. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31536. //all done, run the success callback.
  31537. task.successCallback();
  31538. }
  31539. _this.executeNext();
  31540. });
  31541. });
  31542. }
  31543. else {
  31544. //single simplifier.
  31545. var simplifier = this.getSimplifier(task);
  31546. var runDecimation = function (setting, callback) {
  31547. simplifier.simplify(setting, function (newMesh) {
  31548. task.mesh.addLODLevel(setting.distance, newMesh);
  31549. newMesh.isVisible = true;
  31550. //run the next quality level
  31551. callback();
  31552. });
  31553. };
  31554. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31555. runDecimation(task.settings[loop.index], function () {
  31556. loop.executeNext();
  31557. });
  31558. }, function () {
  31559. //execution ended, run the success callback.
  31560. if (task.successCallback) {
  31561. task.successCallback();
  31562. }
  31563. _this.executeNext();
  31564. });
  31565. }
  31566. };
  31567. SimplificationQueue.prototype.getSimplifier = function (task) {
  31568. switch (task.simplificationType) {
  31569. case SimplificationType.QUADRATIC:
  31570. default:
  31571. return new QuadraticErrorSimplification(task.mesh);
  31572. }
  31573. };
  31574. return SimplificationQueue;
  31575. })();
  31576. BABYLON.SimplificationQueue = SimplificationQueue;
  31577. /**
  31578. * The implemented types of simplification.
  31579. * At the moment only Quadratic Error Decimation is implemented.
  31580. */
  31581. (function (SimplificationType) {
  31582. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31583. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31584. var SimplificationType = BABYLON.SimplificationType;
  31585. var DecimationTriangle = (function () {
  31586. function DecimationTriangle(vertices) {
  31587. this.vertices = vertices;
  31588. this.error = new Array(4);
  31589. this.deleted = false;
  31590. this.isDirty = false;
  31591. this.deletePending = false;
  31592. this.borderFactor = 0;
  31593. }
  31594. return DecimationTriangle;
  31595. })();
  31596. BABYLON.DecimationTriangle = DecimationTriangle;
  31597. var DecimationVertex = (function () {
  31598. function DecimationVertex(position, id) {
  31599. this.position = position;
  31600. this.id = id;
  31601. this.isBorder = true;
  31602. this.q = new QuadraticMatrix();
  31603. this.triangleCount = 0;
  31604. this.triangleStart = 0;
  31605. this.originalOffsets = [];
  31606. }
  31607. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31608. this.position.copyFrom(newPosition);
  31609. };
  31610. return DecimationVertex;
  31611. })();
  31612. BABYLON.DecimationVertex = DecimationVertex;
  31613. var QuadraticMatrix = (function () {
  31614. function QuadraticMatrix(data) {
  31615. this.data = new Array(10);
  31616. for (var i = 0; i < 10; ++i) {
  31617. if (data && data[i]) {
  31618. this.data[i] = data[i];
  31619. }
  31620. else {
  31621. this.data[i] = 0;
  31622. }
  31623. }
  31624. }
  31625. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31626. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31627. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31628. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31629. return det;
  31630. };
  31631. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31632. for (var i = 0; i < 10; ++i) {
  31633. this.data[i] += matrix.data[i];
  31634. }
  31635. };
  31636. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31637. for (var i = 0; i < 10; ++i) {
  31638. this.data[i] += data[i];
  31639. }
  31640. };
  31641. QuadraticMatrix.prototype.add = function (matrix) {
  31642. var m = new QuadraticMatrix();
  31643. for (var i = 0; i < 10; ++i) {
  31644. m.data[i] = this.data[i] + matrix.data[i];
  31645. }
  31646. return m;
  31647. };
  31648. QuadraticMatrix.FromData = function (a, b, c, d) {
  31649. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31650. };
  31651. //returning an array to avoid garbage collection
  31652. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31653. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31654. };
  31655. return QuadraticMatrix;
  31656. })();
  31657. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31658. var Reference = (function () {
  31659. function Reference(vertexId, triangleId) {
  31660. this.vertexId = vertexId;
  31661. this.triangleId = triangleId;
  31662. }
  31663. return Reference;
  31664. })();
  31665. BABYLON.Reference = Reference;
  31666. /**
  31667. * An implementation of the Quadratic Error simplification algorithm.
  31668. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31669. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31670. * @author RaananW
  31671. */
  31672. var QuadraticErrorSimplification = (function () {
  31673. function QuadraticErrorSimplification(_mesh) {
  31674. this._mesh = _mesh;
  31675. this.initialized = false;
  31676. this.syncIterations = 5000;
  31677. this.aggressiveness = 7;
  31678. this.decimationIterations = 100;
  31679. this.boundingBoxEpsilon = BABYLON.Epsilon;
  31680. }
  31681. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31682. var _this = this;
  31683. this.initDecimatedMesh();
  31684. //iterating through the submeshes array, one after the other.
  31685. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31686. _this.initWithMesh(loop.index, function () {
  31687. _this.runDecimation(settings, loop.index, function () {
  31688. loop.executeNext();
  31689. });
  31690. }, settings.optimizeMesh);
  31691. }, function () {
  31692. setTimeout(function () {
  31693. successCallback(_this._reconstructedMesh);
  31694. }, 0);
  31695. });
  31696. };
  31697. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31698. var _this = this;
  31699. var gCount = 0;
  31700. triangle.vertices.forEach(function (vertex) {
  31701. var count = 0;
  31702. var vPos = vertex.position;
  31703. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31704. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31705. ++count;
  31706. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31707. ++count;
  31708. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31709. ++count;
  31710. if (count > 1) {
  31711. ++gCount;
  31712. }
  31713. ;
  31714. });
  31715. if (gCount > 1) {
  31716. console.log(triangle, gCount);
  31717. }
  31718. return gCount > 1;
  31719. };
  31720. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31721. var _this = this;
  31722. var targetCount = ~~(this.triangles.length * settings.quality);
  31723. var deletedTriangles = 0;
  31724. var triangleCount = this.triangles.length;
  31725. var iterationFunction = function (iteration, callback) {
  31726. setTimeout(function () {
  31727. if (iteration % 5 === 0) {
  31728. _this.updateMesh(iteration === 0);
  31729. }
  31730. for (var i = 0; i < _this.triangles.length; ++i) {
  31731. _this.triangles[i].isDirty = false;
  31732. }
  31733. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31734. var trianglesIterator = function (i) {
  31735. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31736. var t = _this.triangles[tIdx];
  31737. if (!t)
  31738. return;
  31739. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31740. return;
  31741. }
  31742. for (var j = 0; j < 3; ++j) {
  31743. if (t.error[j] < threshold) {
  31744. var deleted0 = [];
  31745. var deleted1 = [];
  31746. var v0 = t.vertices[j];
  31747. var v1 = t.vertices[(j + 1) % 3];
  31748. if (v0.isBorder !== v1.isBorder)
  31749. continue;
  31750. var p = BABYLON.Vector3.Zero();
  31751. var n = BABYLON.Vector3.Zero();
  31752. var uv = BABYLON.Vector2.Zero();
  31753. var color = new BABYLON.Color4(0, 0, 0, 1);
  31754. _this.calculateError(v0, v1, p, n, uv, color);
  31755. var delTr = [];
  31756. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31757. continue;
  31758. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31759. continue;
  31760. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31761. continue;
  31762. var uniqueArray = [];
  31763. delTr.forEach(function (deletedT) {
  31764. if (uniqueArray.indexOf(deletedT) === -1) {
  31765. deletedT.deletePending = true;
  31766. uniqueArray.push(deletedT);
  31767. }
  31768. });
  31769. if (uniqueArray.length % 2 !== 0) {
  31770. continue;
  31771. }
  31772. v0.q = v1.q.add(v0.q);
  31773. v0.updatePosition(p);
  31774. var tStart = _this.references.length;
  31775. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31776. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31777. var tCount = _this.references.length - tStart;
  31778. if (tCount <= v0.triangleCount) {
  31779. if (tCount) {
  31780. for (var c = 0; c < tCount; c++) {
  31781. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31782. }
  31783. }
  31784. }
  31785. else {
  31786. v0.triangleStart = tStart;
  31787. }
  31788. v0.triangleCount = tCount;
  31789. break;
  31790. }
  31791. }
  31792. };
  31793. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31794. }, 0);
  31795. };
  31796. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31797. if (triangleCount - deletedTriangles <= targetCount)
  31798. loop.breakLoop();
  31799. else {
  31800. iterationFunction(loop.index, function () {
  31801. loop.executeNext();
  31802. });
  31803. }
  31804. }, function () {
  31805. setTimeout(function () {
  31806. //reconstruct this part of the mesh
  31807. _this.reconstructMesh(submeshIndex);
  31808. successCallback();
  31809. }, 0);
  31810. });
  31811. };
  31812. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31813. var _this = this;
  31814. this.vertices = [];
  31815. this.triangles = [];
  31816. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31817. var indices = this._mesh.getIndices();
  31818. var submesh = this._mesh.subMeshes[submeshIndex];
  31819. var findInVertices = function (positionToSearch) {
  31820. if (optimizeMesh) {
  31821. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31822. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31823. return _this.vertices[ii];
  31824. }
  31825. }
  31826. }
  31827. return null;
  31828. };
  31829. var vertexReferences = [];
  31830. var vertexInit = function (i) {
  31831. var offset = i + submesh.verticesStart;
  31832. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31833. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31834. vertex.originalOffsets.push(offset);
  31835. if (vertex.id === _this.vertices.length) {
  31836. _this.vertices.push(vertex);
  31837. }
  31838. vertexReferences.push(vertex.id);
  31839. };
  31840. //var totalVertices = mesh.getTotalVertices();
  31841. var totalVertices = submesh.verticesCount;
  31842. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31843. var indicesInit = function (i) {
  31844. var offset = (submesh.indexStart / 3) + i;
  31845. var pos = (offset * 3);
  31846. var i0 = indices[pos + 0];
  31847. var i1 = indices[pos + 1];
  31848. var i2 = indices[pos + 2];
  31849. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31850. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31851. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31852. var triangle = new DecimationTriangle([v0, v1, v2]);
  31853. triangle.originalOffset = pos;
  31854. _this.triangles.push(triangle);
  31855. };
  31856. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31857. _this.init(callback);
  31858. });
  31859. });
  31860. };
  31861. QuadraticErrorSimplification.prototype.init = function (callback) {
  31862. var _this = this;
  31863. var triangleInit1 = function (i) {
  31864. var t = _this.triangles[i];
  31865. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31866. for (var j = 0; j < 3; j++) {
  31867. 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))));
  31868. }
  31869. };
  31870. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31871. var triangleInit2 = function (i) {
  31872. var t = _this.triangles[i];
  31873. for (var j = 0; j < 3; ++j) {
  31874. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31875. }
  31876. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31877. };
  31878. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31879. _this.initialized = true;
  31880. callback();
  31881. });
  31882. });
  31883. };
  31884. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31885. var newTriangles = [];
  31886. var i;
  31887. for (i = 0; i < this.vertices.length; ++i) {
  31888. this.vertices[i].triangleCount = 0;
  31889. }
  31890. var t;
  31891. var j;
  31892. for (i = 0; i < this.triangles.length; ++i) {
  31893. if (!this.triangles[i].deleted) {
  31894. t = this.triangles[i];
  31895. for (j = 0; j < 3; ++j) {
  31896. t.vertices[j].triangleCount = 1;
  31897. }
  31898. newTriangles.push(t);
  31899. }
  31900. }
  31901. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31902. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31903. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31904. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31905. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31906. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31907. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31908. var vertexCount = 0;
  31909. for (i = 0; i < this.vertices.length; ++i) {
  31910. var vertex = this.vertices[i];
  31911. vertex.id = vertexCount;
  31912. if (vertex.triangleCount) {
  31913. vertex.originalOffsets.forEach(function (originalOffset) {
  31914. newPositionData.push(vertex.position.x);
  31915. newPositionData.push(vertex.position.y);
  31916. newPositionData.push(vertex.position.z);
  31917. newNormalData.push(normalData[originalOffset * 3]);
  31918. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31919. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31920. if (uvs && uvs.length) {
  31921. newUVsData.push(uvs[(originalOffset * 2)]);
  31922. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31923. }
  31924. else if (colorsData && colorsData.length) {
  31925. newColorsData.push(colorsData[(originalOffset * 4)]);
  31926. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31927. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31928. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31929. }
  31930. ++vertexCount;
  31931. });
  31932. }
  31933. }
  31934. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31935. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31936. var submeshesArray = this._reconstructedMesh.subMeshes;
  31937. this._reconstructedMesh.subMeshes = [];
  31938. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31939. var originalIndices = this._mesh.getIndices();
  31940. for (i = 0; i < newTriangles.length; ++i) {
  31941. t = newTriangles[i]; //now get the new referencing point for each vertex
  31942. [0, 1, 2].forEach(function (idx) {
  31943. var id = originalIndices[t.originalOffset + idx];
  31944. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31945. if (offset < 0)
  31946. offset = 0;
  31947. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31948. });
  31949. }
  31950. //overwriting the old vertex buffers and indices.
  31951. this._reconstructedMesh.setIndices(newIndicesArray);
  31952. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31953. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31954. if (newUVsData.length > 0)
  31955. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31956. if (newColorsData.length > 0)
  31957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31958. //create submesh
  31959. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31960. if (submeshIndex > 0) {
  31961. this._reconstructedMesh.subMeshes = [];
  31962. submeshesArray.forEach(function (submesh) {
  31963. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31964. });
  31965. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31966. }
  31967. };
  31968. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31969. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31970. this._reconstructedMesh.material = this._mesh.material;
  31971. this._reconstructedMesh.parent = this._mesh.parent;
  31972. this._reconstructedMesh.isVisible = false;
  31973. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31974. };
  31975. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31976. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31977. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31978. if (t.deleted)
  31979. continue;
  31980. var s = this.references[vertex1.triangleStart + i].vertexId;
  31981. var v1 = t.vertices[(s + 1) % 3];
  31982. var v2 = t.vertices[(s + 2) % 3];
  31983. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31984. deletedArray[i] = true;
  31985. delTr.push(t);
  31986. continue;
  31987. }
  31988. var d1 = v1.position.subtract(point);
  31989. d1 = d1.normalize();
  31990. var d2 = v2.position.subtract(point);
  31991. d2 = d2.normalize();
  31992. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31993. return true;
  31994. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31995. deletedArray[i] = false;
  31996. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31997. return true;
  31998. }
  31999. return false;
  32000. };
  32001. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32002. var newDeleted = deletedTriangles;
  32003. for (var i = 0; i < vertex.triangleCount; ++i) {
  32004. var ref = this.references[vertex.triangleStart + i];
  32005. var t = this.triangles[ref.triangleId];
  32006. if (t.deleted)
  32007. continue;
  32008. if (deletedArray[i] && t.deletePending) {
  32009. t.deleted = true;
  32010. newDeleted++;
  32011. continue;
  32012. }
  32013. t.vertices[ref.vertexId] = origVertex;
  32014. t.isDirty = true;
  32015. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32016. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32017. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32018. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32019. this.references.push(ref);
  32020. }
  32021. return newDeleted;
  32022. };
  32023. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32024. for (var i = 0; i < this.vertices.length; ++i) {
  32025. var vCount = [];
  32026. var vId = [];
  32027. var v = this.vertices[i];
  32028. var j;
  32029. for (j = 0; j < v.triangleCount; ++j) {
  32030. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32031. for (var ii = 0; ii < 3; ii++) {
  32032. var ofs = 0;
  32033. var vv = triangle.vertices[ii];
  32034. while (ofs < vCount.length) {
  32035. if (vId[ofs] === vv.id)
  32036. break;
  32037. ++ofs;
  32038. }
  32039. if (ofs === vCount.length) {
  32040. vCount.push(1);
  32041. vId.push(vv.id);
  32042. }
  32043. else {
  32044. vCount[ofs]++;
  32045. }
  32046. }
  32047. }
  32048. for (j = 0; j < vCount.length; ++j) {
  32049. if (vCount[j] === 1) {
  32050. this.vertices[vId[j]].isBorder = true;
  32051. }
  32052. else {
  32053. this.vertices[vId[j]].isBorder = false;
  32054. }
  32055. }
  32056. }
  32057. };
  32058. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32059. if (identifyBorders === void 0) { identifyBorders = false; }
  32060. var i;
  32061. if (!identifyBorders) {
  32062. var newTrianglesVector = [];
  32063. for (i = 0; i < this.triangles.length; ++i) {
  32064. if (!this.triangles[i].deleted) {
  32065. newTrianglesVector.push(this.triangles[i]);
  32066. }
  32067. }
  32068. this.triangles = newTrianglesVector;
  32069. }
  32070. for (i = 0; i < this.vertices.length; ++i) {
  32071. this.vertices[i].triangleCount = 0;
  32072. this.vertices[i].triangleStart = 0;
  32073. }
  32074. var t;
  32075. var j;
  32076. var v;
  32077. for (i = 0; i < this.triangles.length; ++i) {
  32078. t = this.triangles[i];
  32079. for (j = 0; j < 3; ++j) {
  32080. v = t.vertices[j];
  32081. v.triangleCount++;
  32082. }
  32083. }
  32084. var tStart = 0;
  32085. for (i = 0; i < this.vertices.length; ++i) {
  32086. this.vertices[i].triangleStart = tStart;
  32087. tStart += this.vertices[i].triangleCount;
  32088. this.vertices[i].triangleCount = 0;
  32089. }
  32090. var newReferences = new Array(this.triangles.length * 3);
  32091. for (i = 0; i < this.triangles.length; ++i) {
  32092. t = this.triangles[i];
  32093. for (j = 0; j < 3; ++j) {
  32094. v = t.vertices[j];
  32095. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32096. v.triangleCount++;
  32097. }
  32098. }
  32099. this.references = newReferences;
  32100. if (identifyBorders) {
  32101. this.identifyBorder();
  32102. }
  32103. };
  32104. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32105. var x = point.x;
  32106. var y = point.y;
  32107. var z = point.z;
  32108. 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
  32109. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32110. };
  32111. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32112. var q = vertex1.q.add(vertex2.q);
  32113. var border = vertex1.isBorder && vertex2.isBorder;
  32114. var error = 0;
  32115. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32116. if (qDet !== 0 && !border) {
  32117. if (!pointResult) {
  32118. pointResult = BABYLON.Vector3.Zero();
  32119. }
  32120. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32121. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32122. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32123. error = this.vertexError(q, pointResult);
  32124. }
  32125. else {
  32126. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32127. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32128. var error1 = this.vertexError(q, vertex1.position);
  32129. var error2 = this.vertexError(q, vertex2.position);
  32130. var error3 = this.vertexError(q, p3);
  32131. error = Math.min(error1, error2, error3);
  32132. if (error === error1) {
  32133. if (pointResult) {
  32134. pointResult.copyFrom(vertex1.position);
  32135. }
  32136. }
  32137. else if (error === error2) {
  32138. if (pointResult) {
  32139. pointResult.copyFrom(vertex2.position);
  32140. }
  32141. }
  32142. else {
  32143. if (pointResult) {
  32144. pointResult.copyFrom(p3);
  32145. }
  32146. }
  32147. }
  32148. return error;
  32149. };
  32150. return QuadraticErrorSimplification;
  32151. })();
  32152. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32153. })(BABYLON || (BABYLON = {}));
  32154. var BABYLON;
  32155. (function (BABYLON) {
  32156. var serializedGeometries = [];
  32157. var serializeGeometry = function (geometry, serializationGeometries) {
  32158. if (serializedGeometries[geometry.id]) {
  32159. return;
  32160. }
  32161. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32162. serializationGeometries.boxes.push(geometry.serialize());
  32163. }
  32164. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32165. serializationGeometries.spheres.push(geometry.serialize());
  32166. }
  32167. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32168. serializationGeometries.cylinders.push(geometry.serialize());
  32169. }
  32170. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32171. serializationGeometries.toruses.push(geometry.serialize());
  32172. }
  32173. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32174. serializationGeometries.grounds.push(geometry.serialize());
  32175. }
  32176. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32177. serializationGeometries.planes.push(geometry.serialize());
  32178. }
  32179. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32180. serializationGeometries.torusKnots.push(geometry.serialize());
  32181. }
  32182. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32183. throw new Error("Unknown primitive type");
  32184. }
  32185. else {
  32186. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32187. }
  32188. serializedGeometries[geometry.id] = true;
  32189. };
  32190. var serializeMesh = function (mesh, serializationScene) {
  32191. var serializationObject = {};
  32192. serializationObject.name = mesh.name;
  32193. serializationObject.id = mesh.id;
  32194. if (BABYLON.Tags.HasTags(mesh)) {
  32195. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32196. }
  32197. serializationObject.position = mesh.position.asArray();
  32198. if (mesh.rotationQuaternion) {
  32199. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32200. }
  32201. else if (mesh.rotation) {
  32202. serializationObject.rotation = mesh.rotation.asArray();
  32203. }
  32204. serializationObject.scaling = mesh.scaling.asArray();
  32205. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32206. serializationObject.isEnabled = mesh.isEnabled();
  32207. serializationObject.isVisible = mesh.isVisible;
  32208. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32209. serializationObject.pickable = mesh.isPickable;
  32210. serializationObject.receiveShadows = mesh.receiveShadows;
  32211. serializationObject.billboardMode = mesh.billboardMode;
  32212. serializationObject.visibility = mesh.visibility;
  32213. serializationObject.checkCollisions = mesh.checkCollisions;
  32214. // Parent
  32215. if (mesh.parent) {
  32216. serializationObject.parentId = mesh.parent.id;
  32217. }
  32218. // Geometry
  32219. var geometry = mesh._geometry;
  32220. if (geometry) {
  32221. var geometryId = geometry.id;
  32222. serializationObject.geometryId = geometryId;
  32223. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32224. // 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
  32225. serializeGeometry(geometry, serializationScene.geometries);
  32226. }
  32227. // SubMeshes
  32228. serializationObject.subMeshes = [];
  32229. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32230. var subMesh = mesh.subMeshes[subIndex];
  32231. serializationObject.subMeshes.push({
  32232. materialIndex: subMesh.materialIndex,
  32233. verticesStart: subMesh.verticesStart,
  32234. verticesCount: subMesh.verticesCount,
  32235. indexStart: subMesh.indexStart,
  32236. indexCount: subMesh.indexCount
  32237. });
  32238. }
  32239. }
  32240. // Material
  32241. if (mesh.material) {
  32242. serializationObject.materialId = mesh.material.id;
  32243. }
  32244. else {
  32245. mesh.material = null;
  32246. }
  32247. // Skeleton
  32248. if (mesh.skeleton) {
  32249. serializationObject.skeletonId = mesh.skeleton.id;
  32250. }
  32251. // Physics
  32252. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32253. serializationObject.physicsMass = mesh.getPhysicsMass();
  32254. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32255. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32256. switch (mesh.getPhysicsImpostor().type) {
  32257. case BABYLON.PhysicsEngine.BoxImpostor:
  32258. serializationObject.physicsImpostor = 1;
  32259. break;
  32260. case BABYLON.PhysicsEngine.SphereImpostor:
  32261. serializationObject.physicsImpostor = 2;
  32262. break;
  32263. }
  32264. }
  32265. // Instances
  32266. serializationObject.instances = [];
  32267. for (var index = 0; index < mesh.instances.length; index++) {
  32268. var instance = mesh.instances[index];
  32269. var serializationInstance = {
  32270. name: instance.name,
  32271. position: instance.position.asArray(),
  32272. scaling: instance.scaling.asArray()
  32273. };
  32274. if (instance.rotationQuaternion) {
  32275. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32276. }
  32277. else if (instance.rotation) {
  32278. serializationInstance.rotation = instance.rotation.asArray();
  32279. }
  32280. serializationObject.instances.push(serializationInstance);
  32281. // Animations
  32282. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32283. serializationInstance.ranges = instance.serializeAnimationRanges();
  32284. }
  32285. // Animations
  32286. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32287. serializationObject.ranges = mesh.serializeAnimationRanges();
  32288. // Layer mask
  32289. serializationObject.layerMask = mesh.layerMask;
  32290. return serializationObject;
  32291. };
  32292. var finalizeSingleMesh = function (mesh, serializationObject) {
  32293. //only works if the mesh is already loaded
  32294. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32295. //serialize material
  32296. if (mesh.material) {
  32297. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32298. serializationObject.materials = serializationObject.materials || [];
  32299. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32300. serializationObject.materials.push(mesh.material.serialize());
  32301. }
  32302. }
  32303. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32304. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32305. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32306. serializationObject.multiMaterials.push(mesh.material.serialize());
  32307. }
  32308. }
  32309. }
  32310. //serialize geometry
  32311. var geometry = mesh._geometry;
  32312. if (geometry) {
  32313. if (!serializationObject.geometries) {
  32314. serializationObject.geometries = {};
  32315. serializationObject.geometries.boxes = [];
  32316. serializationObject.geometries.spheres = [];
  32317. serializationObject.geometries.cylinders = [];
  32318. serializationObject.geometries.toruses = [];
  32319. serializationObject.geometries.grounds = [];
  32320. serializationObject.geometries.planes = [];
  32321. serializationObject.geometries.torusKnots = [];
  32322. serializationObject.geometries.vertexData = [];
  32323. }
  32324. serializeGeometry(geometry, serializationObject.geometries);
  32325. }
  32326. // Skeletons
  32327. if (mesh.skeleton) {
  32328. serializationObject.skeletons = serializationObject.skeletons || [];
  32329. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32330. }
  32331. //serialize the actual mesh
  32332. serializationObject.meshes = serializationObject.meshes || [];
  32333. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32334. }
  32335. };
  32336. var SceneSerializer = (function () {
  32337. function SceneSerializer() {
  32338. }
  32339. SceneSerializer.ClearCache = function () {
  32340. serializedGeometries = [];
  32341. };
  32342. SceneSerializer.Serialize = function (scene) {
  32343. var serializationObject = {};
  32344. // Scene
  32345. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32346. serializationObject.autoClear = scene.autoClear;
  32347. serializationObject.clearColor = scene.clearColor.asArray();
  32348. serializationObject.ambientColor = scene.ambientColor.asArray();
  32349. serializationObject.gravity = scene.gravity.asArray();
  32350. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32351. serializationObject.workerCollisions = scene.workerCollisions;
  32352. // Fog
  32353. if (scene.fogMode && scene.fogMode !== 0) {
  32354. serializationObject.fogMode = scene.fogMode;
  32355. serializationObject.fogColor = scene.fogColor.asArray();
  32356. serializationObject.fogStart = scene.fogStart;
  32357. serializationObject.fogEnd = scene.fogEnd;
  32358. serializationObject.fogDensity = scene.fogDensity;
  32359. }
  32360. //Physics
  32361. if (scene.isPhysicsEnabled()) {
  32362. serializationObject.physicsEnabled = true;
  32363. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32364. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32365. }
  32366. // Lights
  32367. serializationObject.lights = [];
  32368. var index;
  32369. var light;
  32370. for (index = 0; index < scene.lights.length; index++) {
  32371. light = scene.lights[index];
  32372. serializationObject.lights.push(light.serialize());
  32373. }
  32374. // Cameras
  32375. serializationObject.cameras = [];
  32376. for (index = 0; index < scene.cameras.length; index++) {
  32377. var camera = scene.cameras[index];
  32378. serializationObject.cameras.push(camera.serialize());
  32379. }
  32380. if (scene.activeCamera) {
  32381. serializationObject.activeCameraID = scene.activeCamera.id;
  32382. }
  32383. // Animations
  32384. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32385. // Materials
  32386. serializationObject.materials = [];
  32387. serializationObject.multiMaterials = [];
  32388. var material;
  32389. for (index = 0; index < scene.materials.length; index++) {
  32390. material = scene.materials[index];
  32391. serializationObject.materials.push(material.serialize());
  32392. }
  32393. // MultiMaterials
  32394. serializationObject.multiMaterials = [];
  32395. for (index = 0; index < scene.multiMaterials.length; index++) {
  32396. var multiMaterial = scene.multiMaterials[index];
  32397. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32398. }
  32399. // Skeletons
  32400. serializationObject.skeletons = [];
  32401. for (index = 0; index < scene.skeletons.length; index++) {
  32402. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32403. }
  32404. // Geometries
  32405. serializationObject.geometries = {};
  32406. serializationObject.geometries.boxes = [];
  32407. serializationObject.geometries.spheres = [];
  32408. serializationObject.geometries.cylinders = [];
  32409. serializationObject.geometries.toruses = [];
  32410. serializationObject.geometries.grounds = [];
  32411. serializationObject.geometries.planes = [];
  32412. serializationObject.geometries.torusKnots = [];
  32413. serializationObject.geometries.vertexData = [];
  32414. serializedGeometries = [];
  32415. var geometries = scene.getGeometries();
  32416. for (index = 0; index < geometries.length; index++) {
  32417. var geometry = geometries[index];
  32418. if (geometry.isReady()) {
  32419. serializeGeometry(geometry, serializationObject.geometries);
  32420. }
  32421. }
  32422. // Meshes
  32423. serializationObject.meshes = [];
  32424. for (index = 0; index < scene.meshes.length; index++) {
  32425. var abstractMesh = scene.meshes[index];
  32426. if (abstractMesh instanceof BABYLON.Mesh) {
  32427. var mesh = abstractMesh;
  32428. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32429. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32430. }
  32431. }
  32432. }
  32433. // Particles Systems
  32434. serializationObject.particleSystems = [];
  32435. for (index = 0; index < scene.particleSystems.length; index++) {
  32436. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32437. }
  32438. // Lens flares
  32439. serializationObject.lensFlareSystems = [];
  32440. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32441. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32442. }
  32443. // Shadows
  32444. serializationObject.shadowGenerators = [];
  32445. for (index = 0; index < scene.lights.length; index++) {
  32446. light = scene.lights[index];
  32447. if (light.getShadowGenerator()) {
  32448. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32449. }
  32450. }
  32451. return serializationObject;
  32452. };
  32453. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32454. if (withParents === void 0) { withParents = false; }
  32455. if (withChildren === void 0) { withChildren = false; }
  32456. var serializationObject = {};
  32457. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32458. if (withParents || withChildren) {
  32459. //deliberate for loop! not for each, appended should be processed as well.
  32460. for (var i = 0; i < toSerialize.length; ++i) {
  32461. if (withChildren) {
  32462. toSerialize[i].getDescendants().forEach(function (node) {
  32463. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32464. toSerialize.push(node);
  32465. }
  32466. });
  32467. }
  32468. //make sure the array doesn't contain the object already
  32469. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32470. toSerialize.push(toSerialize[i].parent);
  32471. }
  32472. }
  32473. }
  32474. toSerialize.forEach(function (mesh) {
  32475. finalizeSingleMesh(mesh, serializationObject);
  32476. });
  32477. return serializationObject;
  32478. };
  32479. return SceneSerializer;
  32480. })();
  32481. BABYLON.SceneSerializer = SceneSerializer;
  32482. })(BABYLON || (BABYLON = {}));
  32483. var BABYLON;
  32484. (function (BABYLON) {
  32485. // Unique ID when we import meshes from Babylon to CSG
  32486. var currentCSGMeshId = 0;
  32487. // # class Vertex
  32488. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32489. // one to provide additional features like texture coordinates and vertex
  32490. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32491. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32492. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32493. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32494. // is not used anywhere else.
  32495. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32496. var Vertex = (function () {
  32497. function Vertex(pos, normal, uv) {
  32498. this.pos = pos;
  32499. this.normal = normal;
  32500. this.uv = uv;
  32501. }
  32502. Vertex.prototype.clone = function () {
  32503. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32504. };
  32505. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32506. // orientation of a polygon is flipped.
  32507. Vertex.prototype.flip = function () {
  32508. this.normal = this.normal.scale(-1);
  32509. };
  32510. // Create a new vertex between this vertex and `other` by linearly
  32511. // interpolating all properties using a parameter of `t`. Subclasses should
  32512. // override this to interpolate additional properties.
  32513. Vertex.prototype.interpolate = function (other, t) {
  32514. 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));
  32515. };
  32516. return Vertex;
  32517. })();
  32518. // # class Plane
  32519. // Represents a plane in 3D space.
  32520. var Plane = (function () {
  32521. function Plane(normal, w) {
  32522. this.normal = normal;
  32523. this.w = w;
  32524. }
  32525. Plane.FromPoints = function (a, b, c) {
  32526. var v0 = c.subtract(a);
  32527. var v1 = b.subtract(a);
  32528. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32529. return null;
  32530. }
  32531. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32532. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32533. };
  32534. Plane.prototype.clone = function () {
  32535. return new Plane(this.normal.clone(), this.w);
  32536. };
  32537. Plane.prototype.flip = function () {
  32538. this.normal.scaleInPlace(-1);
  32539. this.w = -this.w;
  32540. };
  32541. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32542. // fragments in the appropriate lists. Coplanar polygons go into either
  32543. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32544. // respect to this plane. Polygons in front or in back of this plane go into
  32545. // either `front` or `back`.
  32546. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32547. var COPLANAR = 0;
  32548. var FRONT = 1;
  32549. var BACK = 2;
  32550. var SPANNING = 3;
  32551. // Classify each point as well as the entire polygon into one of the above
  32552. // four classes.
  32553. var polygonType = 0;
  32554. var types = [];
  32555. var i;
  32556. var t;
  32557. for (i = 0; i < polygon.vertices.length; i++) {
  32558. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32559. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32560. polygonType |= type;
  32561. types.push(type);
  32562. }
  32563. // Put the polygon in the correct list, splitting it when necessary.
  32564. switch (polygonType) {
  32565. case COPLANAR:
  32566. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32567. break;
  32568. case FRONT:
  32569. front.push(polygon);
  32570. break;
  32571. case BACK:
  32572. back.push(polygon);
  32573. break;
  32574. case SPANNING:
  32575. var f = [], b = [];
  32576. for (i = 0; i < polygon.vertices.length; i++) {
  32577. var j = (i + 1) % polygon.vertices.length;
  32578. var ti = types[i], tj = types[j];
  32579. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32580. if (ti !== BACK)
  32581. f.push(vi);
  32582. if (ti !== FRONT)
  32583. b.push(ti !== BACK ? vi.clone() : vi);
  32584. if ((ti | tj) === SPANNING) {
  32585. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32586. var v = vi.interpolate(vj, t);
  32587. f.push(v);
  32588. b.push(v.clone());
  32589. }
  32590. }
  32591. var poly;
  32592. if (f.length >= 3) {
  32593. poly = new Polygon(f, polygon.shared);
  32594. if (poly.plane)
  32595. front.push(poly);
  32596. }
  32597. if (b.length >= 3) {
  32598. poly = new Polygon(b, polygon.shared);
  32599. if (poly.plane)
  32600. back.push(poly);
  32601. }
  32602. break;
  32603. }
  32604. };
  32605. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32606. // point is on the plane.
  32607. Plane.EPSILON = 1e-5;
  32608. return Plane;
  32609. })();
  32610. // # class Polygon
  32611. // Represents a convex polygon. The vertices used to initialize a polygon must
  32612. // be coplanar and form a convex loop.
  32613. //
  32614. // Each convex polygon has a `shared` property, which is shared between all
  32615. // polygons that are clones of each other or were split from the same polygon.
  32616. // This can be used to define per-polygon properties (such as surface color).
  32617. var Polygon = (function () {
  32618. function Polygon(vertices, shared) {
  32619. this.vertices = vertices;
  32620. this.shared = shared;
  32621. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32622. }
  32623. Polygon.prototype.clone = function () {
  32624. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32625. return new Polygon(vertices, this.shared);
  32626. };
  32627. Polygon.prototype.flip = function () {
  32628. this.vertices.reverse().map(function (v) { v.flip(); });
  32629. this.plane.flip();
  32630. };
  32631. return Polygon;
  32632. })();
  32633. // # class Node
  32634. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32635. // by picking a polygon to split along. That polygon (and all other coplanar
  32636. // polygons) are added directly to that node and the other polygons are added to
  32637. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32638. // no distinction between internal and leaf nodes.
  32639. var Node = (function () {
  32640. function Node(polygons) {
  32641. this.plane = null;
  32642. this.front = null;
  32643. this.back = null;
  32644. this.polygons = [];
  32645. if (polygons) {
  32646. this.build(polygons);
  32647. }
  32648. }
  32649. Node.prototype.clone = function () {
  32650. var node = new Node();
  32651. node.plane = this.plane && this.plane.clone();
  32652. node.front = this.front && this.front.clone();
  32653. node.back = this.back && this.back.clone();
  32654. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32655. return node;
  32656. };
  32657. // Convert solid space to empty space and empty space to solid space.
  32658. Node.prototype.invert = function () {
  32659. for (var i = 0; i < this.polygons.length; i++) {
  32660. this.polygons[i].flip();
  32661. }
  32662. if (this.plane) {
  32663. this.plane.flip();
  32664. }
  32665. if (this.front) {
  32666. this.front.invert();
  32667. }
  32668. if (this.back) {
  32669. this.back.invert();
  32670. }
  32671. var temp = this.front;
  32672. this.front = this.back;
  32673. this.back = temp;
  32674. };
  32675. // Recursively remove all polygons in `polygons` that are inside this BSP
  32676. // tree.
  32677. Node.prototype.clipPolygons = function (polygons) {
  32678. if (!this.plane)
  32679. return polygons.slice();
  32680. var front = [], back = [];
  32681. for (var i = 0; i < polygons.length; i++) {
  32682. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32683. }
  32684. if (this.front) {
  32685. front = this.front.clipPolygons(front);
  32686. }
  32687. if (this.back) {
  32688. back = this.back.clipPolygons(back);
  32689. }
  32690. else {
  32691. back = [];
  32692. }
  32693. return front.concat(back);
  32694. };
  32695. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32696. // `bsp`.
  32697. Node.prototype.clipTo = function (bsp) {
  32698. this.polygons = bsp.clipPolygons(this.polygons);
  32699. if (this.front)
  32700. this.front.clipTo(bsp);
  32701. if (this.back)
  32702. this.back.clipTo(bsp);
  32703. };
  32704. // Return a list of all polygons in this BSP tree.
  32705. Node.prototype.allPolygons = function () {
  32706. var polygons = this.polygons.slice();
  32707. if (this.front)
  32708. polygons = polygons.concat(this.front.allPolygons());
  32709. if (this.back)
  32710. polygons = polygons.concat(this.back.allPolygons());
  32711. return polygons;
  32712. };
  32713. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32714. // new polygons are filtered down to the bottom of the tree and become new
  32715. // nodes there. Each set of polygons is partitioned using the first polygon
  32716. // (no heuristic is used to pick a good split).
  32717. Node.prototype.build = function (polygons) {
  32718. if (!polygons.length)
  32719. return;
  32720. if (!this.plane)
  32721. this.plane = polygons[0].plane.clone();
  32722. var front = [], back = [];
  32723. for (var i = 0; i < polygons.length; i++) {
  32724. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32725. }
  32726. if (front.length) {
  32727. if (!this.front)
  32728. this.front = new Node();
  32729. this.front.build(front);
  32730. }
  32731. if (back.length) {
  32732. if (!this.back)
  32733. this.back = new Node();
  32734. this.back.build(back);
  32735. }
  32736. };
  32737. return Node;
  32738. })();
  32739. var CSG = (function () {
  32740. function CSG() {
  32741. this.polygons = new Array();
  32742. }
  32743. // Convert BABYLON.Mesh to BABYLON.CSG
  32744. CSG.FromMesh = function (mesh) {
  32745. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32746. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32747. if (mesh instanceof BABYLON.Mesh) {
  32748. mesh.computeWorldMatrix(true);
  32749. matrix = mesh.getWorldMatrix();
  32750. meshPosition = mesh.position.clone();
  32751. meshRotation = mesh.rotation.clone();
  32752. if (mesh.rotationQuaternion) {
  32753. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32754. }
  32755. meshScaling = mesh.scaling.clone();
  32756. }
  32757. else {
  32758. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32759. }
  32760. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32761. var subMeshes = mesh.subMeshes;
  32762. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32763. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32764. vertices = [];
  32765. for (var j = 0; j < 3; j++) {
  32766. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32767. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32768. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32769. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32770. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32771. vertex = new Vertex(position, normal, uv);
  32772. vertices.push(vertex);
  32773. }
  32774. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32775. // To handle the case of degenerated triangle
  32776. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32777. if (polygon.plane)
  32778. polygons.push(polygon);
  32779. }
  32780. }
  32781. var csg = CSG.FromPolygons(polygons);
  32782. csg.matrix = matrix;
  32783. csg.position = meshPosition;
  32784. csg.rotation = meshRotation;
  32785. csg.scaling = meshScaling;
  32786. csg.rotationQuaternion = meshRotationQuaternion;
  32787. currentCSGMeshId++;
  32788. return csg;
  32789. };
  32790. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32791. CSG.FromPolygons = function (polygons) {
  32792. var csg = new CSG();
  32793. csg.polygons = polygons;
  32794. return csg;
  32795. };
  32796. CSG.prototype.clone = function () {
  32797. var csg = new CSG();
  32798. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32799. csg.copyTransformAttributes(this);
  32800. return csg;
  32801. };
  32802. CSG.prototype.toPolygons = function () {
  32803. return this.polygons;
  32804. };
  32805. CSG.prototype.union = function (csg) {
  32806. var a = new Node(this.clone().polygons);
  32807. var b = new Node(csg.clone().polygons);
  32808. a.clipTo(b);
  32809. b.clipTo(a);
  32810. b.invert();
  32811. b.clipTo(a);
  32812. b.invert();
  32813. a.build(b.allPolygons());
  32814. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32815. };
  32816. CSG.prototype.unionInPlace = function (csg) {
  32817. var a = new Node(this.polygons);
  32818. var b = new Node(csg.polygons);
  32819. a.clipTo(b);
  32820. b.clipTo(a);
  32821. b.invert();
  32822. b.clipTo(a);
  32823. b.invert();
  32824. a.build(b.allPolygons());
  32825. this.polygons = a.allPolygons();
  32826. };
  32827. CSG.prototype.subtract = function (csg) {
  32828. var a = new Node(this.clone().polygons);
  32829. var b = new Node(csg.clone().polygons);
  32830. a.invert();
  32831. a.clipTo(b);
  32832. b.clipTo(a);
  32833. b.invert();
  32834. b.clipTo(a);
  32835. b.invert();
  32836. a.build(b.allPolygons());
  32837. a.invert();
  32838. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32839. };
  32840. CSG.prototype.subtractInPlace = function (csg) {
  32841. var a = new Node(this.polygons);
  32842. var b = new Node(csg.polygons);
  32843. a.invert();
  32844. a.clipTo(b);
  32845. b.clipTo(a);
  32846. b.invert();
  32847. b.clipTo(a);
  32848. b.invert();
  32849. a.build(b.allPolygons());
  32850. a.invert();
  32851. this.polygons = a.allPolygons();
  32852. };
  32853. CSG.prototype.intersect = function (csg) {
  32854. var a = new Node(this.clone().polygons);
  32855. var b = new Node(csg.clone().polygons);
  32856. a.invert();
  32857. b.clipTo(a);
  32858. b.invert();
  32859. a.clipTo(b);
  32860. b.clipTo(a);
  32861. a.build(b.allPolygons());
  32862. a.invert();
  32863. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32864. };
  32865. CSG.prototype.intersectInPlace = function (csg) {
  32866. var a = new Node(this.polygons);
  32867. var b = new Node(csg.polygons);
  32868. a.invert();
  32869. b.clipTo(a);
  32870. b.invert();
  32871. a.clipTo(b);
  32872. b.clipTo(a);
  32873. a.build(b.allPolygons());
  32874. a.invert();
  32875. this.polygons = a.allPolygons();
  32876. };
  32877. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32878. // not modified.
  32879. CSG.prototype.inverse = function () {
  32880. var csg = this.clone();
  32881. csg.inverseInPlace();
  32882. return csg;
  32883. };
  32884. CSG.prototype.inverseInPlace = function () {
  32885. this.polygons.map(function (p) { p.flip(); });
  32886. };
  32887. // This is used to keep meshes transformations so they can be restored
  32888. // when we build back a Babylon Mesh
  32889. // NB : All CSG operations are performed in world coordinates
  32890. CSG.prototype.copyTransformAttributes = function (csg) {
  32891. this.matrix = csg.matrix;
  32892. this.position = csg.position;
  32893. this.rotation = csg.rotation;
  32894. this.scaling = csg.scaling;
  32895. this.rotationQuaternion = csg.rotationQuaternion;
  32896. return this;
  32897. };
  32898. // Build Raw mesh from CSG
  32899. // Coordinates here are in world space
  32900. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32901. var matrix = this.matrix.clone();
  32902. matrix.invert();
  32903. 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;
  32904. if (keepSubMeshes) {
  32905. // Sort Polygons, since subMeshes are indices range
  32906. polygons.sort(function (a, b) {
  32907. if (a.shared.meshId === b.shared.meshId) {
  32908. return a.shared.subMeshId - b.shared.subMeshId;
  32909. }
  32910. else {
  32911. return a.shared.meshId - b.shared.meshId;
  32912. }
  32913. });
  32914. }
  32915. for (var i = 0, il = polygons.length; i < il; i++) {
  32916. polygon = polygons[i];
  32917. // Building SubMeshes
  32918. if (!subMesh_dict[polygon.shared.meshId]) {
  32919. subMesh_dict[polygon.shared.meshId] = {};
  32920. }
  32921. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32922. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32923. indexStart: +Infinity,
  32924. indexEnd: -Infinity,
  32925. materialIndex: polygon.shared.materialIndex
  32926. };
  32927. }
  32928. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32929. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32930. polygonIndices[0] = 0;
  32931. polygonIndices[1] = j - 1;
  32932. polygonIndices[2] = j;
  32933. for (var k = 0; k < 3; k++) {
  32934. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32935. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32936. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32937. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32938. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32939. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32940. // Check if 2 points can be merged
  32941. if (!(typeof vertex_idx !== 'undefined' &&
  32942. normals[vertex_idx * 3] === localNormal.x &&
  32943. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32944. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32945. uvs[vertex_idx * 2] === uv.x &&
  32946. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32947. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32948. uvs.push(uv.x, uv.y);
  32949. normals.push(normal.x, normal.y, normal.z);
  32950. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32951. }
  32952. indices.push(vertex_idx);
  32953. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32954. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32955. currentIndex++;
  32956. }
  32957. }
  32958. }
  32959. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32960. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32961. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32962. mesh.setIndices(indices);
  32963. if (keepSubMeshes) {
  32964. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32965. var materialIndexOffset = 0, materialMaxIndex;
  32966. mesh.subMeshes = new Array();
  32967. for (var m in subMesh_dict) {
  32968. materialMaxIndex = -1;
  32969. for (var sm in subMesh_dict[m]) {
  32970. subMesh_obj = subMesh_dict[m][sm];
  32971. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32972. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32973. }
  32974. materialIndexOffset += ++materialMaxIndex;
  32975. }
  32976. }
  32977. return mesh;
  32978. };
  32979. // Build Mesh from CSG taking material and transforms into account
  32980. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32981. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32982. mesh.material = material;
  32983. mesh.position.copyFrom(this.position);
  32984. mesh.rotation.copyFrom(this.rotation);
  32985. if (this.rotationQuaternion) {
  32986. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32987. }
  32988. mesh.scaling.copyFrom(this.scaling);
  32989. mesh.computeWorldMatrix(true);
  32990. return mesh;
  32991. };
  32992. return CSG;
  32993. })();
  32994. BABYLON.CSG = CSG;
  32995. })(BABYLON || (BABYLON = {}));
  32996. var BABYLON;
  32997. (function (BABYLON) {
  32998. var VRDistortionCorrectionPostProcess = (function (_super) {
  32999. __extends(VRDistortionCorrectionPostProcess, _super);
  33000. //ANY
  33001. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  33002. var _this = this;
  33003. _super.call(this, name, "vrDistortionCorrection", [
  33004. 'LensCenter',
  33005. 'Scale',
  33006. 'ScaleIn',
  33007. 'HmdWarpParam'
  33008. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  33009. this._isRightEye = isRightEye;
  33010. this._distortionFactors = vrMetrics.distortionK;
  33011. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  33012. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  33013. this.onSizeChanged = function () {
  33014. _this.aspectRatio = _this.width * .5 / _this.height;
  33015. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  33016. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  33017. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  33018. };
  33019. this.onApply = function (effect) {
  33020. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  33021. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  33022. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  33023. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  33024. };
  33025. }
  33026. return VRDistortionCorrectionPostProcess;
  33027. })(BABYLON.PostProcess);
  33028. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  33029. })(BABYLON || (BABYLON = {}));
  33030. // Mainly based on these 2 articles :
  33031. // 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
  33032. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  33033. var BABYLON;
  33034. (function (BABYLON) {
  33035. (function (JoystickAxis) {
  33036. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  33037. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  33038. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  33039. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  33040. var JoystickAxis = BABYLON.JoystickAxis;
  33041. var VirtualJoystick = (function () {
  33042. function VirtualJoystick(leftJoystick) {
  33043. var _this = this;
  33044. if (leftJoystick) {
  33045. this._leftJoystick = true;
  33046. }
  33047. else {
  33048. this._leftJoystick = false;
  33049. }
  33050. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  33051. VirtualJoystick._globalJoystickIndex++;
  33052. // By default left & right arrow keys are moving the X
  33053. // and up & down keys are moving the Y
  33054. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33055. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33056. this.reverseLeftRight = false;
  33057. this.reverseUpDown = false;
  33058. // collections of pointers
  33059. this._touches = new BABYLON.SmartCollection();
  33060. this.deltaPosition = BABYLON.Vector3.Zero();
  33061. this._joystickSensibility = 25;
  33062. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33063. this._rotationSpeed = 25;
  33064. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  33065. this._rotateOnAxisRelativeToMesh = false;
  33066. this._onResize = function (evt) {
  33067. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33068. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33069. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  33070. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  33071. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  33072. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  33073. };
  33074. // injecting a canvas element on top of the canvas 3D game
  33075. if (!VirtualJoystick.vjCanvas) {
  33076. window.addEventListener("resize", this._onResize, false);
  33077. VirtualJoystick.vjCanvas = document.createElement("canvas");
  33078. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33079. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33080. VirtualJoystick.vjCanvas.width = window.innerWidth;
  33081. VirtualJoystick.vjCanvas.height = window.innerHeight;
  33082. VirtualJoystick.vjCanvas.style.width = "100%";
  33083. VirtualJoystick.vjCanvas.style.height = "100%";
  33084. VirtualJoystick.vjCanvas.style.position = "absolute";
  33085. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  33086. VirtualJoystick.vjCanvas.style.top = "0px";
  33087. VirtualJoystick.vjCanvas.style.left = "0px";
  33088. VirtualJoystick.vjCanvas.style.zIndex = "5";
  33089. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  33090. // Support for jQuery PEP polyfill
  33091. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  33092. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  33093. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  33094. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33095. document.body.appendChild(VirtualJoystick.vjCanvas);
  33096. }
  33097. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  33098. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  33099. this.pressed = false;
  33100. // default joystick color
  33101. this._joystickColor = "cyan";
  33102. this._joystickPointerID = -1;
  33103. // current joystick position
  33104. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  33105. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  33106. // origin joystick position
  33107. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  33108. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  33109. this._onPointerDownHandlerRef = function (evt) {
  33110. _this._onPointerDown(evt);
  33111. };
  33112. this._onPointerMoveHandlerRef = function (evt) {
  33113. _this._onPointerMove(evt);
  33114. };
  33115. this._onPointerOutHandlerRef = function (evt) {
  33116. _this._onPointerUp(evt);
  33117. };
  33118. this._onPointerUpHandlerRef = function (evt) {
  33119. _this._onPointerUp(evt);
  33120. };
  33121. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  33122. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  33123. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  33124. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  33125. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  33126. evt.preventDefault(); // Disables system menu
  33127. }, false);
  33128. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33129. }
  33130. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  33131. this._joystickSensibility = newJoystickSensibility;
  33132. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33133. };
  33134. VirtualJoystick.prototype._onPointerDown = function (e) {
  33135. var positionOnScreenCondition;
  33136. e.preventDefault();
  33137. if (this._leftJoystick === true) {
  33138. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  33139. }
  33140. else {
  33141. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  33142. }
  33143. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33144. // First contact will be dedicated to the virtual joystick
  33145. this._joystickPointerID = e.pointerId;
  33146. this._joystickPointerStartPos.x = e.clientX;
  33147. this._joystickPointerStartPos.y = e.clientY;
  33148. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33149. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33150. this._deltaJoystickVector.x = 0;
  33151. this._deltaJoystickVector.y = 0;
  33152. this.pressed = true;
  33153. this._touches.add(e.pointerId.toString(), e);
  33154. }
  33155. else {
  33156. // You can only trigger the action buttons with a joystick declared
  33157. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33158. this._action();
  33159. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33160. }
  33161. }
  33162. };
  33163. VirtualJoystick.prototype._onPointerMove = function (e) {
  33164. // If the current pointer is the one associated to the joystick (first touch contact)
  33165. if (this._joystickPointerID == e.pointerId) {
  33166. this._joystickPointerPos.x = e.clientX;
  33167. this._joystickPointerPos.y = e.clientY;
  33168. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33169. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33170. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33171. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33172. switch (this._axisTargetedByLeftAndRight) {
  33173. case JoystickAxis.X:
  33174. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33175. break;
  33176. case JoystickAxis.Y:
  33177. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33178. break;
  33179. case JoystickAxis.Z:
  33180. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33181. break;
  33182. }
  33183. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33184. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33185. switch (this._axisTargetedByUpAndDown) {
  33186. case JoystickAxis.X:
  33187. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33188. break;
  33189. case JoystickAxis.Y:
  33190. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33191. break;
  33192. case JoystickAxis.Z:
  33193. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33194. break;
  33195. }
  33196. }
  33197. else {
  33198. if (this._touches.item(e.pointerId.toString())) {
  33199. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33200. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33201. }
  33202. }
  33203. };
  33204. VirtualJoystick.prototype._onPointerUp = function (e) {
  33205. if (this._joystickPointerID == e.pointerId) {
  33206. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33207. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33208. this._joystickPointerID = -1;
  33209. this.pressed = false;
  33210. }
  33211. else {
  33212. var touch = this._touches.item(e.pointerId.toString());
  33213. if (touch) {
  33214. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33215. }
  33216. }
  33217. this._deltaJoystickVector.x = 0;
  33218. this._deltaJoystickVector.y = 0;
  33219. this._touches.remove(e.pointerId.toString());
  33220. };
  33221. /**
  33222. * Change the color of the virtual joystick
  33223. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33224. */
  33225. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33226. this._joystickColor = newColor;
  33227. };
  33228. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33229. this._action = action;
  33230. };
  33231. // Define which axis you'd like to control for left & right
  33232. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33233. switch (axis) {
  33234. case JoystickAxis.X:
  33235. case JoystickAxis.Y:
  33236. case JoystickAxis.Z:
  33237. this._axisTargetedByLeftAndRight = axis;
  33238. break;
  33239. default:
  33240. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33241. break;
  33242. }
  33243. };
  33244. // Define which axis you'd like to control for up & down
  33245. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33246. switch (axis) {
  33247. case JoystickAxis.X:
  33248. case JoystickAxis.Y:
  33249. case JoystickAxis.Z:
  33250. this._axisTargetedByUpAndDown = axis;
  33251. break;
  33252. default:
  33253. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33254. break;
  33255. }
  33256. };
  33257. VirtualJoystick.prototype._clearCanvas = function () {
  33258. if (this._leftJoystick) {
  33259. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33260. }
  33261. else {
  33262. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33263. }
  33264. };
  33265. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33266. var _this = this;
  33267. if (this.pressed) {
  33268. this._touches.forEach(function (touch) {
  33269. if (touch.pointerId === _this._joystickPointerID) {
  33270. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33271. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33272. VirtualJoystick.vjCanvasContext.beginPath();
  33273. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33274. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33275. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33276. VirtualJoystick.vjCanvasContext.stroke();
  33277. VirtualJoystick.vjCanvasContext.closePath();
  33278. VirtualJoystick.vjCanvasContext.beginPath();
  33279. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33280. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33281. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33282. VirtualJoystick.vjCanvasContext.stroke();
  33283. VirtualJoystick.vjCanvasContext.closePath();
  33284. VirtualJoystick.vjCanvasContext.beginPath();
  33285. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33286. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33287. VirtualJoystick.vjCanvasContext.stroke();
  33288. VirtualJoystick.vjCanvasContext.closePath();
  33289. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33290. }
  33291. else {
  33292. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33293. VirtualJoystick.vjCanvasContext.beginPath();
  33294. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33295. VirtualJoystick.vjCanvasContext.beginPath();
  33296. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33297. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33298. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33299. VirtualJoystick.vjCanvasContext.stroke();
  33300. VirtualJoystick.vjCanvasContext.closePath();
  33301. touch.prevX = touch.x;
  33302. touch.prevY = touch.y;
  33303. }
  33304. ;
  33305. });
  33306. }
  33307. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33308. };
  33309. VirtualJoystick.prototype.releaseCanvas = function () {
  33310. if (VirtualJoystick.vjCanvas) {
  33311. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33312. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33313. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33314. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33315. window.removeEventListener("resize", this._onResize);
  33316. document.body.removeChild(VirtualJoystick.vjCanvas);
  33317. VirtualJoystick.vjCanvas = null;
  33318. }
  33319. };
  33320. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33321. VirtualJoystick._globalJoystickIndex = 0;
  33322. return VirtualJoystick;
  33323. })();
  33324. BABYLON.VirtualJoystick = VirtualJoystick;
  33325. })(BABYLON || (BABYLON = {}));
  33326. var BABYLON;
  33327. (function (BABYLON) {
  33328. // We're mainly based on the logic defined into the FreeCamera code
  33329. var VirtualJoysticksCamera = (function (_super) {
  33330. __extends(VirtualJoysticksCamera, _super);
  33331. function VirtualJoysticksCamera(name, position, scene) {
  33332. _super.call(this, name, position, scene);
  33333. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33334. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33335. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33336. this._leftjoystick.setJoystickSensibility(0.15);
  33337. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33338. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33339. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33340. this._rightjoystick.reverseUpDown = true;
  33341. this._rightjoystick.setJoystickSensibility(0.05);
  33342. this._rightjoystick.setJoystickColor("yellow");
  33343. }
  33344. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33345. return this._leftjoystick;
  33346. };
  33347. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33348. return this._rightjoystick;
  33349. };
  33350. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33351. var speed = this._computeLocalCameraSpeed() * 50;
  33352. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33353. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33354. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33355. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33356. if (!this._leftjoystick.pressed) {
  33357. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33358. }
  33359. if (!this._rightjoystick.pressed) {
  33360. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33361. }
  33362. _super.prototype._checkInputs.call(this);
  33363. };
  33364. VirtualJoysticksCamera.prototype.dispose = function () {
  33365. this._leftjoystick.releaseCanvas();
  33366. _super.prototype.dispose.call(this);
  33367. };
  33368. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33369. return "VirtualJoysticksCamera";
  33370. };
  33371. return VirtualJoysticksCamera;
  33372. })(BABYLON.FreeCamera);
  33373. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33374. })(BABYLON || (BABYLON = {}));
  33375. var BABYLON;
  33376. (function (BABYLON) {
  33377. var AnaglyphPostProcess = (function (_super) {
  33378. __extends(AnaglyphPostProcess, _super);
  33379. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33380. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33381. }
  33382. return AnaglyphPostProcess;
  33383. })(BABYLON.PostProcess);
  33384. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33385. })(BABYLON || (BABYLON = {}));
  33386. var BABYLON;
  33387. (function (BABYLON) {
  33388. var OutlineRenderer = (function () {
  33389. function OutlineRenderer(scene) {
  33390. this._scene = scene;
  33391. }
  33392. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33393. var _this = this;
  33394. if (useOverlay === void 0) { useOverlay = false; }
  33395. var scene = this._scene;
  33396. var engine = this._scene.getEngine();
  33397. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33398. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33399. return;
  33400. }
  33401. var mesh = subMesh.getRenderingMesh();
  33402. var material = subMesh.getMaterial();
  33403. engine.enableEffect(this._effect);
  33404. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33405. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33406. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33407. // Bones
  33408. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33409. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33410. }
  33411. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33412. // Alpha test
  33413. if (material && material.needAlphaTesting()) {
  33414. var alphaTexture = material.getAlphaTestTexture();
  33415. this._effect.setTexture("diffuseSampler", alphaTexture);
  33416. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33417. }
  33418. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33419. };
  33420. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33421. var defines = [];
  33422. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33423. var mesh = subMesh.getMesh();
  33424. var material = subMesh.getMaterial();
  33425. // Alpha test
  33426. if (material && material.needAlphaTesting()) {
  33427. defines.push("#define ALPHATEST");
  33428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33429. attribs.push(BABYLON.VertexBuffer.UVKind);
  33430. defines.push("#define UV1");
  33431. }
  33432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33433. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33434. defines.push("#define UV2");
  33435. }
  33436. }
  33437. // Bones
  33438. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33439. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33440. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33441. if (mesh.numBoneInfluencers > 4) {
  33442. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33443. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33444. }
  33445. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33446. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33447. }
  33448. else {
  33449. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33450. }
  33451. // Instances
  33452. if (useInstances) {
  33453. defines.push("#define INSTANCES");
  33454. attribs.push("world0");
  33455. attribs.push("world1");
  33456. attribs.push("world2");
  33457. attribs.push("world3");
  33458. }
  33459. // Get correct effect
  33460. var join = defines.join("\n");
  33461. if (this._cachedDefines !== join) {
  33462. this._cachedDefines = join;
  33463. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33464. }
  33465. return this._effect.isReady();
  33466. };
  33467. return OutlineRenderer;
  33468. })();
  33469. BABYLON.OutlineRenderer = OutlineRenderer;
  33470. })(BABYLON || (BABYLON = {}));
  33471. var BABYLON;
  33472. (function (BABYLON) {
  33473. var MeshAssetTask = (function () {
  33474. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33475. this.name = name;
  33476. this.meshesNames = meshesNames;
  33477. this.rootUrl = rootUrl;
  33478. this.sceneFilename = sceneFilename;
  33479. this.isCompleted = false;
  33480. }
  33481. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33482. var _this = this;
  33483. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33484. _this.loadedMeshes = meshes;
  33485. _this.loadedParticleSystems = particleSystems;
  33486. _this.loadedSkeletons = skeletons;
  33487. _this.isCompleted = true;
  33488. if (_this.onSuccess) {
  33489. _this.onSuccess(_this);
  33490. }
  33491. onSuccess();
  33492. }, null, function () {
  33493. if (_this.onError) {
  33494. _this.onError(_this);
  33495. }
  33496. onError();
  33497. });
  33498. };
  33499. return MeshAssetTask;
  33500. })();
  33501. BABYLON.MeshAssetTask = MeshAssetTask;
  33502. var TextFileAssetTask = (function () {
  33503. function TextFileAssetTask(name, url) {
  33504. this.name = name;
  33505. this.url = url;
  33506. this.isCompleted = false;
  33507. }
  33508. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33509. var _this = this;
  33510. BABYLON.Tools.LoadFile(this.url, function (data) {
  33511. _this.text = data;
  33512. _this.isCompleted = true;
  33513. if (_this.onSuccess) {
  33514. _this.onSuccess(_this);
  33515. }
  33516. onSuccess();
  33517. }, null, scene.database, false, function () {
  33518. if (_this.onError) {
  33519. _this.onError(_this);
  33520. }
  33521. onError();
  33522. });
  33523. };
  33524. return TextFileAssetTask;
  33525. })();
  33526. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33527. var BinaryFileAssetTask = (function () {
  33528. function BinaryFileAssetTask(name, url) {
  33529. this.name = name;
  33530. this.url = url;
  33531. this.isCompleted = false;
  33532. }
  33533. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33534. var _this = this;
  33535. BABYLON.Tools.LoadFile(this.url, function (data) {
  33536. _this.data = data;
  33537. _this.isCompleted = true;
  33538. if (_this.onSuccess) {
  33539. _this.onSuccess(_this);
  33540. }
  33541. onSuccess();
  33542. }, null, scene.database, true, function () {
  33543. if (_this.onError) {
  33544. _this.onError(_this);
  33545. }
  33546. onError();
  33547. });
  33548. };
  33549. return BinaryFileAssetTask;
  33550. })();
  33551. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33552. var ImageAssetTask = (function () {
  33553. function ImageAssetTask(name, url) {
  33554. this.name = name;
  33555. this.url = url;
  33556. this.isCompleted = false;
  33557. }
  33558. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33559. var _this = this;
  33560. var img = new Image();
  33561. img.onload = function () {
  33562. _this.image = img;
  33563. _this.isCompleted = true;
  33564. if (_this.onSuccess) {
  33565. _this.onSuccess(_this);
  33566. }
  33567. onSuccess();
  33568. };
  33569. img.onerror = function () {
  33570. if (_this.onError) {
  33571. _this.onError(_this);
  33572. }
  33573. onError();
  33574. };
  33575. img.src = this.url;
  33576. };
  33577. return ImageAssetTask;
  33578. })();
  33579. BABYLON.ImageAssetTask = ImageAssetTask;
  33580. var TextureAssetTask = (function () {
  33581. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33583. this.name = name;
  33584. this.url = url;
  33585. this.noMipmap = noMipmap;
  33586. this.invertY = invertY;
  33587. this.samplingMode = samplingMode;
  33588. this.isCompleted = false;
  33589. }
  33590. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33591. var _this = this;
  33592. var onload = function () {
  33593. _this.isCompleted = true;
  33594. if (_this.onSuccess) {
  33595. _this.onSuccess(_this);
  33596. }
  33597. onSuccess();
  33598. };
  33599. var onerror = function () {
  33600. if (_this.onError) {
  33601. _this.onError(_this);
  33602. }
  33603. onError();
  33604. };
  33605. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33606. };
  33607. return TextureAssetTask;
  33608. })();
  33609. BABYLON.TextureAssetTask = TextureAssetTask;
  33610. var AssetsManager = (function () {
  33611. function AssetsManager(scene) {
  33612. this._tasks = new Array();
  33613. this._waitingTasksCount = 0;
  33614. this.useDefaultLoadingScreen = true;
  33615. this._scene = scene;
  33616. }
  33617. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33618. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33619. this._tasks.push(task);
  33620. return task;
  33621. };
  33622. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33623. var task = new TextFileAssetTask(taskName, url);
  33624. this._tasks.push(task);
  33625. return task;
  33626. };
  33627. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33628. var task = new BinaryFileAssetTask(taskName, url);
  33629. this._tasks.push(task);
  33630. return task;
  33631. };
  33632. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33633. var task = new ImageAssetTask(taskName, url);
  33634. this._tasks.push(task);
  33635. return task;
  33636. };
  33637. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33639. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33640. this._tasks.push(task);
  33641. return task;
  33642. };
  33643. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33644. this._waitingTasksCount--;
  33645. if (this._waitingTasksCount === 0) {
  33646. if (this.onFinish) {
  33647. this.onFinish(this._tasks);
  33648. }
  33649. this._scene.getEngine().hideLoadingUI();
  33650. }
  33651. };
  33652. AssetsManager.prototype._runTask = function (task) {
  33653. var _this = this;
  33654. task.run(this._scene, function () {
  33655. if (_this.onTaskSuccess) {
  33656. _this.onTaskSuccess(task);
  33657. }
  33658. _this._decreaseWaitingTasksCount();
  33659. }, function () {
  33660. if (_this.onTaskError) {
  33661. _this.onTaskError(task);
  33662. }
  33663. _this._decreaseWaitingTasksCount();
  33664. });
  33665. };
  33666. AssetsManager.prototype.reset = function () {
  33667. this._tasks = new Array();
  33668. return this;
  33669. };
  33670. AssetsManager.prototype.load = function () {
  33671. this._waitingTasksCount = this._tasks.length;
  33672. if (this._waitingTasksCount === 0) {
  33673. if (this.onFinish) {
  33674. this.onFinish(this._tasks);
  33675. }
  33676. return this;
  33677. }
  33678. if (this.useDefaultLoadingScreen) {
  33679. this._scene.getEngine().displayLoadingUI();
  33680. }
  33681. for (var index = 0; index < this._tasks.length; index++) {
  33682. var task = this._tasks[index];
  33683. this._runTask(task);
  33684. }
  33685. return this;
  33686. };
  33687. return AssetsManager;
  33688. })();
  33689. BABYLON.AssetsManager = AssetsManager;
  33690. })(BABYLON || (BABYLON = {}));
  33691. var BABYLON;
  33692. (function (BABYLON) {
  33693. var VRCameraMetrics = (function () {
  33694. function VRCameraMetrics() {
  33695. this.compensateDistortion = true;
  33696. }
  33697. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33698. get: function () {
  33699. return this.hResolution / (2 * this.vResolution);
  33700. },
  33701. enumerable: true,
  33702. configurable: true
  33703. });
  33704. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33705. get: function () {
  33706. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33707. },
  33708. enumerable: true,
  33709. configurable: true
  33710. });
  33711. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33712. get: function () {
  33713. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33714. var h = (4 * meters) / this.hScreenSize;
  33715. return BABYLON.Matrix.Translation(h, 0, 0);
  33716. },
  33717. enumerable: true,
  33718. configurable: true
  33719. });
  33720. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33721. get: function () {
  33722. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33723. var h = (4 * meters) / this.hScreenSize;
  33724. return BABYLON.Matrix.Translation(-h, 0, 0);
  33725. },
  33726. enumerable: true,
  33727. configurable: true
  33728. });
  33729. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33730. get: function () {
  33731. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33732. },
  33733. enumerable: true,
  33734. configurable: true
  33735. });
  33736. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33737. get: function () {
  33738. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33739. },
  33740. enumerable: true,
  33741. configurable: true
  33742. });
  33743. VRCameraMetrics.GetDefault = function () {
  33744. var result = new VRCameraMetrics();
  33745. result.hResolution = 1280;
  33746. result.vResolution = 800;
  33747. result.hScreenSize = 0.149759993;
  33748. result.vScreenSize = 0.0935999975;
  33749. result.vScreenCenter = 0.0467999987,
  33750. result.eyeToScreenDistance = 0.0410000011;
  33751. result.lensSeparationDistance = 0.0635000020;
  33752. result.interpupillaryDistance = 0.0640000030;
  33753. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33754. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33755. result.postProcessScaleFactor = 1.714605507808412;
  33756. result.lensCenterOffset = 0.151976421;
  33757. return result;
  33758. };
  33759. return VRCameraMetrics;
  33760. })();
  33761. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33762. })(BABYLON || (BABYLON = {}));
  33763. var BABYLON;
  33764. (function (BABYLON) {
  33765. var VRDeviceOrientationFreeCamera = (function (_super) {
  33766. __extends(VRDeviceOrientationFreeCamera, _super);
  33767. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33768. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33769. _super.call(this, name, position, scene);
  33770. this._alpha = 0;
  33771. this._beta = 0;
  33772. this._gamma = 0;
  33773. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33774. metrics.compensateDistortion = compensateDistortion;
  33775. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33776. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33777. }
  33778. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33779. this._alpha = +evt.alpha | 0;
  33780. this._beta = +evt.beta | 0;
  33781. this._gamma = +evt.gamma | 0;
  33782. if (this._gamma < 0) {
  33783. this._gamma = 90 + this._gamma;
  33784. }
  33785. else {
  33786. // Incline it in the correct angle.
  33787. this._gamma = 270 - this._gamma;
  33788. }
  33789. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33790. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33791. this.rotation.z = this._beta / 180.0 * Math.PI;
  33792. };
  33793. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33794. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33795. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33796. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33797. };
  33798. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33799. _super.prototype.detachControl.call(this, element);
  33800. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33801. };
  33802. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33803. return "VRDeviceOrientationFreeCamera";
  33804. };
  33805. return VRDeviceOrientationFreeCamera;
  33806. })(BABYLON.FreeCamera);
  33807. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33808. })(BABYLON || (BABYLON = {}));
  33809. var BABYLON;
  33810. (function (BABYLON) {
  33811. var WebVRFreeCamera = (function (_super) {
  33812. __extends(WebVRFreeCamera, _super);
  33813. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33814. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33815. _super.call(this, name, position, scene);
  33816. this._hmdDevice = null;
  33817. this._sensorDevice = null;
  33818. this._cacheState = null;
  33819. this._cacheQuaternion = new BABYLON.Quaternion();
  33820. this._cacheRotation = BABYLON.Vector3.Zero();
  33821. this._vrEnabled = false;
  33822. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33823. metrics.compensateDistortion = compensateDistortion;
  33824. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33825. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33826. }
  33827. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33828. var size = devices.length;
  33829. var i = 0;
  33830. // Reset devices.
  33831. this._sensorDevice = null;
  33832. this._hmdDevice = null;
  33833. // Search for a HmdDevice.
  33834. while (i < size && this._hmdDevice === null) {
  33835. if (devices[i] instanceof HMDVRDevice) {
  33836. this._hmdDevice = devices[i];
  33837. }
  33838. i++;
  33839. }
  33840. i = 0;
  33841. while (i < size && this._sensorDevice === null) {
  33842. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33843. this._sensorDevice = devices[i];
  33844. }
  33845. i++;
  33846. }
  33847. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33848. };
  33849. WebVRFreeCamera.prototype._checkInputs = function () {
  33850. if (this._vrEnabled) {
  33851. this._cacheState = this._sensorDevice.getState();
  33852. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33853. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33854. this.rotation.x = -this._cacheRotation.x;
  33855. this.rotation.y = -this._cacheRotation.y;
  33856. this.rotation.z = this._cacheRotation.z;
  33857. }
  33858. _super.prototype._checkInputs.call(this);
  33859. };
  33860. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33861. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33862. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33863. if (navigator.getVRDevices) {
  33864. navigator.getVRDevices().then(this._getWebVRDevices);
  33865. }
  33866. else if (navigator.mozGetVRDevices) {
  33867. navigator.mozGetVRDevices(this._getWebVRDevices);
  33868. }
  33869. };
  33870. WebVRFreeCamera.prototype.detachControl = function (element) {
  33871. _super.prototype.detachControl.call(this, element);
  33872. this._vrEnabled = false;
  33873. };
  33874. WebVRFreeCamera.prototype.getTypeName = function () {
  33875. return "WebVRFreeCamera";
  33876. };
  33877. return WebVRFreeCamera;
  33878. })(BABYLON.FreeCamera);
  33879. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33880. })(BABYLON || (BABYLON = {}));
  33881. var BABYLON;
  33882. (function (BABYLON) {
  33883. // Standard optimizations
  33884. var SceneOptimization = (function () {
  33885. function SceneOptimization(priority) {
  33886. if (priority === void 0) { priority = 0; }
  33887. this.priority = priority;
  33888. this.apply = function (scene) {
  33889. return true; // Return true if everything that can be done was applied
  33890. };
  33891. }
  33892. return SceneOptimization;
  33893. })();
  33894. BABYLON.SceneOptimization = SceneOptimization;
  33895. var TextureOptimization = (function (_super) {
  33896. __extends(TextureOptimization, _super);
  33897. function TextureOptimization(priority, maximumSize) {
  33898. var _this = this;
  33899. if (priority === void 0) { priority = 0; }
  33900. if (maximumSize === void 0) { maximumSize = 1024; }
  33901. _super.call(this, priority);
  33902. this.priority = priority;
  33903. this.maximumSize = maximumSize;
  33904. this.apply = function (scene) {
  33905. var allDone = true;
  33906. for (var index = 0; index < scene.textures.length; index++) {
  33907. var texture = scene.textures[index];
  33908. if (!texture.canRescale) {
  33909. continue;
  33910. }
  33911. var currentSize = texture.getSize();
  33912. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33913. if (maxDimension > _this.maximumSize) {
  33914. texture.scale(0.5);
  33915. allDone = false;
  33916. }
  33917. }
  33918. return allDone;
  33919. };
  33920. }
  33921. return TextureOptimization;
  33922. })(SceneOptimization);
  33923. BABYLON.TextureOptimization = TextureOptimization;
  33924. var HardwareScalingOptimization = (function (_super) {
  33925. __extends(HardwareScalingOptimization, _super);
  33926. function HardwareScalingOptimization(priority, maximumScale) {
  33927. var _this = this;
  33928. if (priority === void 0) { priority = 0; }
  33929. if (maximumScale === void 0) { maximumScale = 2; }
  33930. _super.call(this, priority);
  33931. this.priority = priority;
  33932. this.maximumScale = maximumScale;
  33933. this._currentScale = 1;
  33934. this.apply = function (scene) {
  33935. _this._currentScale++;
  33936. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33937. return _this._currentScale >= _this.maximumScale;
  33938. };
  33939. }
  33940. return HardwareScalingOptimization;
  33941. })(SceneOptimization);
  33942. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33943. var ShadowsOptimization = (function (_super) {
  33944. __extends(ShadowsOptimization, _super);
  33945. function ShadowsOptimization() {
  33946. _super.apply(this, arguments);
  33947. this.apply = function (scene) {
  33948. scene.shadowsEnabled = false;
  33949. return true;
  33950. };
  33951. }
  33952. return ShadowsOptimization;
  33953. })(SceneOptimization);
  33954. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33955. var PostProcessesOptimization = (function (_super) {
  33956. __extends(PostProcessesOptimization, _super);
  33957. function PostProcessesOptimization() {
  33958. _super.apply(this, arguments);
  33959. this.apply = function (scene) {
  33960. scene.postProcessesEnabled = false;
  33961. return true;
  33962. };
  33963. }
  33964. return PostProcessesOptimization;
  33965. })(SceneOptimization);
  33966. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33967. var LensFlaresOptimization = (function (_super) {
  33968. __extends(LensFlaresOptimization, _super);
  33969. function LensFlaresOptimization() {
  33970. _super.apply(this, arguments);
  33971. this.apply = function (scene) {
  33972. scene.lensFlaresEnabled = false;
  33973. return true;
  33974. };
  33975. }
  33976. return LensFlaresOptimization;
  33977. })(SceneOptimization);
  33978. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33979. var ParticlesOptimization = (function (_super) {
  33980. __extends(ParticlesOptimization, _super);
  33981. function ParticlesOptimization() {
  33982. _super.apply(this, arguments);
  33983. this.apply = function (scene) {
  33984. scene.particlesEnabled = false;
  33985. return true;
  33986. };
  33987. }
  33988. return ParticlesOptimization;
  33989. })(SceneOptimization);
  33990. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33991. var RenderTargetsOptimization = (function (_super) {
  33992. __extends(RenderTargetsOptimization, _super);
  33993. function RenderTargetsOptimization() {
  33994. _super.apply(this, arguments);
  33995. this.apply = function (scene) {
  33996. scene.renderTargetsEnabled = false;
  33997. return true;
  33998. };
  33999. }
  34000. return RenderTargetsOptimization;
  34001. })(SceneOptimization);
  34002. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  34003. var MergeMeshesOptimization = (function (_super) {
  34004. __extends(MergeMeshesOptimization, _super);
  34005. function MergeMeshesOptimization() {
  34006. var _this = this;
  34007. _super.apply(this, arguments);
  34008. this._canBeMerged = function (abstractMesh) {
  34009. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  34010. return false;
  34011. }
  34012. var mesh = abstractMesh;
  34013. if (!mesh.isVisible || !mesh.isEnabled()) {
  34014. return false;
  34015. }
  34016. if (mesh.instances.length > 0) {
  34017. return false;
  34018. }
  34019. if (mesh.skeleton || mesh.hasLODLevels) {
  34020. return false;
  34021. }
  34022. if (mesh.parent) {
  34023. return false;
  34024. }
  34025. return true;
  34026. };
  34027. this.apply = function (scene, updateSelectionTree) {
  34028. var globalPool = scene.meshes.slice(0);
  34029. var globalLength = globalPool.length;
  34030. for (var index = 0; index < globalLength; index++) {
  34031. var currentPool = new Array();
  34032. var current = globalPool[index];
  34033. // Checks
  34034. if (!_this._canBeMerged(current)) {
  34035. continue;
  34036. }
  34037. currentPool.push(current);
  34038. // Find compatible meshes
  34039. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  34040. var otherMesh = globalPool[subIndex];
  34041. if (!_this._canBeMerged(otherMesh)) {
  34042. continue;
  34043. }
  34044. if (otherMesh.material !== current.material) {
  34045. continue;
  34046. }
  34047. if (otherMesh.checkCollisions !== current.checkCollisions) {
  34048. continue;
  34049. }
  34050. currentPool.push(otherMesh);
  34051. globalLength--;
  34052. globalPool.splice(subIndex, 1);
  34053. subIndex--;
  34054. }
  34055. if (currentPool.length < 2) {
  34056. continue;
  34057. }
  34058. // Merge meshes
  34059. BABYLON.Mesh.MergeMeshes(currentPool);
  34060. }
  34061. if (updateSelectionTree != undefined) {
  34062. if (updateSelectionTree) {
  34063. scene.createOrUpdateSelectionOctree();
  34064. }
  34065. }
  34066. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  34067. scene.createOrUpdateSelectionOctree();
  34068. }
  34069. return true;
  34070. };
  34071. }
  34072. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  34073. get: function () {
  34074. return MergeMeshesOptimization._UpdateSelectionTree;
  34075. },
  34076. set: function (value) {
  34077. MergeMeshesOptimization._UpdateSelectionTree = value;
  34078. },
  34079. enumerable: true,
  34080. configurable: true
  34081. });
  34082. MergeMeshesOptimization._UpdateSelectionTree = false;
  34083. return MergeMeshesOptimization;
  34084. })(SceneOptimization);
  34085. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  34086. // Options
  34087. var SceneOptimizerOptions = (function () {
  34088. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  34089. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  34090. if (trackerDuration === void 0) { trackerDuration = 2000; }
  34091. this.targetFrameRate = targetFrameRate;
  34092. this.trackerDuration = trackerDuration;
  34093. this.optimizations = new Array();
  34094. }
  34095. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  34096. var result = new SceneOptimizerOptions(targetFrameRate);
  34097. var priority = 0;
  34098. result.optimizations.push(new MergeMeshesOptimization(priority));
  34099. result.optimizations.push(new ShadowsOptimization(priority));
  34100. result.optimizations.push(new LensFlaresOptimization(priority));
  34101. // Next priority
  34102. priority++;
  34103. result.optimizations.push(new PostProcessesOptimization(priority));
  34104. result.optimizations.push(new ParticlesOptimization(priority));
  34105. // Next priority
  34106. priority++;
  34107. result.optimizations.push(new TextureOptimization(priority, 1024));
  34108. return result;
  34109. };
  34110. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  34111. var result = new SceneOptimizerOptions(targetFrameRate);
  34112. var priority = 0;
  34113. result.optimizations.push(new MergeMeshesOptimization(priority));
  34114. result.optimizations.push(new ShadowsOptimization(priority));
  34115. result.optimizations.push(new LensFlaresOptimization(priority));
  34116. // Next priority
  34117. priority++;
  34118. result.optimizations.push(new PostProcessesOptimization(priority));
  34119. result.optimizations.push(new ParticlesOptimization(priority));
  34120. // Next priority
  34121. priority++;
  34122. result.optimizations.push(new TextureOptimization(priority, 512));
  34123. // Next priority
  34124. priority++;
  34125. result.optimizations.push(new RenderTargetsOptimization(priority));
  34126. // Next priority
  34127. priority++;
  34128. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  34129. return result;
  34130. };
  34131. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  34132. var result = new SceneOptimizerOptions(targetFrameRate);
  34133. var priority = 0;
  34134. result.optimizations.push(new MergeMeshesOptimization(priority));
  34135. result.optimizations.push(new ShadowsOptimization(priority));
  34136. result.optimizations.push(new LensFlaresOptimization(priority));
  34137. // Next priority
  34138. priority++;
  34139. result.optimizations.push(new PostProcessesOptimization(priority));
  34140. result.optimizations.push(new ParticlesOptimization(priority));
  34141. // Next priority
  34142. priority++;
  34143. result.optimizations.push(new TextureOptimization(priority, 256));
  34144. // Next priority
  34145. priority++;
  34146. result.optimizations.push(new RenderTargetsOptimization(priority));
  34147. // Next priority
  34148. priority++;
  34149. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34150. return result;
  34151. };
  34152. return SceneOptimizerOptions;
  34153. })();
  34154. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34155. // Scene optimizer tool
  34156. var SceneOptimizer = (function () {
  34157. function SceneOptimizer() {
  34158. }
  34159. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34160. // TODO: add an epsilon
  34161. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34162. if (onSuccess) {
  34163. onSuccess();
  34164. }
  34165. return;
  34166. }
  34167. // Apply current level of optimizations
  34168. var allDone = true;
  34169. var noOptimizationApplied = true;
  34170. for (var index = 0; index < options.optimizations.length; index++) {
  34171. var optimization = options.optimizations[index];
  34172. if (optimization.priority === currentPriorityLevel) {
  34173. noOptimizationApplied = false;
  34174. allDone = allDone && optimization.apply(scene);
  34175. }
  34176. }
  34177. // If no optimization was applied, this is a failure :(
  34178. if (noOptimizationApplied) {
  34179. if (onFailure) {
  34180. onFailure();
  34181. }
  34182. return;
  34183. }
  34184. // If all optimizations were done, move to next level
  34185. if (allDone) {
  34186. currentPriorityLevel++;
  34187. }
  34188. // Let's the system running for a specific amount of time before checking FPS
  34189. scene.executeWhenReady(function () {
  34190. setTimeout(function () {
  34191. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34192. }, options.trackerDuration);
  34193. });
  34194. };
  34195. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34196. if (!options) {
  34197. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34198. }
  34199. // Let's the system running for a specific amount of time before checking FPS
  34200. scene.executeWhenReady(function () {
  34201. setTimeout(function () {
  34202. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34203. }, options.trackerDuration);
  34204. });
  34205. };
  34206. return SceneOptimizer;
  34207. })();
  34208. BABYLON.SceneOptimizer = SceneOptimizer;
  34209. })(BABYLON || (BABYLON = {}));
  34210. var BABYLON;
  34211. (function (BABYLON) {
  34212. var Internals;
  34213. (function (Internals) {
  34214. var MeshLODLevel = (function () {
  34215. function MeshLODLevel(distance, mesh) {
  34216. this.distance = distance;
  34217. this.mesh = mesh;
  34218. }
  34219. return MeshLODLevel;
  34220. })();
  34221. Internals.MeshLODLevel = MeshLODLevel;
  34222. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34223. })(BABYLON || (BABYLON = {}));
  34224. var BABYLON;
  34225. (function (BABYLON) {
  34226. var RawTexture = (function (_super) {
  34227. __extends(RawTexture, _super);
  34228. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34229. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34230. if (invertY === void 0) { invertY = false; }
  34231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34232. _super.call(this, null, scene, !generateMipMaps, invertY);
  34233. this.format = format;
  34234. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34235. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34236. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34237. }
  34238. RawTexture.prototype.update = function (data) {
  34239. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34240. };
  34241. // Statics
  34242. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34244. if (invertY === void 0) { invertY = false; }
  34245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34247. };
  34248. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34250. if (invertY === void 0) { invertY = false; }
  34251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34253. };
  34254. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34256. if (invertY === void 0) { invertY = false; }
  34257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34259. };
  34260. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34262. if (invertY === void 0) { invertY = false; }
  34263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34264. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34265. };
  34266. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34267. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34268. if (invertY === void 0) { invertY = false; }
  34269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34270. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34271. };
  34272. return RawTexture;
  34273. })(BABYLON.Texture);
  34274. BABYLON.RawTexture = RawTexture;
  34275. })(BABYLON || (BABYLON = {}));
  34276. var BABYLON;
  34277. (function (BABYLON) {
  34278. var IndexedVector2 = (function (_super) {
  34279. __extends(IndexedVector2, _super);
  34280. function IndexedVector2(original, index) {
  34281. _super.call(this, original.x, original.y);
  34282. this.index = index;
  34283. }
  34284. return IndexedVector2;
  34285. })(BABYLON.Vector2);
  34286. var PolygonPoints = (function () {
  34287. function PolygonPoints() {
  34288. this.elements = new Array();
  34289. }
  34290. PolygonPoints.prototype.add = function (originalPoints) {
  34291. var _this = this;
  34292. var result = new Array();
  34293. originalPoints.forEach(function (point) {
  34294. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34295. var newPoint = new IndexedVector2(point, _this.elements.length);
  34296. result.push(newPoint);
  34297. _this.elements.push(newPoint);
  34298. }
  34299. });
  34300. return result;
  34301. };
  34302. PolygonPoints.prototype.computeBounds = function () {
  34303. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34304. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34305. this.elements.forEach(function (point) {
  34306. // x
  34307. if (point.x < lmin.x) {
  34308. lmin.x = point.x;
  34309. }
  34310. else if (point.x > lmax.x) {
  34311. lmax.x = point.x;
  34312. }
  34313. // y
  34314. if (point.y < lmin.y) {
  34315. lmin.y = point.y;
  34316. }
  34317. else if (point.y > lmax.y) {
  34318. lmax.y = point.y;
  34319. }
  34320. });
  34321. return {
  34322. min: lmin,
  34323. max: lmax,
  34324. width: lmax.x - lmin.x,
  34325. height: lmax.y - lmin.y
  34326. };
  34327. };
  34328. return PolygonPoints;
  34329. })();
  34330. var Polygon = (function () {
  34331. function Polygon() {
  34332. }
  34333. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34334. return [
  34335. new BABYLON.Vector2(xmin, ymin),
  34336. new BABYLON.Vector2(xmax, ymin),
  34337. new BABYLON.Vector2(xmax, ymax),
  34338. new BABYLON.Vector2(xmin, ymax)
  34339. ];
  34340. };
  34341. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34342. if (cx === void 0) { cx = 0; }
  34343. if (cy === void 0) { cy = 0; }
  34344. if (numberOfSides === void 0) { numberOfSides = 32; }
  34345. var result = new Array();
  34346. var angle = 0;
  34347. var increment = (Math.PI * 2) / numberOfSides;
  34348. for (var i = 0; i < numberOfSides; i++) {
  34349. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34350. angle -= increment;
  34351. }
  34352. return result;
  34353. };
  34354. Polygon.Parse = function (input) {
  34355. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34356. var i, result = [];
  34357. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34358. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34359. }
  34360. return result;
  34361. };
  34362. Polygon.StartingAt = function (x, y) {
  34363. return BABYLON.Path2.StartingAt(x, y);
  34364. };
  34365. return Polygon;
  34366. })();
  34367. BABYLON.Polygon = Polygon;
  34368. var PolygonMeshBuilder = (function () {
  34369. function PolygonMeshBuilder(name, contours, scene) {
  34370. this._points = new PolygonPoints();
  34371. this._outlinepoints = new PolygonPoints();
  34372. this._holes = [];
  34373. if (!("poly2tri" in window)) {
  34374. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34375. }
  34376. this._name = name;
  34377. this._scene = scene;
  34378. var points;
  34379. if (contours instanceof BABYLON.Path2) {
  34380. points = contours.getPoints();
  34381. }
  34382. else {
  34383. points = contours;
  34384. }
  34385. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34386. this._outlinepoints.add(points);
  34387. }
  34388. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34389. this._swctx.addHole(this._points.add(hole));
  34390. var holepoints = new PolygonPoints();
  34391. holepoints.add(hole);
  34392. this._holes.push(holepoints);
  34393. return this;
  34394. };
  34395. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34396. var _this = this;
  34397. if (updatable === void 0) { updatable = false; }
  34398. var result = new BABYLON.Mesh(this._name, this._scene);
  34399. var normals = [];
  34400. var positions = [];
  34401. var uvs = [];
  34402. var bounds = this._points.computeBounds();
  34403. this._points.elements.forEach(function (p) {
  34404. normals.push(0, 1.0, 0);
  34405. positions.push(p.x, 0, p.y);
  34406. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34407. });
  34408. var indices = [];
  34409. this._swctx.triangulate();
  34410. this._swctx.getTriangles().forEach(function (triangle) {
  34411. triangle.getPoints().forEach(function (point) {
  34412. indices.push(point.index);
  34413. });
  34414. });
  34415. if (depth > 0) {
  34416. var positionscount = (positions.length / 3); //get the current pointcount
  34417. this._points.elements.forEach(function (p) {
  34418. normals.push(0, -1.0, 0);
  34419. positions.push(p.x, -depth, p.y);
  34420. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34421. });
  34422. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34423. var p2;
  34424. var poscounter = 0;
  34425. this._swctx.getTriangles().forEach(function (triangle) {
  34426. triangle.getPoints().forEach(function (point) {
  34427. switch (poscounter) {
  34428. case 0:
  34429. p1 = point;
  34430. break;
  34431. case 1:
  34432. p2 = point;
  34433. break;
  34434. case 2:
  34435. indices.push(point.index + positionscount);
  34436. indices.push(p2.index + positionscount);
  34437. indices.push(p1.index + positionscount);
  34438. poscounter = -1;
  34439. break;
  34440. }
  34441. poscounter++;
  34442. //indices.push((<IndexedVector2>point).index + positionscount);
  34443. });
  34444. });
  34445. //Add the sides
  34446. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34447. this._holes.forEach(function (hole) {
  34448. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34449. });
  34450. }
  34451. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34452. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34453. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34454. result.setIndices(indices);
  34455. return result;
  34456. };
  34457. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34458. var StartIndex = positions.length / 3;
  34459. var ulength = 0;
  34460. for (var i = 0; i < points.elements.length; i++) {
  34461. var p = points.elements[i];
  34462. var p1;
  34463. if ((i + 1) > points.elements.length - 1) {
  34464. p1 = points.elements[0];
  34465. }
  34466. else {
  34467. p1 = points.elements[i + 1];
  34468. }
  34469. positions.push(p.x, 0, p.y);
  34470. positions.push(p.x, -depth, p.y);
  34471. positions.push(p1.x, 0, p1.y);
  34472. positions.push(p1.x, -depth, p1.y);
  34473. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34474. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34475. var v3 = v2.subtract(v1);
  34476. var v4 = new BABYLON.Vector3(0, 1, 0);
  34477. var vn = BABYLON.Vector3.Cross(v3, v4);
  34478. vn = vn.normalize();
  34479. uvs.push(ulength / bounds.width, 0);
  34480. uvs.push(ulength / bounds.width, 1);
  34481. ulength += v3.length();
  34482. uvs.push((ulength / bounds.width), 0);
  34483. uvs.push((ulength / bounds.width), 1);
  34484. if (!flip) {
  34485. normals.push(-vn.x, -vn.y, -vn.z);
  34486. normals.push(-vn.x, -vn.y, -vn.z);
  34487. normals.push(-vn.x, -vn.y, -vn.z);
  34488. normals.push(-vn.x, -vn.y, -vn.z);
  34489. indices.push(StartIndex);
  34490. indices.push(StartIndex + 1);
  34491. indices.push(StartIndex + 2);
  34492. indices.push(StartIndex + 1);
  34493. indices.push(StartIndex + 3);
  34494. indices.push(StartIndex + 2);
  34495. }
  34496. else {
  34497. normals.push(vn.x, vn.y, vn.z);
  34498. normals.push(vn.x, vn.y, vn.z);
  34499. normals.push(vn.x, vn.y, vn.z);
  34500. normals.push(vn.x, vn.y, vn.z);
  34501. indices.push(StartIndex);
  34502. indices.push(StartIndex + 2);
  34503. indices.push(StartIndex + 1);
  34504. indices.push(StartIndex + 1);
  34505. indices.push(StartIndex + 2);
  34506. indices.push(StartIndex + 3);
  34507. }
  34508. StartIndex += 4;
  34509. }
  34510. ;
  34511. };
  34512. return PolygonMeshBuilder;
  34513. })();
  34514. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34515. })(BABYLON || (BABYLON = {}));
  34516. var BABYLON;
  34517. (function (BABYLON) {
  34518. var Octree = (function () {
  34519. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34520. if (maxDepth === void 0) { maxDepth = 2; }
  34521. this.maxDepth = maxDepth;
  34522. this.dynamicContent = new Array();
  34523. this._maxBlockCapacity = maxBlockCapacity || 64;
  34524. this._selectionContent = new BABYLON.SmartArray(1024);
  34525. this._creationFunc = creationFunc;
  34526. }
  34527. // Methods
  34528. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34529. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34530. };
  34531. Octree.prototype.addMesh = function (entry) {
  34532. for (var index = 0; index < this.blocks.length; index++) {
  34533. var block = this.blocks[index];
  34534. block.addEntry(entry);
  34535. }
  34536. };
  34537. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34538. this._selectionContent.reset();
  34539. for (var index = 0; index < this.blocks.length; index++) {
  34540. var block = this.blocks[index];
  34541. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34542. }
  34543. if (allowDuplicate) {
  34544. this._selectionContent.concat(this.dynamicContent);
  34545. }
  34546. else {
  34547. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34548. }
  34549. return this._selectionContent;
  34550. };
  34551. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34552. this._selectionContent.reset();
  34553. for (var index = 0; index < this.blocks.length; index++) {
  34554. var block = this.blocks[index];
  34555. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34556. }
  34557. if (allowDuplicate) {
  34558. this._selectionContent.concat(this.dynamicContent);
  34559. }
  34560. else {
  34561. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34562. }
  34563. return this._selectionContent;
  34564. };
  34565. Octree.prototype.intersectsRay = function (ray) {
  34566. this._selectionContent.reset();
  34567. for (var index = 0; index < this.blocks.length; index++) {
  34568. var block = this.blocks[index];
  34569. block.intersectsRay(ray, this._selectionContent);
  34570. }
  34571. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34572. return this._selectionContent;
  34573. };
  34574. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34575. target.blocks = new Array();
  34576. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34577. // Segmenting space
  34578. for (var x = 0; x < 2; x++) {
  34579. for (var y = 0; y < 2; y++) {
  34580. for (var z = 0; z < 2; z++) {
  34581. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34582. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34583. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34584. block.addEntries(entries);
  34585. target.blocks.push(block);
  34586. }
  34587. }
  34588. }
  34589. };
  34590. Octree.CreationFuncForMeshes = function (entry, block) {
  34591. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34592. block.entries.push(entry);
  34593. }
  34594. };
  34595. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34596. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34597. block.entries.push(entry);
  34598. }
  34599. };
  34600. return Octree;
  34601. })();
  34602. BABYLON.Octree = Octree;
  34603. })(BABYLON || (BABYLON = {}));
  34604. var BABYLON;
  34605. (function (BABYLON) {
  34606. var OctreeBlock = (function () {
  34607. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34608. this.entries = new Array();
  34609. this._boundingVectors = new Array();
  34610. this._capacity = capacity;
  34611. this._depth = depth;
  34612. this._maxDepth = maxDepth;
  34613. this._creationFunc = creationFunc;
  34614. this._minPoint = minPoint;
  34615. this._maxPoint = maxPoint;
  34616. this._boundingVectors.push(minPoint.clone());
  34617. this._boundingVectors.push(maxPoint.clone());
  34618. this._boundingVectors.push(minPoint.clone());
  34619. this._boundingVectors[2].x = maxPoint.x;
  34620. this._boundingVectors.push(minPoint.clone());
  34621. this._boundingVectors[3].y = maxPoint.y;
  34622. this._boundingVectors.push(minPoint.clone());
  34623. this._boundingVectors[4].z = maxPoint.z;
  34624. this._boundingVectors.push(maxPoint.clone());
  34625. this._boundingVectors[5].z = minPoint.z;
  34626. this._boundingVectors.push(maxPoint.clone());
  34627. this._boundingVectors[6].x = minPoint.x;
  34628. this._boundingVectors.push(maxPoint.clone());
  34629. this._boundingVectors[7].y = minPoint.y;
  34630. }
  34631. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34632. // Property
  34633. get: function () {
  34634. return this._capacity;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34640. get: function () {
  34641. return this._minPoint;
  34642. },
  34643. enumerable: true,
  34644. configurable: true
  34645. });
  34646. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34647. get: function () {
  34648. return this._maxPoint;
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. // Methods
  34654. OctreeBlock.prototype.addEntry = function (entry) {
  34655. if (this.blocks) {
  34656. for (var index = 0; index < this.blocks.length; index++) {
  34657. var block = this.blocks[index];
  34658. block.addEntry(entry);
  34659. }
  34660. return;
  34661. }
  34662. this._creationFunc(entry, this);
  34663. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34664. this.createInnerBlocks();
  34665. }
  34666. };
  34667. OctreeBlock.prototype.addEntries = function (entries) {
  34668. for (var index = 0; index < entries.length; index++) {
  34669. var mesh = entries[index];
  34670. this.addEntry(mesh);
  34671. }
  34672. };
  34673. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34674. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34675. if (this.blocks) {
  34676. for (var index = 0; index < this.blocks.length; index++) {
  34677. var block = this.blocks[index];
  34678. block.select(frustumPlanes, selection, allowDuplicate);
  34679. }
  34680. return;
  34681. }
  34682. if (allowDuplicate) {
  34683. selection.concat(this.entries);
  34684. }
  34685. else {
  34686. selection.concatWithNoDuplicate(this.entries);
  34687. }
  34688. }
  34689. };
  34690. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34691. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34692. if (this.blocks) {
  34693. for (var index = 0; index < this.blocks.length; index++) {
  34694. var block = this.blocks[index];
  34695. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34696. }
  34697. return;
  34698. }
  34699. if (allowDuplicate) {
  34700. selection.concat(this.entries);
  34701. }
  34702. else {
  34703. selection.concatWithNoDuplicate(this.entries);
  34704. }
  34705. }
  34706. };
  34707. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34708. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34709. if (this.blocks) {
  34710. for (var index = 0; index < this.blocks.length; index++) {
  34711. var block = this.blocks[index];
  34712. block.intersectsRay(ray, selection);
  34713. }
  34714. return;
  34715. }
  34716. selection.concatWithNoDuplicate(this.entries);
  34717. }
  34718. };
  34719. OctreeBlock.prototype.createInnerBlocks = function () {
  34720. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34721. };
  34722. return OctreeBlock;
  34723. })();
  34724. BABYLON.OctreeBlock = OctreeBlock;
  34725. })(BABYLON || (BABYLON = {}));
  34726. var BABYLON;
  34727. (function (BABYLON) {
  34728. var BlurPostProcess = (function (_super) {
  34729. __extends(BlurPostProcess, _super);
  34730. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34731. var _this = this;
  34732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34733. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34734. this.direction = direction;
  34735. this.blurWidth = blurWidth;
  34736. this.onApply = function (effect) {
  34737. effect.setFloat2("screenSize", _this.width, _this.height);
  34738. effect.setVector2("direction", _this.direction);
  34739. effect.setFloat("blurWidth", _this.blurWidth);
  34740. };
  34741. }
  34742. return BlurPostProcess;
  34743. })(BABYLON.PostProcess);
  34744. BABYLON.BlurPostProcess = BlurPostProcess;
  34745. })(BABYLON || (BABYLON = {}));
  34746. var BABYLON;
  34747. (function (BABYLON) {
  34748. var RefractionPostProcess = (function (_super) {
  34749. __extends(RefractionPostProcess, _super);
  34750. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34751. var _this = this;
  34752. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34753. this.color = color;
  34754. this.depth = depth;
  34755. this.colorLevel = colorLevel;
  34756. this.onActivate = function (cam) {
  34757. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34758. };
  34759. this.onApply = function (effect) {
  34760. effect.setColor3("baseColor", _this.color);
  34761. effect.setFloat("depth", _this.depth);
  34762. effect.setFloat("colorLevel", _this.colorLevel);
  34763. effect.setTexture("refractionSampler", _this._refRexture);
  34764. };
  34765. }
  34766. // Methods
  34767. RefractionPostProcess.prototype.dispose = function (camera) {
  34768. if (this._refRexture) {
  34769. this._refRexture.dispose();
  34770. }
  34771. _super.prototype.dispose.call(this, camera);
  34772. };
  34773. return RefractionPostProcess;
  34774. })(BABYLON.PostProcess);
  34775. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34776. })(BABYLON || (BABYLON = {}));
  34777. var BABYLON;
  34778. (function (BABYLON) {
  34779. var BlackAndWhitePostProcess = (function (_super) {
  34780. __extends(BlackAndWhitePostProcess, _super);
  34781. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34782. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34783. }
  34784. return BlackAndWhitePostProcess;
  34785. })(BABYLON.PostProcess);
  34786. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34787. })(BABYLON || (BABYLON = {}));
  34788. var BABYLON;
  34789. (function (BABYLON) {
  34790. var ConvolutionPostProcess = (function (_super) {
  34791. __extends(ConvolutionPostProcess, _super);
  34792. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34793. var _this = this;
  34794. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34795. this.kernel = kernel;
  34796. this.onApply = function (effect) {
  34797. effect.setFloat2("screenSize", _this.width, _this.height);
  34798. effect.setArray("kernel", _this.kernel);
  34799. };
  34800. }
  34801. // Statics
  34802. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34803. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34804. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34805. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34806. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34807. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34808. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34809. return ConvolutionPostProcess;
  34810. })(BABYLON.PostProcess);
  34811. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34812. })(BABYLON || (BABYLON = {}));
  34813. var BABYLON;
  34814. (function (BABYLON) {
  34815. var FilterPostProcess = (function (_super) {
  34816. __extends(FilterPostProcess, _super);
  34817. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34818. var _this = this;
  34819. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34820. this.kernelMatrix = kernelMatrix;
  34821. this.onApply = function (effect) {
  34822. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34823. };
  34824. }
  34825. return FilterPostProcess;
  34826. })(BABYLON.PostProcess);
  34827. BABYLON.FilterPostProcess = FilterPostProcess;
  34828. })(BABYLON || (BABYLON = {}));
  34829. var BABYLON;
  34830. (function (BABYLON) {
  34831. var FxaaPostProcess = (function (_super) {
  34832. __extends(FxaaPostProcess, _super);
  34833. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34834. var _this = this;
  34835. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34836. this.onSizeChanged = function () {
  34837. _this.texelWidth = 1.0 / _this.width;
  34838. _this.texelHeight = 1.0 / _this.height;
  34839. };
  34840. this.onApply = function (effect) {
  34841. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34842. };
  34843. }
  34844. return FxaaPostProcess;
  34845. })(BABYLON.PostProcess);
  34846. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34847. })(BABYLON || (BABYLON = {}));
  34848. var BABYLON;
  34849. (function (BABYLON) {
  34850. var StereoscopicInterlacePostProcess = (function (_super) {
  34851. __extends(StereoscopicInterlacePostProcess, _super);
  34852. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34853. var _this = this;
  34854. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34855. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34856. this.onSizeChanged = function () {
  34857. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34858. };
  34859. this.onApply = function (effect) {
  34860. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34861. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34862. };
  34863. }
  34864. return StereoscopicInterlacePostProcess;
  34865. })(BABYLON.PostProcess);
  34866. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34867. })(BABYLON || (BABYLON = {}));
  34868. var BABYLON;
  34869. (function (BABYLON) {
  34870. var LensFlare = (function () {
  34871. function LensFlare(size, position, color, imgUrl, system) {
  34872. this.size = size;
  34873. this.position = position;
  34874. this.dispose = function () {
  34875. if (this.texture) {
  34876. this.texture.dispose();
  34877. }
  34878. // Remove from scene
  34879. var index = this._system.lensFlares.indexOf(this);
  34880. this._system.lensFlares.splice(index, 1);
  34881. };
  34882. this.color = color || new BABYLON.Color3(1, 1, 1);
  34883. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34884. this._system = system;
  34885. system.lensFlares.push(this);
  34886. }
  34887. return LensFlare;
  34888. })();
  34889. BABYLON.LensFlare = LensFlare;
  34890. })(BABYLON || (BABYLON = {}));
  34891. var BABYLON;
  34892. (function (BABYLON) {
  34893. var LensFlareSystem = (function () {
  34894. function LensFlareSystem(name, emitter, scene) {
  34895. this.name = name;
  34896. this.lensFlares = new Array();
  34897. this.borderLimit = 300;
  34898. this.layerMask = 0x0FFFFFFF;
  34899. this._vertexDeclaration = [2];
  34900. this._vertexStrideSize = 2 * 4;
  34901. this._isEnabled = true;
  34902. this._scene = scene;
  34903. this._emitter = emitter;
  34904. scene.lensFlareSystems.push(this);
  34905. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34906. // VBO
  34907. var vertices = [];
  34908. vertices.push(1, 1);
  34909. vertices.push(-1, 1);
  34910. vertices.push(-1, -1);
  34911. vertices.push(1, -1);
  34912. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34913. // Indices
  34914. var indices = [];
  34915. indices.push(0);
  34916. indices.push(1);
  34917. indices.push(2);
  34918. indices.push(0);
  34919. indices.push(2);
  34920. indices.push(3);
  34921. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34922. // Effects
  34923. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34924. }
  34925. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34926. get: function () {
  34927. return this._isEnabled;
  34928. },
  34929. set: function (value) {
  34930. this._isEnabled = value;
  34931. },
  34932. enumerable: true,
  34933. configurable: true
  34934. });
  34935. LensFlareSystem.prototype.getScene = function () {
  34936. return this._scene;
  34937. };
  34938. LensFlareSystem.prototype.getEmitter = function () {
  34939. return this._emitter;
  34940. };
  34941. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34942. this._emitter = newEmitter;
  34943. };
  34944. LensFlareSystem.prototype.getEmitterPosition = function () {
  34945. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34946. };
  34947. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34948. var position = this.getEmitterPosition();
  34949. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34950. this._positionX = position.x;
  34951. this._positionY = position.y;
  34952. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34953. if (position.z > 0) {
  34954. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34955. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34956. return true;
  34957. }
  34958. }
  34959. return false;
  34960. };
  34961. LensFlareSystem.prototype._isVisible = function () {
  34962. if (!this._isEnabled) {
  34963. return false;
  34964. }
  34965. var emitterPosition = this.getEmitterPosition();
  34966. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34967. var distance = direction.length();
  34968. direction.normalize();
  34969. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34970. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34971. return !pickInfo.hit || pickInfo.distance > distance;
  34972. };
  34973. LensFlareSystem.prototype.render = function () {
  34974. if (!this._effect.isReady())
  34975. return false;
  34976. var engine = this._scene.getEngine();
  34977. var viewport = this._scene.activeCamera.viewport;
  34978. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  34979. // Position
  34980. if (!this.computeEffectivePosition(globalViewport)) {
  34981. return false;
  34982. }
  34983. // Visibility
  34984. if (!this._isVisible()) {
  34985. return false;
  34986. }
  34987. // Intensity
  34988. var awayX;
  34989. var awayY;
  34990. if (this._positionX < this.borderLimit + globalViewport.x) {
  34991. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34992. }
  34993. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34994. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34995. }
  34996. else {
  34997. awayX = 0;
  34998. }
  34999. if (this._positionY < this.borderLimit + globalViewport.y) {
  35000. awayY = this.borderLimit + globalViewport.y - this._positionY;
  35001. }
  35002. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  35003. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  35004. }
  35005. else {
  35006. awayY = 0;
  35007. }
  35008. var away = (awayX > awayY) ? awayX : awayY;
  35009. if (away > this.borderLimit) {
  35010. away = this.borderLimit;
  35011. }
  35012. var intensity = 1.0 - (away / this.borderLimit);
  35013. if (intensity < 0) {
  35014. return false;
  35015. }
  35016. if (intensity > 1.0) {
  35017. intensity = 1.0;
  35018. }
  35019. // Position
  35020. var centerX = globalViewport.x + globalViewport.width / 2;
  35021. var centerY = globalViewport.y + globalViewport.height / 2;
  35022. var distX = centerX - this._positionX;
  35023. var distY = centerY - this._positionY;
  35024. // Effects
  35025. engine.enableEffect(this._effect);
  35026. engine.setState(false);
  35027. engine.setDepthBuffer(false);
  35028. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35029. // VBOs
  35030. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  35031. // Flares
  35032. for (var index = 0; index < this.lensFlares.length; index++) {
  35033. var flare = this.lensFlares[index];
  35034. var x = centerX - (distX * flare.position);
  35035. var y = centerY - (distY * flare.position);
  35036. var cw = flare.size;
  35037. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  35038. var cx = 2 * (x / globalViewport.width) - 1.0;
  35039. var cy = 1.0 - 2 * (y / globalViewport.height);
  35040. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  35041. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  35042. // Texture
  35043. this._effect.setTexture("textureSampler", flare.texture);
  35044. // Color
  35045. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  35046. // Draw order
  35047. engine.draw(true, 0, 6);
  35048. }
  35049. engine.setDepthBuffer(true);
  35050. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35051. return true;
  35052. };
  35053. LensFlareSystem.prototype.dispose = function () {
  35054. if (this._vertexBuffer) {
  35055. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  35056. this._vertexBuffer = null;
  35057. }
  35058. if (this._indexBuffer) {
  35059. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35060. this._indexBuffer = null;
  35061. }
  35062. while (this.lensFlares.length) {
  35063. this.lensFlares[0].dispose();
  35064. }
  35065. // Remove from scene
  35066. var index = this._scene.lensFlareSystems.indexOf(this);
  35067. this._scene.lensFlareSystems.splice(index, 1);
  35068. };
  35069. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  35070. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  35071. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  35072. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  35073. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  35074. var parsedFlare = parsedLensFlareSystem.flares[index];
  35075. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  35076. }
  35077. return lensFlareSystem;
  35078. };
  35079. LensFlareSystem.prototype.serialize = function () {
  35080. var serializationObject = {};
  35081. serializationObject.emitterId = this.getEmitter().id;
  35082. serializationObject.borderLimit = this.borderLimit;
  35083. serializationObject.flares = [];
  35084. for (var index = 0; index < this.lensFlares.length; index++) {
  35085. var flare = this.lensFlares[index];
  35086. serializationObject.flares.push({
  35087. size: flare.size,
  35088. position: flare.position,
  35089. color: flare.color.asArray(),
  35090. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  35091. });
  35092. }
  35093. return serializationObject;
  35094. };
  35095. return LensFlareSystem;
  35096. })();
  35097. BABYLON.LensFlareSystem = LensFlareSystem;
  35098. })(BABYLON || (BABYLON = {}));
  35099. var BABYLON;
  35100. (function (BABYLON) {
  35101. // We're mainly based on the logic defined into the FreeCamera code
  35102. var DeviceOrientationCamera = (function (_super) {
  35103. __extends(DeviceOrientationCamera, _super);
  35104. function DeviceOrientationCamera(name, position, scene) {
  35105. var _this = this;
  35106. _super.call(this, name, position, scene);
  35107. this._offsetX = null;
  35108. this._offsetY = null;
  35109. this._orientationGamma = 0;
  35110. this._orientationBeta = 0;
  35111. this._initialOrientationGamma = 0;
  35112. this._initialOrientationBeta = 0;
  35113. this.angularSensibility = 10000.0;
  35114. this.moveSensibility = 50.0;
  35115. window.addEventListener("resize", function () {
  35116. _this._initialOrientationGamma = null;
  35117. }, false);
  35118. }
  35119. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35120. var _this = this;
  35121. if (this._attachedCanvas) {
  35122. return;
  35123. }
  35124. this._attachedCanvas = canvas;
  35125. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35126. if (!this._orientationChanged) {
  35127. this._orientationChanged = function (evt) {
  35128. if (!_this._initialOrientationGamma) {
  35129. _this._initialOrientationGamma = evt.gamma;
  35130. _this._initialOrientationBeta = evt.beta;
  35131. }
  35132. _this._orientationGamma = evt.gamma;
  35133. _this._orientationBeta = evt.beta;
  35134. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  35135. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  35136. };
  35137. }
  35138. window.addEventListener("deviceorientation", this._orientationChanged);
  35139. };
  35140. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  35141. if (this._attachedCanvas !== canvas) {
  35142. return;
  35143. }
  35144. window.removeEventListener("deviceorientation", this._orientationChanged);
  35145. this._attachedCanvas = null;
  35146. this._orientationGamma = 0;
  35147. this._orientationBeta = 0;
  35148. this._initialOrientationGamma = 0;
  35149. this._initialOrientationBeta = 0;
  35150. };
  35151. DeviceOrientationCamera.prototype._checkInputs = function () {
  35152. if (!this._offsetX) {
  35153. return;
  35154. }
  35155. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35156. var speed = this._computeLocalCameraSpeed();
  35157. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35158. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35159. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35160. _super.prototype._checkInputs.call(this);
  35161. };
  35162. DeviceOrientationCamera.prototype.getTypeName = function () {
  35163. return "DeviceOrientationCamera";
  35164. };
  35165. __decorate([
  35166. BABYLON.serialize()
  35167. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35168. __decorate([
  35169. BABYLON.serialize()
  35170. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35171. return DeviceOrientationCamera;
  35172. })(BABYLON.FreeCamera);
  35173. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35174. })(BABYLON || (BABYLON = {}));
  35175. var BABYLON;
  35176. (function (BABYLON) {
  35177. var Analyser = (function () {
  35178. function Analyser(scene) {
  35179. this.SMOOTHING = 0.75;
  35180. this.FFT_SIZE = 512;
  35181. this.BARGRAPHAMPLITUDE = 256;
  35182. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35183. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35184. this._scene = scene;
  35185. this._audioEngine = BABYLON.Engine.audioEngine;
  35186. if (this._audioEngine.canUseWebAudio) {
  35187. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35188. this._webAudioAnalyser.minDecibels = -140;
  35189. this._webAudioAnalyser.maxDecibels = 0;
  35190. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35191. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35192. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35193. }
  35194. }
  35195. Analyser.prototype.getFrequencyBinCount = function () {
  35196. if (this._audioEngine.canUseWebAudio) {
  35197. return this._webAudioAnalyser.frequencyBinCount;
  35198. }
  35199. else {
  35200. return 0;
  35201. }
  35202. };
  35203. Analyser.prototype.getByteFrequencyData = function () {
  35204. if (this._audioEngine.canUseWebAudio) {
  35205. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35206. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35207. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35208. }
  35209. return this._byteFreqs;
  35210. };
  35211. Analyser.prototype.getByteTimeDomainData = function () {
  35212. if (this._audioEngine.canUseWebAudio) {
  35213. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35214. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35215. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35216. }
  35217. return this._byteTime;
  35218. };
  35219. Analyser.prototype.getFloatFrequencyData = function () {
  35220. if (this._audioEngine.canUseWebAudio) {
  35221. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35222. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35223. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35224. }
  35225. return this._floatFreqs;
  35226. };
  35227. Analyser.prototype.drawDebugCanvas = function () {
  35228. var _this = this;
  35229. if (this._audioEngine.canUseWebAudio) {
  35230. if (!this._debugCanvas) {
  35231. this._debugCanvas = document.createElement("canvas");
  35232. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35233. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35234. this._debugCanvas.style.position = "absolute";
  35235. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35236. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35237. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35238. document.body.appendChild(this._debugCanvas);
  35239. this._registerFunc = function () {
  35240. _this.drawDebugCanvas();
  35241. };
  35242. this._scene.registerBeforeRender(this._registerFunc);
  35243. }
  35244. if (this._registerFunc) {
  35245. var workingArray = this.getByteFrequencyData();
  35246. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35247. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35248. // Draw the frequency domain chart.
  35249. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35250. var value = workingArray[i];
  35251. var percent = value / this.BARGRAPHAMPLITUDE;
  35252. var height = this.DEBUGCANVASSIZE.height * percent;
  35253. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35254. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35255. var hue = i / this.getFrequencyBinCount() * 360;
  35256. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35257. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35258. }
  35259. }
  35260. }
  35261. };
  35262. Analyser.prototype.stopDebugCanvas = function () {
  35263. if (this._debugCanvas) {
  35264. this._scene.unregisterBeforeRender(this._registerFunc);
  35265. this._registerFunc = null;
  35266. document.body.removeChild(this._debugCanvas);
  35267. this._debugCanvas = null;
  35268. this._debugCanvasContext = null;
  35269. }
  35270. };
  35271. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35272. if (this._audioEngine.canUseWebAudio) {
  35273. inputAudioNode.connect(this._webAudioAnalyser);
  35274. this._webAudioAnalyser.connect(outputAudioNode);
  35275. }
  35276. };
  35277. Analyser.prototype.dispose = function () {
  35278. if (this._audioEngine.canUseWebAudio) {
  35279. this._webAudioAnalyser.disconnect();
  35280. }
  35281. };
  35282. return Analyser;
  35283. })();
  35284. BABYLON.Analyser = Analyser;
  35285. })(BABYLON || (BABYLON = {}));
  35286. var BABYLON;
  35287. (function (BABYLON) {
  35288. var AudioEngine = (function () {
  35289. function AudioEngine() {
  35290. this._audioContext = null;
  35291. this._audioContextInitialized = false;
  35292. this.canUseWebAudio = false;
  35293. this.WarnedWebAudioUnsupported = false;
  35294. this.unlocked = false;
  35295. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35296. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35297. this.canUseWebAudio = true;
  35298. }
  35299. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35300. this._unlockiOSaudio();
  35301. }
  35302. else {
  35303. this.unlocked = true;
  35304. }
  35305. }
  35306. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35307. get: function () {
  35308. if (!this._audioContextInitialized) {
  35309. this._initializeAudioContext();
  35310. }
  35311. return this._audioContext;
  35312. },
  35313. enumerable: true,
  35314. configurable: true
  35315. });
  35316. AudioEngine.prototype._unlockiOSaudio = function () {
  35317. var _this = this;
  35318. var unlockaudio = function () {
  35319. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35320. var source = _this.audioContext.createBufferSource();
  35321. source.buffer = buffer;
  35322. source.connect(_this.audioContext.destination);
  35323. source.start(0);
  35324. setTimeout(function () {
  35325. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35326. _this.unlocked = true;
  35327. window.removeEventListener('touchend', unlockaudio, false);
  35328. if (_this.onAudioUnlocked) {
  35329. _this.onAudioUnlocked();
  35330. }
  35331. }
  35332. }, 0);
  35333. };
  35334. window.addEventListener('touchend', unlockaudio, false);
  35335. };
  35336. AudioEngine.prototype._initializeAudioContext = function () {
  35337. try {
  35338. if (this.canUseWebAudio) {
  35339. this._audioContext = new AudioContext();
  35340. // create a global volume gain node
  35341. this.masterGain = this._audioContext.createGain();
  35342. this.masterGain.gain.value = 1;
  35343. this.masterGain.connect(this._audioContext.destination);
  35344. this._audioContextInitialized = true;
  35345. }
  35346. }
  35347. catch (e) {
  35348. this.canUseWebAudio = false;
  35349. BABYLON.Tools.Error("Web Audio: " + e.message);
  35350. }
  35351. };
  35352. AudioEngine.prototype.dispose = function () {
  35353. if (this.canUseWebAudio && this._audioContextInitialized) {
  35354. if (this._connectedAnalyser) {
  35355. this._connectedAnalyser.stopDebugCanvas();
  35356. this._connectedAnalyser.dispose();
  35357. this.masterGain.disconnect();
  35358. this.masterGain.connect(this._audioContext.destination);
  35359. this._connectedAnalyser = null;
  35360. }
  35361. this.masterGain.gain.value = 1;
  35362. }
  35363. this.WarnedWebAudioUnsupported = false;
  35364. };
  35365. AudioEngine.prototype.getGlobalVolume = function () {
  35366. if (this.canUseWebAudio && this._audioContextInitialized) {
  35367. return this.masterGain.gain.value;
  35368. }
  35369. else {
  35370. return -1;
  35371. }
  35372. };
  35373. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35374. if (this.canUseWebAudio && this._audioContextInitialized) {
  35375. this.masterGain.gain.value = newVolume;
  35376. }
  35377. };
  35378. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35379. if (this._connectedAnalyser) {
  35380. this._connectedAnalyser.stopDebugCanvas();
  35381. }
  35382. if (this.canUseWebAudio && this._audioContextInitialized) {
  35383. this._connectedAnalyser = analyser;
  35384. this.masterGain.disconnect();
  35385. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35386. }
  35387. };
  35388. return AudioEngine;
  35389. })();
  35390. BABYLON.AudioEngine = AudioEngine;
  35391. })(BABYLON || (BABYLON = {}));
  35392. var BABYLON;
  35393. (function (BABYLON) {
  35394. var Sound = (function () {
  35395. /**
  35396. * Create a sound and attach it to a scene
  35397. * @param name Name of your sound
  35398. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35399. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35400. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35401. */
  35402. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35403. var _this = this;
  35404. this.autoplay = false;
  35405. this.loop = false;
  35406. this.useCustomAttenuation = false;
  35407. this.spatialSound = false;
  35408. this.refDistance = 1;
  35409. this.rolloffFactor = 1;
  35410. this.maxDistance = 100;
  35411. this.distanceModel = "linear";
  35412. this._panningModel = "equalpower";
  35413. this._playbackRate = 1;
  35414. this._streaming = false;
  35415. this._startTime = 0;
  35416. this._startOffset = 0;
  35417. this._position = BABYLON.Vector3.Zero();
  35418. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35419. this._volume = 1;
  35420. this._isLoaded = false;
  35421. this._isReadyToPlay = false;
  35422. this.isPlaying = false;
  35423. this.isPaused = false;
  35424. this._isDirectional = false;
  35425. // Used if you'd like to create a directional sound.
  35426. // If not set, the sound will be omnidirectional
  35427. this._coneInnerAngle = 360;
  35428. this._coneOuterAngle = 360;
  35429. this._coneOuterGain = 0;
  35430. this._isOutputConnected = false;
  35431. this.name = name;
  35432. this._scene = scene;
  35433. this._readyToPlayCallback = readyToPlayCallback;
  35434. // Default custom attenuation function is a linear attenuation
  35435. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35436. if (currentDistance < maxDistance) {
  35437. return currentVolume * (1 - currentDistance / maxDistance);
  35438. }
  35439. else {
  35440. return 0;
  35441. }
  35442. };
  35443. if (options) {
  35444. this.autoplay = options.autoplay || false;
  35445. this.loop = options.loop || false;
  35446. // if volume === 0, we need another way to check this option
  35447. if (options.volume !== undefined) {
  35448. this._volume = options.volume;
  35449. }
  35450. this.spatialSound = options.spatialSound || false;
  35451. this.maxDistance = options.maxDistance || 100;
  35452. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35453. this.rolloffFactor = options.rolloffFactor || 1;
  35454. this.refDistance = options.refDistance || 1;
  35455. this.distanceModel = options.distanceModel || "linear";
  35456. this._playbackRate = options.playbackRate || 1;
  35457. this._streaming = options.streaming || false;
  35458. }
  35459. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35460. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35461. this._soundGain.gain.value = this._volume;
  35462. this._inputAudioNode = this._soundGain;
  35463. this._ouputAudioNode = this._soundGain;
  35464. if (this.spatialSound) {
  35465. this._createSpatialParameters();
  35466. }
  35467. this._scene.mainSoundTrack.AddSound(this);
  35468. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35469. if (urlOrArrayBuffer) {
  35470. // If it's an URL
  35471. if (typeof (urlOrArrayBuffer) === "string") {
  35472. // Loading sound using XHR2
  35473. if (!this._streaming) {
  35474. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35475. }
  35476. else {
  35477. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35478. this._htmlAudioElement.controls = false;
  35479. this._htmlAudioElement.loop = this.loop;
  35480. this._htmlAudioElement.crossOrigin = "anonymous";
  35481. this._htmlAudioElement.preload = "auto";
  35482. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35483. _this._isReadyToPlay = true;
  35484. if (_this.autoplay) {
  35485. _this.play();
  35486. }
  35487. if (_this._readyToPlayCallback) {
  35488. _this._readyToPlayCallback();
  35489. }
  35490. });
  35491. document.body.appendChild(this._htmlAudioElement);
  35492. }
  35493. }
  35494. else {
  35495. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35496. if (urlOrArrayBuffer.byteLength > 0) {
  35497. this._soundLoaded(urlOrArrayBuffer);
  35498. }
  35499. }
  35500. else {
  35501. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35502. }
  35503. }
  35504. }
  35505. }
  35506. else {
  35507. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35508. this._scene.mainSoundTrack.AddSound(this);
  35509. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35510. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35511. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35512. }
  35513. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35514. if (this._readyToPlayCallback) {
  35515. window.setTimeout(function () {
  35516. _this._readyToPlayCallback();
  35517. }, 1000);
  35518. }
  35519. }
  35520. }
  35521. Sound.prototype.dispose = function () {
  35522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35523. if (this.isPlaying) {
  35524. this.stop();
  35525. }
  35526. this._isReadyToPlay = false;
  35527. if (this.soundTrackId === -1) {
  35528. this._scene.mainSoundTrack.RemoveSound(this);
  35529. }
  35530. else {
  35531. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35532. }
  35533. if (this._soundGain) {
  35534. this._soundGain.disconnect();
  35535. this._soundGain = null;
  35536. }
  35537. if (this._soundPanner) {
  35538. this._soundPanner.disconnect();
  35539. this._soundPanner = null;
  35540. }
  35541. if (this._soundSource) {
  35542. this._soundSource.disconnect();
  35543. this._soundSource = null;
  35544. }
  35545. this._audioBuffer = null;
  35546. if (this._htmlAudioElement) {
  35547. this._htmlAudioElement.pause();
  35548. this._htmlAudioElement.src = "";
  35549. document.body.removeChild(this._htmlAudioElement);
  35550. }
  35551. if (this._connectedMesh) {
  35552. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35553. this._connectedMesh = null;
  35554. }
  35555. }
  35556. };
  35557. Sound.prototype._soundLoaded = function (audioData) {
  35558. var _this = this;
  35559. this._isLoaded = true;
  35560. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35561. _this._audioBuffer = buffer;
  35562. _this._isReadyToPlay = true;
  35563. if (_this.autoplay) {
  35564. _this.play();
  35565. }
  35566. if (_this._readyToPlayCallback) {
  35567. _this._readyToPlayCallback();
  35568. }
  35569. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35570. };
  35571. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35572. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35573. this._audioBuffer = audioBuffer;
  35574. this._isReadyToPlay = true;
  35575. }
  35576. };
  35577. Sound.prototype.updateOptions = function (options) {
  35578. if (options) {
  35579. this.loop = options.loop || this.loop;
  35580. this.maxDistance = options.maxDistance || this.maxDistance;
  35581. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35582. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35583. this.refDistance = options.refDistance || this.refDistance;
  35584. this.distanceModel = options.distanceModel || this.distanceModel;
  35585. this._playbackRate = options.playbackRate || this._playbackRate;
  35586. this._updateSpatialParameters();
  35587. if (this.isPlaying) {
  35588. if (this._streaming) {
  35589. this._htmlAudioElement.playbackRate = this._playbackRate;
  35590. }
  35591. else {
  35592. this._soundSource.playbackRate.value = this._playbackRate;
  35593. }
  35594. }
  35595. }
  35596. };
  35597. Sound.prototype._createSpatialParameters = function () {
  35598. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35599. if (this._scene.headphone) {
  35600. this._panningModel = "HRTF";
  35601. }
  35602. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35603. this._updateSpatialParameters();
  35604. this._soundPanner.connect(this._ouputAudioNode);
  35605. this._inputAudioNode = this._soundPanner;
  35606. }
  35607. };
  35608. Sound.prototype._updateSpatialParameters = function () {
  35609. if (this.spatialSound) {
  35610. if (this.useCustomAttenuation) {
  35611. // Tricks to disable in a way embedded Web Audio attenuation
  35612. this._soundPanner.distanceModel = "linear";
  35613. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35614. this._soundPanner.refDistance = 1;
  35615. this._soundPanner.rolloffFactor = 1;
  35616. this._soundPanner.panningModel = this._panningModel;
  35617. }
  35618. else {
  35619. this._soundPanner.distanceModel = this.distanceModel;
  35620. this._soundPanner.maxDistance = this.maxDistance;
  35621. this._soundPanner.refDistance = this.refDistance;
  35622. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35623. this._soundPanner.panningModel = this._panningModel;
  35624. }
  35625. }
  35626. };
  35627. Sound.prototype.switchPanningModelToHRTF = function () {
  35628. this._panningModel = "HRTF";
  35629. this._switchPanningModel();
  35630. };
  35631. Sound.prototype.switchPanningModelToEqualPower = function () {
  35632. this._panningModel = "equalpower";
  35633. this._switchPanningModel();
  35634. };
  35635. Sound.prototype._switchPanningModel = function () {
  35636. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35637. this._soundPanner.panningModel = this._panningModel;
  35638. }
  35639. };
  35640. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35641. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35642. if (this._isOutputConnected) {
  35643. this._ouputAudioNode.disconnect();
  35644. }
  35645. this._ouputAudioNode.connect(soundTrackAudioNode);
  35646. this._isOutputConnected = true;
  35647. }
  35648. };
  35649. /**
  35650. * Transform this sound into a directional source
  35651. * @param coneInnerAngle Size of the inner cone in degree
  35652. * @param coneOuterAngle Size of the outer cone in degree
  35653. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35654. */
  35655. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35656. if (coneOuterAngle < coneInnerAngle) {
  35657. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35658. return;
  35659. }
  35660. this._coneInnerAngle = coneInnerAngle;
  35661. this._coneOuterAngle = coneOuterAngle;
  35662. this._coneOuterGain = coneOuterGain;
  35663. this._isDirectional = true;
  35664. if (this.isPlaying && this.loop) {
  35665. this.stop();
  35666. this.play();
  35667. }
  35668. };
  35669. Sound.prototype.setPosition = function (newPosition) {
  35670. this._position = newPosition;
  35671. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35672. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35673. }
  35674. };
  35675. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35676. this._localDirection = newLocalDirection;
  35677. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35678. this._updateDirection();
  35679. }
  35680. };
  35681. Sound.prototype._updateDirection = function () {
  35682. var mat = this._connectedMesh.getWorldMatrix();
  35683. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35684. direction.normalize();
  35685. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35686. };
  35687. Sound.prototype.updateDistanceFromListener = function () {
  35688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35689. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35690. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35691. }
  35692. };
  35693. Sound.prototype.setAttenuationFunction = function (callback) {
  35694. this._customAttenuationFunction = callback;
  35695. };
  35696. /**
  35697. * Play the sound
  35698. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35699. */
  35700. Sound.prototype.play = function (time) {
  35701. var _this = this;
  35702. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35703. try {
  35704. if (this._startOffset < 0) {
  35705. time = -this._startOffset;
  35706. this._startOffset = 0;
  35707. }
  35708. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35709. if (!this._soundSource || !this._streamingSource) {
  35710. if (this.spatialSound) {
  35711. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35712. if (this._isDirectional) {
  35713. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35714. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35715. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35716. if (this._connectedMesh) {
  35717. this._updateDirection();
  35718. }
  35719. else {
  35720. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35721. }
  35722. }
  35723. }
  35724. }
  35725. if (this._streaming) {
  35726. if (!this._streamingSource) {
  35727. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35728. this._htmlAudioElement.onended = function () { _this._onended(); };
  35729. this._htmlAudioElement.playbackRate = this._playbackRate;
  35730. }
  35731. this._streamingSource.disconnect();
  35732. this._streamingSource.connect(this._inputAudioNode);
  35733. this._htmlAudioElement.play();
  35734. }
  35735. else {
  35736. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35737. this._soundSource.buffer = this._audioBuffer;
  35738. this._soundSource.connect(this._inputAudioNode);
  35739. this._soundSource.loop = this.loop;
  35740. this._soundSource.playbackRate.value = this._playbackRate;
  35741. this._soundSource.onended = function () { _this._onended(); };
  35742. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35743. }
  35744. this._startTime = startTime;
  35745. this.isPlaying = true;
  35746. this.isPaused = false;
  35747. }
  35748. catch (ex) {
  35749. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35750. }
  35751. }
  35752. };
  35753. Sound.prototype._onended = function () {
  35754. this.isPlaying = false;
  35755. if (this.onended) {
  35756. this.onended();
  35757. }
  35758. };
  35759. /**
  35760. * Stop the sound
  35761. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35762. */
  35763. Sound.prototype.stop = function (time) {
  35764. if (this.isPlaying) {
  35765. if (this._streaming) {
  35766. this._htmlAudioElement.pause();
  35767. // Test needed for Firefox or it will generate an Invalid State Error
  35768. if (this._htmlAudioElement.currentTime > 0) {
  35769. this._htmlAudioElement.currentTime = 0;
  35770. }
  35771. }
  35772. else {
  35773. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35774. this._soundSource.stop(stopTime);
  35775. if (!this.isPaused) {
  35776. this._startOffset = 0;
  35777. }
  35778. }
  35779. this.isPlaying = false;
  35780. }
  35781. };
  35782. Sound.prototype.pause = function () {
  35783. if (this.isPlaying) {
  35784. this.isPaused = true;
  35785. if (this._streaming) {
  35786. this._htmlAudioElement.pause();
  35787. }
  35788. else {
  35789. this.stop(0);
  35790. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35791. }
  35792. }
  35793. };
  35794. Sound.prototype.setVolume = function (newVolume, time) {
  35795. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35796. if (time) {
  35797. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35798. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35799. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35800. }
  35801. else {
  35802. this._soundGain.gain.value = newVolume;
  35803. }
  35804. }
  35805. this._volume = newVolume;
  35806. };
  35807. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35808. this._playbackRate = newPlaybackRate;
  35809. if (this.isPlaying) {
  35810. if (this._streaming) {
  35811. this._htmlAudioElement.playbackRate = this._playbackRate;
  35812. }
  35813. else {
  35814. this._soundSource.playbackRate.value = this._playbackRate;
  35815. }
  35816. }
  35817. };
  35818. Sound.prototype.getVolume = function () {
  35819. return this._volume;
  35820. };
  35821. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35822. var _this = this;
  35823. if (this._connectedMesh) {
  35824. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35825. this._registerFunc = null;
  35826. }
  35827. this._connectedMesh = meshToConnectTo;
  35828. if (!this.spatialSound) {
  35829. this.spatialSound = true;
  35830. this._createSpatialParameters();
  35831. if (this.isPlaying && this.loop) {
  35832. this.stop();
  35833. this.play();
  35834. }
  35835. }
  35836. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35837. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35838. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35839. };
  35840. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35841. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35842. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35843. this._updateDirection();
  35844. }
  35845. };
  35846. Sound.prototype.clone = function () {
  35847. var _this = this;
  35848. if (!this._streaming) {
  35849. var setBufferAndRun = function () {
  35850. if (_this._isReadyToPlay) {
  35851. clonedSound._audioBuffer = _this.getAudioBuffer();
  35852. clonedSound._isReadyToPlay = true;
  35853. if (clonedSound.autoplay) {
  35854. clonedSound.play();
  35855. }
  35856. }
  35857. else {
  35858. window.setTimeout(setBufferAndRun, 300);
  35859. }
  35860. };
  35861. var currentOptions = {
  35862. autoplay: this.autoplay, loop: this.loop,
  35863. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35864. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35865. refDistance: this.refDistance, distanceModel: this.distanceModel
  35866. };
  35867. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35868. if (this.useCustomAttenuation) {
  35869. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35870. }
  35871. clonedSound.setPosition(this._position);
  35872. clonedSound.setPlaybackRate(this._playbackRate);
  35873. setBufferAndRun();
  35874. return clonedSound;
  35875. }
  35876. else {
  35877. return null;
  35878. }
  35879. };
  35880. Sound.prototype.getAudioBuffer = function () {
  35881. return this._audioBuffer;
  35882. };
  35883. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35884. var soundName = parsedSound.name;
  35885. var soundUrl;
  35886. if (parsedSound.url) {
  35887. soundUrl = rootUrl + parsedSound.url;
  35888. }
  35889. else {
  35890. soundUrl = rootUrl + soundName;
  35891. }
  35892. var options = {
  35893. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35894. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35895. rolloffFactor: parsedSound.rolloffFactor,
  35896. refDistance: parsedSound.refDistance,
  35897. distanceModel: parsedSound.distanceModel,
  35898. playbackRate: parsedSound.playbackRate
  35899. };
  35900. var newSound;
  35901. if (!sourceSound) {
  35902. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35903. scene._addPendingData(newSound);
  35904. }
  35905. else {
  35906. var setBufferAndRun = function () {
  35907. if (sourceSound._isReadyToPlay) {
  35908. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35909. newSound._isReadyToPlay = true;
  35910. if (newSound.autoplay) {
  35911. newSound.play();
  35912. }
  35913. }
  35914. else {
  35915. window.setTimeout(setBufferAndRun, 300);
  35916. }
  35917. };
  35918. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35919. setBufferAndRun();
  35920. }
  35921. if (parsedSound.position) {
  35922. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35923. newSound.setPosition(soundPosition);
  35924. }
  35925. if (parsedSound.isDirectional) {
  35926. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35927. if (parsedSound.localDirectionToMesh) {
  35928. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35929. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35930. }
  35931. }
  35932. if (parsedSound.connectedMeshId) {
  35933. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35934. if (connectedMesh) {
  35935. newSound.attachToMesh(connectedMesh);
  35936. }
  35937. }
  35938. return newSound;
  35939. };
  35940. return Sound;
  35941. })();
  35942. BABYLON.Sound = Sound;
  35943. })(BABYLON || (BABYLON = {}));
  35944. var BABYLON;
  35945. (function (BABYLON) {
  35946. var SoundTrack = (function () {
  35947. function SoundTrack(scene, options) {
  35948. this.id = -1;
  35949. this._isMainTrack = false;
  35950. this._isInitialized = false;
  35951. this._scene = scene;
  35952. this.soundCollection = new Array();
  35953. this._options = options;
  35954. if (!this._isMainTrack) {
  35955. this._scene.soundTracks.push(this);
  35956. this.id = this._scene.soundTracks.length - 1;
  35957. }
  35958. }
  35959. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35960. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35961. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35962. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35963. if (this._options) {
  35964. if (this._options.volume) {
  35965. this._outputAudioNode.gain.value = this._options.volume;
  35966. }
  35967. if (this._options.mainTrack) {
  35968. this._isMainTrack = this._options.mainTrack;
  35969. }
  35970. }
  35971. this._isInitialized = true;
  35972. }
  35973. };
  35974. SoundTrack.prototype.dispose = function () {
  35975. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35976. if (this._connectedAnalyser) {
  35977. this._connectedAnalyser.stopDebugCanvas();
  35978. }
  35979. while (this.soundCollection.length) {
  35980. this.soundCollection[0].dispose();
  35981. }
  35982. if (this._outputAudioNode) {
  35983. this._outputAudioNode.disconnect();
  35984. }
  35985. this._outputAudioNode = null;
  35986. }
  35987. };
  35988. SoundTrack.prototype.AddSound = function (sound) {
  35989. if (!this._isInitialized) {
  35990. this._initializeSoundTrackAudioGraph();
  35991. }
  35992. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35993. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35994. }
  35995. if (sound.soundTrackId) {
  35996. if (sound.soundTrackId === -1) {
  35997. this._scene.mainSoundTrack.RemoveSound(sound);
  35998. }
  35999. else {
  36000. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36001. }
  36002. }
  36003. this.soundCollection.push(sound);
  36004. sound.soundTrackId = this.id;
  36005. };
  36006. SoundTrack.prototype.RemoveSound = function (sound) {
  36007. var index = this.soundCollection.indexOf(sound);
  36008. if (index !== -1) {
  36009. this.soundCollection.splice(index, 1);
  36010. }
  36011. };
  36012. SoundTrack.prototype.setVolume = function (newVolume) {
  36013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36014. this._outputAudioNode.gain.value = newVolume;
  36015. }
  36016. };
  36017. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36018. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36019. for (var i = 0; i < this.soundCollection.length; i++) {
  36020. this.soundCollection[i].switchPanningModelToHRTF();
  36021. }
  36022. }
  36023. };
  36024. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36025. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36026. for (var i = 0; i < this.soundCollection.length; i++) {
  36027. this.soundCollection[i].switchPanningModelToEqualPower();
  36028. }
  36029. }
  36030. };
  36031. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36032. if (this._connectedAnalyser) {
  36033. this._connectedAnalyser.stopDebugCanvas();
  36034. }
  36035. this._connectedAnalyser = analyser;
  36036. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36037. this._outputAudioNode.disconnect();
  36038. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36039. }
  36040. };
  36041. return SoundTrack;
  36042. })();
  36043. BABYLON.SoundTrack = SoundTrack;
  36044. })(BABYLON || (BABYLON = {}));
  36045. var BABYLON;
  36046. (function (BABYLON) {
  36047. var DepthRenderer = (function () {
  36048. function DepthRenderer(scene, type) {
  36049. var _this = this;
  36050. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  36051. this._viewMatrix = BABYLON.Matrix.Zero();
  36052. this._projectionMatrix = BABYLON.Matrix.Zero();
  36053. this._transformMatrix = BABYLON.Matrix.Zero();
  36054. this._worldViewProjection = BABYLON.Matrix.Zero();
  36055. this._scene = scene;
  36056. var engine = scene.getEngine();
  36057. // Render target
  36058. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  36059. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36060. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36061. this._depthMap.refreshRate = 1;
  36062. this._depthMap.renderParticles = false;
  36063. this._depthMap.renderList = null;
  36064. // set default depth value to 1.0 (far away)
  36065. this._depthMap.onClear = function (engine) {
  36066. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  36067. };
  36068. // Custom render function
  36069. var renderSubMesh = function (subMesh) {
  36070. var mesh = subMesh.getRenderingMesh();
  36071. var scene = _this._scene;
  36072. var engine = scene.getEngine();
  36073. // Culling
  36074. engine.setState(subMesh.getMaterial().backFaceCulling);
  36075. // Managing instances
  36076. var batch = mesh._getInstancesRenderList(subMesh._id);
  36077. if (batch.mustReturn) {
  36078. return;
  36079. }
  36080. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36081. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36082. engine.enableEffect(_this._effect);
  36083. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  36084. var material = subMesh.getMaterial();
  36085. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  36086. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  36087. // Alpha test
  36088. if (material && material.needAlphaTesting()) {
  36089. var alphaTexture = material.getAlphaTestTexture();
  36090. _this._effect.setTexture("diffuseSampler", alphaTexture);
  36091. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36092. }
  36093. // Bones
  36094. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36095. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36096. }
  36097. // Draw
  36098. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  36099. }
  36100. };
  36101. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  36102. var index;
  36103. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36104. renderSubMesh(opaqueSubMeshes.data[index]);
  36105. }
  36106. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36107. renderSubMesh(alphaTestSubMeshes.data[index]);
  36108. }
  36109. };
  36110. }
  36111. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  36112. var defines = [];
  36113. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36114. var mesh = subMesh.getMesh();
  36115. var scene = mesh.getScene();
  36116. var material = subMesh.getMaterial();
  36117. // Alpha test
  36118. if (material && material.needAlphaTesting()) {
  36119. defines.push("#define ALPHATEST");
  36120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36121. attribs.push(BABYLON.VertexBuffer.UVKind);
  36122. defines.push("#define UV1");
  36123. }
  36124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36126. defines.push("#define UV2");
  36127. }
  36128. }
  36129. // Bones
  36130. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36131. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36132. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36133. if (mesh.numBoneInfluencers > 4) {
  36134. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36135. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36136. }
  36137. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36138. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36139. }
  36140. else {
  36141. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36142. }
  36143. // Instances
  36144. if (useInstances) {
  36145. defines.push("#define INSTANCES");
  36146. attribs.push("world0");
  36147. attribs.push("world1");
  36148. attribs.push("world2");
  36149. attribs.push("world3");
  36150. }
  36151. // Get correct effect
  36152. var join = defines.join("\n");
  36153. if (this._cachedDefines !== join) {
  36154. this._cachedDefines = join;
  36155. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36156. }
  36157. return this._effect.isReady();
  36158. };
  36159. DepthRenderer.prototype.getDepthMap = function () {
  36160. return this._depthMap;
  36161. };
  36162. // Methods
  36163. DepthRenderer.prototype.dispose = function () {
  36164. this._depthMap.dispose();
  36165. };
  36166. return DepthRenderer;
  36167. })();
  36168. BABYLON.DepthRenderer = DepthRenderer;
  36169. })(BABYLON || (BABYLON = {}));
  36170. var BABYLON;
  36171. (function (BABYLON) {
  36172. var SSAORenderingPipeline = (function (_super) {
  36173. __extends(SSAORenderingPipeline, _super);
  36174. /**
  36175. * @constructor
  36176. * @param {string} name - The rendering pipeline name
  36177. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36178. * @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 }
  36179. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36180. */
  36181. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36182. var _this = this;
  36183. _super.call(this, scene.getEngine(), name);
  36184. // Members
  36185. /**
  36186. * The PassPostProcess id in the pipeline that contains the original scene color
  36187. * @type {string}
  36188. */
  36189. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36190. /**
  36191. * The SSAO PostProcess id in the pipeline
  36192. * @type {string}
  36193. */
  36194. this.SSAORenderEffect = "SSAORenderEffect";
  36195. /**
  36196. * The horizontal blur PostProcess id in the pipeline
  36197. * @type {string}
  36198. */
  36199. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36200. /**
  36201. * The vertical blur PostProcess id in the pipeline
  36202. * @type {string}
  36203. */
  36204. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36205. /**
  36206. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36207. * @type {string}
  36208. */
  36209. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36210. /**
  36211. * The output strength of the SSAO post-process. Default value is 1.0.
  36212. * @type {number}
  36213. */
  36214. this.totalStrength = 1.0;
  36215. /**
  36216. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36217. * @type {number}
  36218. */
  36219. this.radius = 0.0001;
  36220. /**
  36221. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36222. * Must not be equal to fallOff and superior to fallOff.
  36223. * Default value is 0.975
  36224. * @type {number}
  36225. */
  36226. this.area = 0.0075;
  36227. /**
  36228. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36229. * Must not be equal to area and inferior to area.
  36230. * Default value is 0.0
  36231. * @type {number}
  36232. */
  36233. this.fallOff = 0.000001;
  36234. /**
  36235. * The base color of the SSAO post-process
  36236. * The final result is "base + ssao" between [0, 1]
  36237. * @type {number}
  36238. */
  36239. this.base = 0.5;
  36240. this._firstUpdate = true;
  36241. this._scene = scene;
  36242. // Set up assets
  36243. this._createRandomTexture();
  36244. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36245. var ssaoRatio = ratio.ssaoRatio || ratio;
  36246. var combineRatio = ratio.combineRatio || ratio;
  36247. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36248. this._createSSAOPostProcess(ssaoRatio);
  36249. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36250. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36251. this._createSSAOCombinePostProcess(combineRatio);
  36252. // Set up pipeline
  36253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36254. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36258. // Finish
  36259. scene.postProcessRenderPipelineManager.addPipeline(this);
  36260. if (cameras)
  36261. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36262. }
  36263. // Public Methods
  36264. /**
  36265. * Returns the horizontal blur PostProcess
  36266. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36267. */
  36268. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36269. return this._blurHPostProcess;
  36270. };
  36271. /**
  36272. * Returns the vertical blur PostProcess
  36273. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36274. */
  36275. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36276. return this._blurVPostProcess;
  36277. };
  36278. /**
  36279. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36280. */
  36281. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36282. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36283. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36284. this._originalColorPostProcess = undefined;
  36285. this._ssaoPostProcess = undefined;
  36286. this._blurHPostProcess = undefined;
  36287. this._blurVPostProcess = undefined;
  36288. this._ssaoCombinePostProcess = undefined;
  36289. this._randomTexture.dispose();
  36290. if (disableDepthRender)
  36291. this._scene.disableDepthRenderer();
  36292. };
  36293. // Private Methods
  36294. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36295. var _this = this;
  36296. var numSamples = 16;
  36297. var sampleSphere = [
  36298. 0.5381, 0.1856, -0.4319,
  36299. 0.1379, 0.2486, 0.4430,
  36300. 0.3371, 0.5679, -0.0057,
  36301. -0.6999, -0.0451, -0.0019,
  36302. 0.0689, -0.1598, -0.8547,
  36303. 0.0560, 0.0069, -0.1843,
  36304. -0.0146, 0.1402, 0.0762,
  36305. 0.0100, -0.1924, -0.0344,
  36306. -0.3577, -0.5301, -0.4358,
  36307. -0.3169, 0.1063, 0.0158,
  36308. 0.0103, -0.5869, 0.0046,
  36309. -0.0897, -0.4940, 0.3287,
  36310. 0.7119, -0.0154, -0.0918,
  36311. -0.0533, 0.0596, -0.5411,
  36312. 0.0352, -0.0631, 0.5460,
  36313. -0.4776, 0.2847, -0.0271
  36314. ];
  36315. var samplesFactor = 1.0 / numSamples;
  36316. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36317. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36318. "area", "fallOff", "base"
  36319. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36320. this._ssaoPostProcess.onApply = function (effect) {
  36321. if (_this._firstUpdate) {
  36322. effect.setArray3("sampleSphere", sampleSphere);
  36323. effect.setFloat("samplesFactor", samplesFactor);
  36324. effect.setFloat("randTextureTiles", 4.0);
  36325. _this._firstUpdate = false;
  36326. }
  36327. effect.setFloat("totalStrength", _this.totalStrength);
  36328. effect.setFloat("radius", _this.radius);
  36329. effect.setFloat("area", _this.area);
  36330. effect.setFloat("fallOff", _this.fallOff);
  36331. effect.setFloat("base", _this.base);
  36332. effect.setTexture("textureSampler", _this._depthTexture);
  36333. effect.setTexture("randomSampler", _this._randomTexture);
  36334. };
  36335. };
  36336. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36337. var _this = this;
  36338. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36339. this._ssaoCombinePostProcess.onApply = function (effect) {
  36340. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36341. };
  36342. };
  36343. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36344. var size = 512;
  36345. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36346. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36347. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36348. var context = this._randomTexture.getContext();
  36349. var rand = function (min, max) {
  36350. return Math.random() * (max - min) + min;
  36351. };
  36352. var randVector = BABYLON.Vector3.Zero();
  36353. for (var x = 0; x < size; x++) {
  36354. for (var y = 0; y < size; y++) {
  36355. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36356. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36357. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36358. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36359. context.fillRect(x, y, 1, 1);
  36360. }
  36361. }
  36362. this._randomTexture.update(false);
  36363. };
  36364. return SSAORenderingPipeline;
  36365. })(BABYLON.PostProcessRenderPipeline);
  36366. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36367. })(BABYLON || (BABYLON = {}));
  36368. var BABYLON;
  36369. (function (BABYLON) {
  36370. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36371. var VolumetricLightScatteringPostProcess = (function (_super) {
  36372. __extends(VolumetricLightScatteringPostProcess, _super);
  36373. /**
  36374. * @constructor
  36375. * @param {string} name - The post-process name
  36376. * @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)
  36377. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36378. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36379. * @param {number} samples - The post-process quality, default 100
  36380. * @param {number} samplingMode - The post-process filtering mode
  36381. * @param {BABYLON.Engine} engine - The babylon engine
  36382. * @param {boolean} reusable - If the post-process is reusable
  36383. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36384. */
  36385. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36386. var _this = this;
  36387. if (samples === void 0) { samples = 100; }
  36388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36389. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36390. this._screenCoordinates = BABYLON.Vector2.Zero();
  36391. /**
  36392. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36393. * @type {boolean}
  36394. */
  36395. this.useCustomMeshPosition = false;
  36396. /**
  36397. * If the post-process should inverse the light scattering direction
  36398. * @type {boolean}
  36399. */
  36400. this.invert = true;
  36401. /**
  36402. * Set to true to use the diffuseColor instead of the diffuseTexture
  36403. * @type {boolean}
  36404. */
  36405. this.useDiffuseColor = false;
  36406. /**
  36407. * Array containing the excluded meshes not rendered in the internal pass
  36408. */
  36409. this.excludedMeshes = new Array();
  36410. /**
  36411. * Controls the overall intensity of the post-process
  36412. * @type {number}
  36413. */
  36414. this.exposure = 0.3;
  36415. /**
  36416. * Dissipates each sample's contribution in range [0, 1]
  36417. * @type {number}
  36418. */
  36419. this.decay = 0.96815;
  36420. /**
  36421. * Controls the overall intensity of each sample
  36422. * @type {number}
  36423. */
  36424. this.weight = 0.58767;
  36425. /**
  36426. * Controls the density of each sample
  36427. * @type {number}
  36428. */
  36429. this.density = 0.926;
  36430. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36431. var engine = scene.getEngine();
  36432. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36433. // Configure mesh
  36434. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36435. // Configure
  36436. this._createPass(scene, ratio.passRatio || ratio);
  36437. this.onActivate = function (camera) {
  36438. if (!_this.isSupported) {
  36439. _this.dispose(camera);
  36440. }
  36441. _this.onActivate = null;
  36442. };
  36443. this.onApply = function (effect) {
  36444. _this._updateMeshScreenCoordinates(scene);
  36445. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36446. effect.setFloat("exposure", _this.exposure);
  36447. effect.setFloat("decay", _this.decay);
  36448. effect.setFloat("weight", _this.weight);
  36449. effect.setFloat("density", _this.density);
  36450. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36451. };
  36452. }
  36453. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36454. var mesh = subMesh.getMesh();
  36455. var defines = [];
  36456. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36457. var material = subMesh.getMaterial();
  36458. var needUV = false;
  36459. // Render this.mesh as default
  36460. if (mesh === this.mesh) {
  36461. if (this.useDiffuseColor) {
  36462. defines.push("#define DIFFUSE_COLOR_RENDER");
  36463. }
  36464. else if (material) {
  36465. if (material.diffuseTexture !== undefined) {
  36466. defines.push("#define BASIC_RENDER");
  36467. }
  36468. else {
  36469. defines.push("#define DIFFUSE_COLOR_RENDER");
  36470. }
  36471. }
  36472. defines.push("#define NEED_UV");
  36473. needUV = true;
  36474. }
  36475. // Alpha test
  36476. if (material) {
  36477. if (material.needAlphaTesting()) {
  36478. defines.push("#define ALPHATEST");
  36479. }
  36480. if (material.opacityTexture !== undefined) {
  36481. defines.push("#define OPACITY");
  36482. if (material.opacityTexture.getAlphaFromRGB) {
  36483. defines.push("#define OPACITYRGB");
  36484. }
  36485. if (!needUV) {
  36486. defines.push("#define NEED_UV");
  36487. }
  36488. }
  36489. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36490. attribs.push(BABYLON.VertexBuffer.UVKind);
  36491. defines.push("#define UV1");
  36492. }
  36493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36494. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36495. defines.push("#define UV2");
  36496. }
  36497. }
  36498. // Bones
  36499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36502. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36503. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36504. }
  36505. else {
  36506. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36507. }
  36508. // Instances
  36509. if (useInstances) {
  36510. defines.push("#define INSTANCES");
  36511. attribs.push("world0");
  36512. attribs.push("world1");
  36513. attribs.push("world2");
  36514. attribs.push("world3");
  36515. }
  36516. // Get correct effect
  36517. var join = defines.join("\n");
  36518. if (this._cachedDefines !== join) {
  36519. this._cachedDefines = join;
  36520. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36521. }
  36522. return this._volumetricLightScatteringPass.isReady();
  36523. };
  36524. /**
  36525. * Sets the new light position for light scattering effect
  36526. * @param {BABYLON.Vector3} The new custom light position
  36527. */
  36528. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36529. this._customMeshPosition = position;
  36530. };
  36531. /**
  36532. * Returns the light position for light scattering effect
  36533. * @return {BABYLON.Vector3} The custom light position
  36534. */
  36535. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36536. return this._customMeshPosition;
  36537. };
  36538. /**
  36539. * Disposes the internal assets and detaches the post-process from the camera
  36540. */
  36541. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36542. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36543. if (rttIndex !== -1) {
  36544. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36545. }
  36546. this._volumetricLightScatteringRTT.dispose();
  36547. _super.prototype.dispose.call(this, camera);
  36548. };
  36549. /**
  36550. * Returns the render target texture used by the post-process
  36551. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36552. */
  36553. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36554. return this._volumetricLightScatteringRTT;
  36555. };
  36556. // Private methods
  36557. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36558. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36559. return true;
  36560. }
  36561. return false;
  36562. };
  36563. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36564. var _this = this;
  36565. var engine = scene.getEngine();
  36566. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36567. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36568. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36569. this._volumetricLightScatteringRTT.renderList = null;
  36570. this._volumetricLightScatteringRTT.renderParticles = false;
  36571. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36572. // Custom render function for submeshes
  36573. var renderSubMesh = function (subMesh) {
  36574. var mesh = subMesh.getRenderingMesh();
  36575. if (_this._meshExcluded(mesh)) {
  36576. return;
  36577. }
  36578. var scene = mesh.getScene();
  36579. var engine = scene.getEngine();
  36580. // Culling
  36581. engine.setState(subMesh.getMaterial().backFaceCulling);
  36582. // Managing instances
  36583. var batch = mesh._getInstancesRenderList(subMesh._id);
  36584. if (batch.mustReturn) {
  36585. return;
  36586. }
  36587. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36588. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36589. engine.enableEffect(_this._volumetricLightScatteringPass);
  36590. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36591. var material = subMesh.getMaterial();
  36592. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36593. // Alpha test
  36594. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36595. var alphaTexture = material.getAlphaTestTexture();
  36596. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36597. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36598. }
  36599. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36600. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36601. if (alphaTexture) {
  36602. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36603. }
  36604. }
  36605. if (material.opacityTexture !== undefined) {
  36606. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36607. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36608. }
  36609. }
  36610. // Bones
  36611. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36612. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36613. }
  36614. // Draw
  36615. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36616. }
  36617. };
  36618. // Render target texture callbacks
  36619. var savedSceneClearColor;
  36620. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36621. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36622. savedSceneClearColor = scene.clearColor;
  36623. scene.clearColor = sceneClearColor;
  36624. };
  36625. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36626. scene.clearColor = savedSceneClearColor;
  36627. };
  36628. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36629. var engine = scene.getEngine();
  36630. var index;
  36631. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36632. renderSubMesh(opaqueSubMeshes.data[index]);
  36633. }
  36634. engine.setAlphaTesting(true);
  36635. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36636. renderSubMesh(alphaTestSubMeshes.data[index]);
  36637. }
  36638. engine.setAlphaTesting(false);
  36639. if (transparentSubMeshes.length) {
  36640. // Sort sub meshes
  36641. for (index = 0; index < transparentSubMeshes.length; index++) {
  36642. var submesh = transparentSubMeshes.data[index];
  36643. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36644. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36645. }
  36646. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36647. sortedArray.sort(function (a, b) {
  36648. // Alpha index first
  36649. if (a._alphaIndex > b._alphaIndex) {
  36650. return 1;
  36651. }
  36652. if (a._alphaIndex < b._alphaIndex) {
  36653. return -1;
  36654. }
  36655. // Then distance to camera
  36656. if (a._distanceToCamera < b._distanceToCamera) {
  36657. return 1;
  36658. }
  36659. if (a._distanceToCamera > b._distanceToCamera) {
  36660. return -1;
  36661. }
  36662. return 0;
  36663. });
  36664. // Render sub meshes
  36665. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36666. for (index = 0; index < sortedArray.length; index++) {
  36667. renderSubMesh(sortedArray[index]);
  36668. }
  36669. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36670. }
  36671. };
  36672. };
  36673. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36674. var transform = scene.getTransformMatrix();
  36675. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36676. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36677. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36678. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36679. if (this.invert)
  36680. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36681. };
  36682. // Static methods
  36683. /**
  36684. * Creates a default mesh for the Volumeric Light Scattering post-process
  36685. * @param {string} The mesh name
  36686. * @param {BABYLON.Scene} The scene where to create the mesh
  36687. * @return {BABYLON.Mesh} the default mesh
  36688. */
  36689. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36690. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36691. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36692. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36693. return mesh;
  36694. };
  36695. return VolumetricLightScatteringPostProcess;
  36696. })(BABYLON.PostProcess);
  36697. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36698. })(BABYLON || (BABYLON = {}));
  36699. // BABYLON.JS Chromatic Aberration GLSL Shader
  36700. // Author: Olivier Guyot
  36701. // Separates very slightly R, G and B colors on the edges of the screen
  36702. // Inspired by Francois Tarlier & Martins Upitis
  36703. var BABYLON;
  36704. (function (BABYLON) {
  36705. var LensRenderingPipeline = (function (_super) {
  36706. __extends(LensRenderingPipeline, _super);
  36707. /**
  36708. * @constructor
  36709. *
  36710. * Effect parameters are as follow:
  36711. * {
  36712. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36713. * edge_blur: number; // from 0 to x (1 for realism)
  36714. * distortion: number; // from 0 to x (1 for realism)
  36715. * grain_amount: number; // from 0 to 1
  36716. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36717. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36718. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36719. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36720. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36721. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36722. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36723. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36724. * }
  36725. * Note: if an effect parameter is unset, effect is disabled
  36726. *
  36727. * @param {string} name - The rendering pipeline name
  36728. * @param {object} parameters - An object containing all parameters (see above)
  36729. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36730. * @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)
  36731. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36732. */
  36733. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36734. var _this = this;
  36735. if (ratio === void 0) { ratio = 1.0; }
  36736. _super.call(this, scene.getEngine(), name);
  36737. // Lens effects can be of the following:
  36738. // - chromatic aberration (slight shift of RGB colors)
  36739. // - blur on the edge of the lens
  36740. // - lens distortion
  36741. // - depth-of-field blur & highlights enhancing
  36742. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36743. // - grain effect (noise or custom texture)
  36744. // Two additional texture samplers are needed:
  36745. // - depth map (for depth-of-field)
  36746. // - grain texture
  36747. /**
  36748. * The chromatic aberration PostProcess id in the pipeline
  36749. * @type {string}
  36750. */
  36751. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36752. /**
  36753. * The highlights enhancing PostProcess id in the pipeline
  36754. * @type {string}
  36755. */
  36756. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36757. /**
  36758. * The depth-of-field PostProcess id in the pipeline
  36759. * @type {string}
  36760. */
  36761. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36762. this._scene = scene;
  36763. // Fetch texture samplers
  36764. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36765. if (parameters.grain_texture) {
  36766. this._grainTexture = parameters.grain_texture;
  36767. }
  36768. else {
  36769. this._createGrainTexture();
  36770. }
  36771. // save parameters
  36772. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36773. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36774. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36775. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36776. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36777. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36778. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36779. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36780. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36781. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36782. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36783. // Create effects
  36784. this._createChromaticAberrationPostProcess(ratio);
  36785. this._createHighlightsPostProcess(ratio);
  36786. this._createDepthOfFieldPostProcess(ratio / 4);
  36787. // Set up pipeline
  36788. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36791. if (this._highlightsGain === -1) {
  36792. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36793. }
  36794. // Finish
  36795. scene.postProcessRenderPipelineManager.addPipeline(this);
  36796. if (cameras) {
  36797. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36798. }
  36799. }
  36800. // public methods (self explanatory)
  36801. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36802. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36803. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36804. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36805. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36806. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36807. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36808. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36809. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36810. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36811. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36812. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36813. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36814. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36815. };
  36816. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36817. this._highlightsPostProcess.updateEffect();
  36818. };
  36819. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36820. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36821. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36822. this._highlightsGain = amount;
  36823. };
  36824. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36825. if (this._highlightsGain === -1) {
  36826. this._highlightsGain = 1.0;
  36827. }
  36828. this._highlightsThreshold = amount;
  36829. };
  36830. LensRenderingPipeline.prototype.disableHighlights = function () {
  36831. this._highlightsGain = -1;
  36832. };
  36833. /**
  36834. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36835. */
  36836. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36837. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36838. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36839. this._chromaticAberrationPostProcess = undefined;
  36840. this._highlightsPostProcess = undefined;
  36841. this._depthOfFieldPostProcess = undefined;
  36842. this._grainTexture.dispose();
  36843. if (disableDepthRender)
  36844. this._scene.disableDepthRenderer();
  36845. };
  36846. // colors shifting and distortion
  36847. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36848. var _this = this;
  36849. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36850. [], // samplers
  36851. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36852. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36853. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36854. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36855. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36856. };
  36857. };
  36858. // highlights enhancing
  36859. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36860. var _this = this;
  36861. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36862. [], // samplers
  36863. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36864. this._highlightsPostProcess.onApply = function (effect) {
  36865. effect.setFloat('gain', _this._highlightsGain);
  36866. effect.setFloat('threshold', _this._highlightsThreshold);
  36867. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36868. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36869. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36870. };
  36871. };
  36872. // colors shifting and distortion
  36873. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36874. var _this = this;
  36875. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36876. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36877. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36878. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36879. this._depthOfFieldPostProcess.onApply = function (effect) {
  36880. effect.setTexture("depthSampler", _this._depthTexture);
  36881. effect.setTexture("grainSampler", _this._grainTexture);
  36882. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36883. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36884. effect.setFloat('grain_amount', _this._grainAmount);
  36885. effect.setBool('blur_noise', _this._blurNoise);
  36886. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36887. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36888. effect.setFloat('distortion', _this._distortion);
  36889. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36890. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36891. effect.setFloat('aperture', _this._dofAperture);
  36892. effect.setFloat('darken', _this._dofDarken);
  36893. effect.setFloat('edge_blur', _this._edgeBlur);
  36894. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36895. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36896. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36897. };
  36898. };
  36899. // creates a black and white random noise texture, 512x512
  36900. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36901. var size = 512;
  36902. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36903. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36904. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36905. var context = this._grainTexture.getContext();
  36906. var rand = function (min, max) {
  36907. return Math.random() * (max - min) + min;
  36908. };
  36909. var value;
  36910. for (var x = 0; x < size; x++) {
  36911. for (var y = 0; y < size; y++) {
  36912. value = Math.floor(rand(0.42, 0.58) * 255);
  36913. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36914. context.fillRect(x, y, 1, 1);
  36915. }
  36916. }
  36917. this._grainTexture.update(false);
  36918. };
  36919. return LensRenderingPipeline;
  36920. })(BABYLON.PostProcessRenderPipeline);
  36921. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36922. })(BABYLON || (BABYLON = {}));
  36923. //
  36924. // This post-process allows the modification of rendered colors by using
  36925. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36926. //
  36927. // The object needs to be provided an url to a texture containing the color
  36928. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36929. // Use an image editing software to tweak the LUT to match your needs.
  36930. //
  36931. // For an example of a color LUT, see here:
  36932. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36933. // For explanations on color grading, see here:
  36934. // http://udn.epicgames.com/Three/ColorGrading.html
  36935. //
  36936. var BABYLON;
  36937. (function (BABYLON) {
  36938. var ColorCorrectionPostProcess = (function (_super) {
  36939. __extends(ColorCorrectionPostProcess, _super);
  36940. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36941. var _this = this;
  36942. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36943. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36944. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36945. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36946. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36947. this.onApply = function (effect) {
  36948. effect.setTexture("colorTable", _this._colorTableTexture);
  36949. };
  36950. }
  36951. return ColorCorrectionPostProcess;
  36952. })(BABYLON.PostProcess);
  36953. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36954. })(BABYLON || (BABYLON = {}));
  36955. var BABYLON;
  36956. (function (BABYLON) {
  36957. var HDRRenderingPipeline = (function (_super) {
  36958. __extends(HDRRenderingPipeline, _super);
  36959. /**
  36960. * @constructor
  36961. * @param {string} name - The rendering pipeline name
  36962. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36963. * @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)
  36964. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36965. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36966. */
  36967. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36968. var _this = this;
  36969. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36970. _super.call(this, scene.getEngine(), name);
  36971. /**
  36972. * Public members
  36973. */
  36974. // Gaussian Blur
  36975. /**
  36976. * Gaussian blur coefficient
  36977. * @type {number}
  36978. */
  36979. this.gaussCoeff = 0.3;
  36980. /**
  36981. * Gaussian blur mean
  36982. * @type {number}
  36983. */
  36984. this.gaussMean = 1.0;
  36985. /**
  36986. * Gaussian blur standard deviation
  36987. * @type {number}
  36988. */
  36989. this.gaussStandDev = 0.8;
  36990. /**
  36991. * Gaussian blur multiplier. Multiplies the blur effect
  36992. * @type {number}
  36993. */
  36994. this.gaussMultiplier = 4.0;
  36995. // HDR
  36996. /**
  36997. * Exposure, controls the overall intensity of the pipeline
  36998. * @type {number}
  36999. */
  37000. this.exposure = 1.0;
  37001. /**
  37002. * Minimum luminance that the post-process can output. Luminance is >= 0
  37003. * @type {number}
  37004. */
  37005. this.minimumLuminance = 1.0;
  37006. /**
  37007. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  37008. * @type {number}
  37009. */
  37010. this.maximumLuminance = 1e20;
  37011. /**
  37012. * Increase rate for luminance: eye adaptation speed to dark
  37013. * @type {number}
  37014. */
  37015. this.luminanceIncreaserate = 0.5;
  37016. /**
  37017. * Decrease rate for luminance: eye adaptation speed to bright
  37018. * @type {number}
  37019. */
  37020. this.luminanceDecreaseRate = 0.5;
  37021. // Bright pass
  37022. /**
  37023. * Minimum luminance needed to compute HDR
  37024. * @type {number}
  37025. */
  37026. this.brightThreshold = 0.8;
  37027. this._needUpdate = true;
  37028. this._scene = scene;
  37029. // Bright pass
  37030. this._createBrightPassPostProcess(scene, ratio);
  37031. // Down sample X4
  37032. this._createDownSampleX4PostProcess(scene, ratio);
  37033. // Create gaussian blur post-processes
  37034. this._createGaussianBlurPostProcess(scene, ratio);
  37035. // Texture adder
  37036. this._createTextureAdderPostProcess(scene, ratio);
  37037. // Luminance generator
  37038. this._createLuminanceGeneratorPostProcess(scene);
  37039. // HDR
  37040. this._createHDRPostProcess(scene, ratio);
  37041. // Pass postprocess
  37042. if (originalPostProcess === null) {
  37043. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  37044. }
  37045. else {
  37046. this._originalPostProcess = originalPostProcess;
  37047. }
  37048. // Configure pipeline
  37049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  37050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  37051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  37052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  37053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  37054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  37055. var addDownSamplerPostProcess = function (id) {
  37056. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  37057. };
  37058. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37059. addDownSamplerPostProcess(i);
  37060. }
  37061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  37062. // Finish
  37063. scene.postProcessRenderPipelineManager.addPipeline(this);
  37064. if (cameras !== null) {
  37065. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37066. }
  37067. this.update();
  37068. }
  37069. /**
  37070. * Tells the pipeline to update its post-processes
  37071. */
  37072. HDRRenderingPipeline.prototype.update = function () {
  37073. this._needUpdate = true;
  37074. };
  37075. /**
  37076. * Returns the current calculated luminance
  37077. */
  37078. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  37079. return this._hdrCurrentLuminance;
  37080. };
  37081. /**
  37082. * Returns the currently drawn luminance
  37083. */
  37084. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  37085. return this._hdrOutputLuminance;
  37086. };
  37087. /**
  37088. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  37089. */
  37090. HDRRenderingPipeline.prototype.dispose = function () {
  37091. this._originalPostProcess = undefined;
  37092. this._brightPassPostProcess = undefined;
  37093. this._downSampleX4PostProcess = undefined;
  37094. this._guassianBlurHPostProcess = undefined;
  37095. this._guassianBlurVPostProcess = undefined;
  37096. this._textureAdderPostProcess = undefined;
  37097. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37098. this._downSamplePostProcesses[i] = undefined;
  37099. }
  37100. this._hdrPostProcess = undefined;
  37101. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37102. };
  37103. /**
  37104. * Creates the HDR post-process and computes the luminance adaptation
  37105. */
  37106. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  37107. var _this = this;
  37108. var hdrLastLuminance = 0.0;
  37109. this._hdrOutputLuminance = -1.0;
  37110. this._hdrCurrentLuminance = 1.0;
  37111. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  37112. this._hdrPostProcess.onApply = function (effect) {
  37113. if (_this._hdrOutputLuminance < 0.0) {
  37114. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37115. }
  37116. else {
  37117. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  37118. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  37119. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  37120. }
  37121. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  37122. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  37123. }
  37124. else {
  37125. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37126. }
  37127. }
  37128. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  37129. hdrLastLuminance += scene.getEngine().getDeltaTime();
  37130. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37131. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37132. effect.setFloat("exposure", _this.exposure);
  37133. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  37134. _this._needUpdate = false;
  37135. };
  37136. };
  37137. /**
  37138. * Texture Adder post-process
  37139. */
  37140. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  37141. var _this = this;
  37142. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  37143. this._textureAdderPostProcess.onApply = function (effect) {
  37144. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37145. };
  37146. };
  37147. /**
  37148. * Down sample X4 post-process
  37149. */
  37150. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37151. var _this = this;
  37152. var downSampleX4Offsets = new Array(32);
  37153. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37154. this._downSampleX4PostProcess.onApply = function (effect) {
  37155. if (_this._needUpdate) {
  37156. var id = 0;
  37157. for (var i = -2; i < 2; i++) {
  37158. for (var j = -2; j < 2; j++) {
  37159. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37160. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37161. id += 2;
  37162. }
  37163. }
  37164. }
  37165. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37166. };
  37167. };
  37168. /**
  37169. * Bright pass post-process
  37170. */
  37171. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37172. var _this = this;
  37173. var brightOffsets = new Array(8);
  37174. var brightPassCallback = function (effect) {
  37175. if (_this._needUpdate) {
  37176. var sU = (1.0 / _this._brightPassPostProcess.width);
  37177. var sV = (1.0 / _this._brightPassPostProcess.height);
  37178. brightOffsets[0] = -0.5 * sU;
  37179. brightOffsets[1] = 0.5 * sV;
  37180. brightOffsets[2] = 0.5 * sU;
  37181. brightOffsets[3] = 0.5 * sV;
  37182. brightOffsets[4] = -0.5 * sU;
  37183. brightOffsets[5] = -0.5 * sV;
  37184. brightOffsets[6] = 0.5 * sU;
  37185. brightOffsets[7] = -0.5 * sV;
  37186. }
  37187. effect.setArray2("dsOffsets", brightOffsets);
  37188. effect.setFloat("brightThreshold", _this.brightThreshold);
  37189. };
  37190. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37191. this._brightPassPostProcess.onApply = brightPassCallback;
  37192. };
  37193. /**
  37194. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37195. */
  37196. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37197. var _this = this;
  37198. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37199. var luminanceOffsets = new Array(8);
  37200. var downSampleOffsets = new Array(18);
  37201. var halfDestPixelSize;
  37202. this._downSamplePostProcesses = new Array(lumSteps);
  37203. // Utils for luminance
  37204. var luminanceUpdateSourceOffsets = function (width, height) {
  37205. var sU = (1.0 / width);
  37206. var sV = (1.0 / height);
  37207. luminanceOffsets[0] = -0.5 * sU;
  37208. luminanceOffsets[1] = 0.5 * sV;
  37209. luminanceOffsets[2] = 0.5 * sU;
  37210. luminanceOffsets[3] = 0.5 * sV;
  37211. luminanceOffsets[4] = -0.5 * sU;
  37212. luminanceOffsets[5] = -0.5 * sV;
  37213. luminanceOffsets[6] = 0.5 * sU;
  37214. luminanceOffsets[7] = -0.5 * sV;
  37215. };
  37216. var luminanceUpdateDestOffsets = function (width, height) {
  37217. var id = 0;
  37218. for (var x = -1; x < 2; x++) {
  37219. for (var y = -1; y < 2; y++) {
  37220. downSampleOffsets[id] = (x) / width;
  37221. downSampleOffsets[id + 1] = (y) / height;
  37222. id += 2;
  37223. }
  37224. }
  37225. };
  37226. // Luminance callback
  37227. var luminanceCallback = function (effect) {
  37228. if (_this._needUpdate) {
  37229. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37230. }
  37231. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37232. effect.setArray2("lumOffsets", luminanceOffsets);
  37233. };
  37234. // Down sample callbacks
  37235. var downSampleCallback = function (indice) {
  37236. var i = indice;
  37237. return function (effect) {
  37238. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37239. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37240. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37241. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37242. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37243. effect.setArray2("dsOffsets", downSampleOffsets);
  37244. };
  37245. };
  37246. var downSampleAfterRenderCallback = function (effect) {
  37247. // Unpack result
  37248. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37249. 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);
  37250. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37251. };
  37252. // Create luminance post-process
  37253. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37254. 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);
  37255. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37256. // Create down sample post-processes
  37257. for (var i = lumSteps - 2; i >= 0; i--) {
  37258. var length = Math.pow(3, i);
  37259. ratio = { width: length, height: length };
  37260. var defines = "#define DOWN_SAMPLE\n";
  37261. if (i === 0) {
  37262. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37263. }
  37264. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37265. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37266. if (i === 0) {
  37267. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37268. }
  37269. }
  37270. };
  37271. /**
  37272. * Gaussian blur post-processes. Horizontal and Vertical
  37273. */
  37274. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37275. var _this = this;
  37276. var blurOffsetsW = new Array(9);
  37277. var blurOffsetsH = new Array(9);
  37278. var blurWeights = new Array(9);
  37279. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37280. // Utils for gaussian blur
  37281. var calculateBlurOffsets = function (height) {
  37282. var lastOutputDimensions = {
  37283. width: scene.getEngine().getRenderWidth(),
  37284. height: scene.getEngine().getRenderHeight()
  37285. };
  37286. for (var i = 0; i < 9; i++) {
  37287. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37288. if (height) {
  37289. blurOffsetsH[i] = value;
  37290. }
  37291. else {
  37292. blurOffsetsW[i] = value;
  37293. }
  37294. }
  37295. };
  37296. var calculateWeights = function () {
  37297. var x = 0.0;
  37298. for (var i = 0; i < 9; i++) {
  37299. x = (i - 4.0) / 4.0;
  37300. 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));
  37301. }
  37302. };
  37303. // Callback
  37304. var gaussianBlurCallback = function (height) {
  37305. return function (effect) {
  37306. if (_this._needUpdate) {
  37307. calculateWeights();
  37308. calculateBlurOffsets(height);
  37309. }
  37310. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37311. effect.setArray("blurWeights", blurWeights);
  37312. effect.setFloat("multiplier", _this.gaussMultiplier);
  37313. };
  37314. };
  37315. // Create horizontal gaussian blur post-processes
  37316. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37317. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37318. // Create vertical gaussian blur post-process
  37319. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37320. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37321. };
  37322. // Luminance generator
  37323. HDRRenderingPipeline.LUM_STEPS = 6;
  37324. return HDRRenderingPipeline;
  37325. })(BABYLON.PostProcessRenderPipeline);
  37326. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37327. })(BABYLON || (BABYLON = {}));
  37328. var BABYLON;
  37329. (function (BABYLON) {
  37330. var FaceAdjacencies = (function () {
  37331. function FaceAdjacencies() {
  37332. this.edges = new Array();
  37333. this.edgesConnectedCount = 0;
  37334. }
  37335. return FaceAdjacencies;
  37336. })();
  37337. var EdgesRenderer = (function () {
  37338. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37339. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37340. if (epsilon === void 0) { epsilon = 0.95; }
  37341. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37342. this.edgesWidthScalerForOrthographic = 1000.0;
  37343. this.edgesWidthScalerForPerspective = 50.0;
  37344. this._linesPositions = new Array();
  37345. this._linesNormals = new Array();
  37346. this._linesIndices = new Array();
  37347. this._buffers = new Array();
  37348. this._checkVerticesInsteadOfIndices = false;
  37349. this._source = source;
  37350. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37351. this._epsilon = epsilon;
  37352. this._prepareRessources();
  37353. this._generateEdgesLines();
  37354. }
  37355. EdgesRenderer.prototype._prepareRessources = function () {
  37356. if (this._lineShader) {
  37357. return;
  37358. }
  37359. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37360. attributes: ["position", "normal"],
  37361. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37362. });
  37363. this._lineShader.disableDepthWrite = true;
  37364. this._lineShader.backFaceCulling = false;
  37365. };
  37366. EdgesRenderer.prototype.dispose = function () {
  37367. this._vb0.dispose();
  37368. this._vb1.dispose();
  37369. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37370. this._lineShader.dispose();
  37371. };
  37372. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37373. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37374. return 0;
  37375. }
  37376. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37377. return 1;
  37378. }
  37379. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37380. return 2;
  37381. }
  37382. return -1;
  37383. };
  37384. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37385. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37386. return 0;
  37387. }
  37388. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37389. return 1;
  37390. }
  37391. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37392. return 2;
  37393. }
  37394. return -1;
  37395. };
  37396. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37397. var needToCreateLine;
  37398. if (edge === undefined) {
  37399. needToCreateLine = true;
  37400. }
  37401. else {
  37402. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37403. needToCreateLine = dotProduct < this._epsilon;
  37404. }
  37405. if (needToCreateLine) {
  37406. var offset = this._linesPositions.length / 3;
  37407. var normal = p0.subtract(p1);
  37408. normal.normalize();
  37409. // Positions
  37410. this._linesPositions.push(p0.x);
  37411. this._linesPositions.push(p0.y);
  37412. this._linesPositions.push(p0.z);
  37413. this._linesPositions.push(p0.x);
  37414. this._linesPositions.push(p0.y);
  37415. this._linesPositions.push(p0.z);
  37416. this._linesPositions.push(p1.x);
  37417. this._linesPositions.push(p1.y);
  37418. this._linesPositions.push(p1.z);
  37419. this._linesPositions.push(p1.x);
  37420. this._linesPositions.push(p1.y);
  37421. this._linesPositions.push(p1.z);
  37422. // Normals
  37423. this._linesNormals.push(p1.x);
  37424. this._linesNormals.push(p1.y);
  37425. this._linesNormals.push(p1.z);
  37426. this._linesNormals.push(-1);
  37427. this._linesNormals.push(p1.x);
  37428. this._linesNormals.push(p1.y);
  37429. this._linesNormals.push(p1.z);
  37430. this._linesNormals.push(1);
  37431. this._linesNormals.push(p0.x);
  37432. this._linesNormals.push(p0.y);
  37433. this._linesNormals.push(p0.z);
  37434. this._linesNormals.push(-1);
  37435. this._linesNormals.push(p0.x);
  37436. this._linesNormals.push(p0.y);
  37437. this._linesNormals.push(p0.z);
  37438. this._linesNormals.push(1);
  37439. // Indices
  37440. this._linesIndices.push(offset);
  37441. this._linesIndices.push(offset + 1);
  37442. this._linesIndices.push(offset + 2);
  37443. this._linesIndices.push(offset);
  37444. this._linesIndices.push(offset + 2);
  37445. this._linesIndices.push(offset + 3);
  37446. }
  37447. };
  37448. EdgesRenderer.prototype._generateEdgesLines = function () {
  37449. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37450. var indices = this._source.getIndices();
  37451. // First let's find adjacencies
  37452. var adjacencies = new Array();
  37453. var faceNormals = new Array();
  37454. var index;
  37455. var faceAdjacencies;
  37456. // Prepare faces
  37457. for (index = 0; index < indices.length; index += 3) {
  37458. faceAdjacencies = new FaceAdjacencies();
  37459. var p0Index = indices[index];
  37460. var p1Index = indices[index + 1];
  37461. var p2Index = indices[index + 2];
  37462. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37463. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37464. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37465. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37466. faceNormal.normalize();
  37467. faceNormals.push(faceNormal);
  37468. adjacencies.push(faceAdjacencies);
  37469. }
  37470. // Scan
  37471. for (index = 0; index < adjacencies.length; index++) {
  37472. faceAdjacencies = adjacencies[index];
  37473. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37474. var otherFaceAdjacencies = adjacencies[otherIndex];
  37475. if (faceAdjacencies.edgesConnectedCount === 3) {
  37476. break;
  37477. }
  37478. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37479. continue;
  37480. }
  37481. var otherP0 = indices[otherIndex * 3];
  37482. var otherP1 = indices[otherIndex * 3 + 1];
  37483. var otherP2 = indices[otherIndex * 3 + 2];
  37484. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37485. var otherEdgeIndex;
  37486. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37487. continue;
  37488. }
  37489. switch (edgeIndex) {
  37490. case 0:
  37491. if (this._checkVerticesInsteadOfIndices) {
  37492. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37493. }
  37494. else {
  37495. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37496. }
  37497. break;
  37498. case 1:
  37499. if (this._checkVerticesInsteadOfIndices) {
  37500. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37501. }
  37502. else {
  37503. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37504. }
  37505. break;
  37506. case 2:
  37507. if (this._checkVerticesInsteadOfIndices) {
  37508. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37509. }
  37510. else {
  37511. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37512. }
  37513. break;
  37514. }
  37515. if (otherEdgeIndex === -1) {
  37516. continue;
  37517. }
  37518. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37519. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37520. faceAdjacencies.edgesConnectedCount++;
  37521. otherFaceAdjacencies.edgesConnectedCount++;
  37522. if (faceAdjacencies.edgesConnectedCount === 3) {
  37523. break;
  37524. }
  37525. }
  37526. }
  37527. }
  37528. // Create lines
  37529. for (index = 0; index < adjacencies.length; index++) {
  37530. // 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
  37531. var current = adjacencies[index];
  37532. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37533. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37534. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37535. }
  37536. // Merge into a single mesh
  37537. var engine = this._source.getScene().getEngine();
  37538. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37539. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37540. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37541. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37542. this._ib = engine.createIndexBuffer(this._linesIndices);
  37543. this._indicesCount = this._linesIndices.length;
  37544. };
  37545. EdgesRenderer.prototype.render = function () {
  37546. if (!this._lineShader.isReady()) {
  37547. return;
  37548. }
  37549. var scene = this._source.getScene();
  37550. var engine = scene.getEngine();
  37551. this._lineShader._preBind();
  37552. // VBOs
  37553. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37554. scene.resetCachedMaterial();
  37555. this._lineShader.setColor4("color", this._source.edgesColor);
  37556. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37557. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37558. }
  37559. else {
  37560. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37561. }
  37562. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37563. this._lineShader.bind(this._source.getWorldMatrix());
  37564. // Draw order
  37565. engine.draw(true, 0, this._indicesCount);
  37566. this._lineShader.unbind();
  37567. engine.setDepthWrite(true);
  37568. };
  37569. return EdgesRenderer;
  37570. })();
  37571. BABYLON.EdgesRenderer = EdgesRenderer;
  37572. })(BABYLON || (BABYLON = {}));
  37573. var BABYLON;
  37574. (function (BABYLON) {
  37575. (function (TonemappingOperator) {
  37576. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37577. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37578. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37579. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37580. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37581. var TonemappingOperator = BABYLON.TonemappingOperator;
  37582. ;
  37583. var TonemapPostProcess = (function (_super) {
  37584. __extends(TonemapPostProcess, _super);
  37585. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37586. var _this = this;
  37587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37588. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37589. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37590. this._operator = _operator;
  37591. this.exposureAdjustment = exposureAdjustment;
  37592. var defines = "#define ";
  37593. if (this._operator === TonemappingOperator.Hable)
  37594. defines += "HABLE_TONEMAPPING";
  37595. else if (this._operator === TonemappingOperator.Reinhard)
  37596. defines += "REINHARD_TONEMAPPING";
  37597. else if (this._operator === TonemappingOperator.HejiDawson)
  37598. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37599. else if (this._operator === TonemappingOperator.Photographic)
  37600. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37601. //sadly a second call to create the effect.
  37602. this.updateEffect(defines);
  37603. this.onApply = function (effect) {
  37604. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37605. };
  37606. }
  37607. return TonemapPostProcess;
  37608. })(BABYLON.PostProcess);
  37609. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37610. })(BABYLON || (BABYLON = {}));
  37611. var BABYLON;
  37612. (function (BABYLON) {
  37613. var ReflectionProbe = (function () {
  37614. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37615. var _this = this;
  37616. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37617. this.name = name;
  37618. this._viewMatrix = BABYLON.Matrix.Identity();
  37619. this._target = BABYLON.Vector3.Zero();
  37620. this._add = BABYLON.Vector3.Zero();
  37621. this.position = BABYLON.Vector3.Zero();
  37622. this._scene = scene;
  37623. this._scene.reflectionProbes.push(this);
  37624. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37625. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37626. switch (faceIndex) {
  37627. case 0:
  37628. _this._add.copyFromFloats(1, 0, 0);
  37629. break;
  37630. case 1:
  37631. _this._add.copyFromFloats(-1, 0, 0);
  37632. break;
  37633. case 2:
  37634. _this._add.copyFromFloats(0, -1, 0);
  37635. break;
  37636. case 3:
  37637. _this._add.copyFromFloats(0, 1, 0);
  37638. break;
  37639. case 4:
  37640. _this._add.copyFromFloats(0, 0, 1);
  37641. break;
  37642. case 5:
  37643. _this._add.copyFromFloats(0, 0, -1);
  37644. break;
  37645. }
  37646. if (_this._attachedMesh) {
  37647. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37648. }
  37649. _this.position.addToRef(_this._add, _this._target);
  37650. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37651. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37652. };
  37653. this._renderTargetTexture.onAfterUnbind = function () {
  37654. scene.updateTransformMatrix(true);
  37655. };
  37656. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37657. }
  37658. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37659. get: function () {
  37660. return this._renderTargetTexture.refreshRate;
  37661. },
  37662. set: function (value) {
  37663. this._renderTargetTexture.refreshRate = value;
  37664. },
  37665. enumerable: true,
  37666. configurable: true
  37667. });
  37668. ReflectionProbe.prototype.getScene = function () {
  37669. return this._scene;
  37670. };
  37671. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37672. get: function () {
  37673. return this._renderTargetTexture;
  37674. },
  37675. enumerable: true,
  37676. configurable: true
  37677. });
  37678. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37679. get: function () {
  37680. return this._renderTargetTexture.renderList;
  37681. },
  37682. enumerable: true,
  37683. configurable: true
  37684. });
  37685. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37686. this._attachedMesh = mesh;
  37687. };
  37688. ReflectionProbe.prototype.dispose = function () {
  37689. var index = this._scene.reflectionProbes.indexOf(this);
  37690. if (index !== -1) {
  37691. // Remove from the scene if found
  37692. this._scene.reflectionProbes.splice(index, 1);
  37693. }
  37694. if (this._renderTargetTexture) {
  37695. this._renderTargetTexture.dispose();
  37696. this._renderTargetTexture = null;
  37697. }
  37698. };
  37699. return ReflectionProbe;
  37700. })();
  37701. BABYLON.ReflectionProbe = ReflectionProbe;
  37702. })(BABYLON || (BABYLON = {}));
  37703. var BABYLON;
  37704. (function (BABYLON) {
  37705. var SolidParticle = (function () {
  37706. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37707. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37708. this.position = BABYLON.Vector3.Zero(); // position
  37709. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37710. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37711. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37712. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37713. this.alive = true; // alive
  37714. this.idx = particleIndex;
  37715. this._pos = positionIndex;
  37716. this._model = model;
  37717. this.shapeId = shapeId;
  37718. this.idxInShape = idxInShape;
  37719. }
  37720. return SolidParticle;
  37721. })();
  37722. BABYLON.SolidParticle = SolidParticle;
  37723. var ModelShape = (function () {
  37724. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37725. this.shapeID = id;
  37726. this._shape = shape;
  37727. this._shapeUV = shapeUV;
  37728. this._positionFunction = posFunction;
  37729. this._vertexFunction = vtxFunction;
  37730. }
  37731. return ModelShape;
  37732. })();
  37733. BABYLON.ModelShape = ModelShape;
  37734. })(BABYLON || (BABYLON = {}));
  37735. var BABYLON;
  37736. (function (BABYLON) {
  37737. /**
  37738. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37739. */
  37740. var SolidParticleSystem = (function () {
  37741. /**
  37742. * Creates a SPS (Solid Particle System) object.
  37743. * @param name the SPS name, this will be the underlying mesh name
  37744. * @param scene the scene in which the SPS is added
  37745. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37746. */
  37747. function SolidParticleSystem(name, scene, options) {
  37748. // public members
  37749. /**
  37750. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37751. * Example : var p = SPS.particles[i];
  37752. */
  37753. this.particles = new Array();
  37754. /**
  37755. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37756. */
  37757. this.nbParticles = 0;
  37758. /**
  37759. * If the particles must ever face the camera (default false). Useful for planar particles.
  37760. */
  37761. this.billboard = false;
  37762. /**
  37763. * This a counter ofr your own usage. It's not set by any SPS functions.
  37764. */
  37765. this.counter = 0;
  37766. /**
  37767. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37768. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37769. */
  37770. this.vars = {};
  37771. this._positions = new Array();
  37772. this._indices = new Array();
  37773. this._normals = new Array();
  37774. this._colors = new Array();
  37775. this._uvs = new Array();
  37776. this._index = 0; // indices index
  37777. this._updatable = true;
  37778. this._pickable = false;
  37779. this._isVisibilityBoxLocked = false;
  37780. this._alwaysVisible = false;
  37781. this._shapeCounter = 0;
  37782. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37783. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37784. this._computeParticleColor = true;
  37785. this._computeParticleTexture = true;
  37786. this._computeParticleRotation = true;
  37787. this._computeParticleVertex = false;
  37788. this._computeBoundingBox = false;
  37789. this._cam_axisZ = BABYLON.Vector3.Zero();
  37790. this._cam_axisY = BABYLON.Vector3.Zero();
  37791. this._cam_axisX = BABYLON.Vector3.Zero();
  37792. this._axisX = BABYLON.Axis.X;
  37793. this._axisY = BABYLON.Axis.Y;
  37794. this._axisZ = BABYLON.Axis.Z;
  37795. this._fakeCamPos = BABYLON.Vector3.Zero();
  37796. this._rotMatrix = new BABYLON.Matrix();
  37797. this._invertMatrix = new BABYLON.Matrix();
  37798. this._rotated = BABYLON.Vector3.Zero();
  37799. this._quaternion = new BABYLON.Quaternion();
  37800. this._vertex = BABYLON.Vector3.Zero();
  37801. this._normal = BABYLON.Vector3.Zero();
  37802. this._yaw = 0.0;
  37803. this._pitch = 0.0;
  37804. this._roll = 0.0;
  37805. this._halfroll = 0.0;
  37806. this._halfpitch = 0.0;
  37807. this._halfyaw = 0.0;
  37808. this._sinRoll = 0.0;
  37809. this._cosRoll = 0.0;
  37810. this._sinPitch = 0.0;
  37811. this._cosPitch = 0.0;
  37812. this._sinYaw = 0.0;
  37813. this._cosYaw = 0.0;
  37814. this._w = 0.0;
  37815. this._minimum = BABYLON.Tmp.Vector3[0];
  37816. this._maximum = BABYLON.Tmp.Vector3[1];
  37817. this.name = name;
  37818. this._scene = scene;
  37819. this._camera = scene.activeCamera;
  37820. this._pickable = options ? options.isPickable : false;
  37821. if (options && options.updatable) {
  37822. this._updatable = options.updatable;
  37823. }
  37824. else {
  37825. this._updatable = true;
  37826. }
  37827. if (this._pickable) {
  37828. this.pickedParticles = [];
  37829. }
  37830. }
  37831. /**
  37832. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37833. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37834. */
  37835. SolidParticleSystem.prototype.buildMesh = function () {
  37836. if (this.nbParticles === 0) {
  37837. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37838. this.addShape(triangle, 1);
  37839. triangle.dispose();
  37840. }
  37841. this._positions32 = new Float32Array(this._positions);
  37842. this._uvs32 = new Float32Array(this._uvs);
  37843. this._colors32 = new Float32Array(this._colors);
  37844. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37845. this._normals32 = new Float32Array(this._normals);
  37846. this._fixedNormal32 = new Float32Array(this._normals);
  37847. var vertexData = new BABYLON.VertexData();
  37848. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37849. vertexData.indices = this._indices;
  37850. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37851. if (this._uvs32) {
  37852. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37853. ;
  37854. }
  37855. if (this._colors32) {
  37856. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37857. }
  37858. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37859. vertexData.applyToMesh(mesh, this._updatable);
  37860. this.mesh = mesh;
  37861. this.mesh.isPickable = this._pickable;
  37862. // free memory
  37863. this._positions = null;
  37864. this._normals = null;
  37865. this._uvs = null;
  37866. this._colors = null;
  37867. if (!this._updatable) {
  37868. this.particles.length = 0;
  37869. }
  37870. return mesh;
  37871. };
  37872. /**
  37873. * Digests the mesh and generates as many solid particles in the system as wanted.
  37874. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37875. * Thus the particles generated from digest() have their property "positiion" yet set.
  37876. * @param mesh the mesh to be digested
  37877. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37878. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37879. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37880. */
  37881. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37882. var size = (options && options.facetNb) || 1;
  37883. var number = (options && options.number);
  37884. var delta = (options && options.delta) || 0;
  37885. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37886. var meshInd = mesh.getIndices();
  37887. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37888. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37889. var f = 0; // facet counter
  37890. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37891. // compute size from number
  37892. if (number) {
  37893. number = (number > totalFacets) ? totalFacets : number;
  37894. size = Math.round(totalFacets / number);
  37895. delta = 0;
  37896. }
  37897. else {
  37898. size = (size > totalFacets) ? totalFacets : size;
  37899. }
  37900. var facetPos = []; // submesh positions
  37901. var facetInd = []; // submesh indices
  37902. var facetUV = []; // submesh UV
  37903. var facetCol = []; // submesh colors
  37904. var barycenter = BABYLON.Tmp.Vector3[0];
  37905. var rand;
  37906. var sizeO = size;
  37907. while (f < totalFacets) {
  37908. size = sizeO + Math.floor((1 + delta) * Math.random());
  37909. if (f > totalFacets - size) {
  37910. size = totalFacets - f;
  37911. }
  37912. // reset temp arrays
  37913. facetPos.length = 0;
  37914. facetInd.length = 0;
  37915. facetUV.length = 0;
  37916. facetCol.length = 0;
  37917. // iterate over "size" facets
  37918. var fi = 0;
  37919. for (var j = f * 3; j < (f + size) * 3; j++) {
  37920. facetInd.push(fi);
  37921. var i = meshInd[j];
  37922. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37923. if (meshUV) {
  37924. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37925. }
  37926. if (meshCol) {
  37927. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37928. }
  37929. fi++;
  37930. }
  37931. // create a model shape for each single particle
  37932. var idx = this.nbParticles;
  37933. var shape = this._posToShape(facetPos);
  37934. var shapeUV = this._uvsToShapeUV(facetUV);
  37935. // compute the barycenter of the shape
  37936. var v;
  37937. for (v = 0; v < shape.length; v++) {
  37938. barycenter.addInPlace(shape[v]);
  37939. }
  37940. barycenter.scaleInPlace(1 / shape.length);
  37941. // shift the shape from its barycenter to the origin
  37942. for (v = 0; v < shape.length; v++) {
  37943. shape[v].subtractInPlace(barycenter);
  37944. }
  37945. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37946. // add the particle in the SPS
  37947. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37948. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37949. // initialize the particle position
  37950. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37951. this._index += shape.length;
  37952. idx++;
  37953. this.nbParticles++;
  37954. this._shapeCounter++;
  37955. f += size;
  37956. }
  37957. };
  37958. //reset copy
  37959. SolidParticleSystem.prototype._resetCopy = function () {
  37960. this._copy.position.x = 0;
  37961. this._copy.position.y = 0;
  37962. this._copy.position.z = 0;
  37963. this._copy.rotation.x = 0;
  37964. this._copy.rotation.y = 0;
  37965. this._copy.rotation.z = 0;
  37966. this._copy.quaternion = null;
  37967. this._copy.scale.x = 1;
  37968. this._copy.scale.y = 1;
  37969. this._copy.scale.z = 1;
  37970. this._copy.uvs.x = 0;
  37971. this._copy.uvs.y = 0;
  37972. this._copy.uvs.z = 1;
  37973. this._copy.uvs.w = 1;
  37974. this._copy.color = null;
  37975. };
  37976. // _meshBuilder : inserts the shape model in the global SPS mesh
  37977. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37978. var i;
  37979. var u = 0;
  37980. var c = 0;
  37981. this._resetCopy();
  37982. if (options && options.positionFunction) {
  37983. options.positionFunction(this._copy, idx, idxInShape);
  37984. }
  37985. if (this._copy.quaternion) {
  37986. this._quaternion.x = this._copy.quaternion.x;
  37987. this._quaternion.y = this._copy.quaternion.y;
  37988. this._quaternion.z = this._copy.quaternion.z;
  37989. this._quaternion.w = this._copy.quaternion.w;
  37990. }
  37991. else {
  37992. this._yaw = this._copy.rotation.y;
  37993. this._pitch = this._copy.rotation.x;
  37994. this._roll = this._copy.rotation.z;
  37995. this._quaternionRotationYPR();
  37996. }
  37997. this._quaternionToRotationMatrix();
  37998. for (i = 0; i < shape.length; i++) {
  37999. this._vertex.x = shape[i].x;
  38000. this._vertex.y = shape[i].y;
  38001. this._vertex.z = shape[i].z;
  38002. if (options && options.vertexFunction) {
  38003. options.vertexFunction(this._copy, this._vertex, i);
  38004. }
  38005. this._vertex.x *= this._copy.scale.x;
  38006. this._vertex.y *= this._copy.scale.y;
  38007. this._vertex.z *= this._copy.scale.z;
  38008. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38009. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38010. if (meshUV) {
  38011. 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);
  38012. u += 2;
  38013. }
  38014. if (this._copy.color) {
  38015. this._color = this._copy.color;
  38016. }
  38017. else if (meshCol && meshCol[c]) {
  38018. this._color.r = meshCol[c];
  38019. this._color.g = meshCol[c + 1];
  38020. this._color.b = meshCol[c + 2];
  38021. this._color.a = meshCol[c + 3];
  38022. }
  38023. else {
  38024. this._color.r = 1;
  38025. this._color.g = 1;
  38026. this._color.b = 1;
  38027. this._color.a = 1;
  38028. }
  38029. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38030. c += 4;
  38031. }
  38032. for (i = 0; i < meshInd.length; i++) {
  38033. indices.push(p + meshInd[i]);
  38034. }
  38035. if (this._pickable) {
  38036. var nbfaces = meshInd.length / 3;
  38037. for (i = 0; i < nbfaces; i++) {
  38038. this.pickedParticles.push({ idx: idx, faceId: i });
  38039. }
  38040. }
  38041. };
  38042. // returns a shape array from positions array
  38043. SolidParticleSystem.prototype._posToShape = function (positions) {
  38044. var shape = [];
  38045. for (var i = 0; i < positions.length; i += 3) {
  38046. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38047. }
  38048. return shape;
  38049. };
  38050. // returns a shapeUV array from a Vector4 uvs
  38051. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38052. var shapeUV = [];
  38053. if (uvs) {
  38054. for (var i = 0; i < uvs.length; i++)
  38055. shapeUV.push(uvs[i]);
  38056. }
  38057. return shapeUV;
  38058. };
  38059. // adds a new particle object in the particles array
  38060. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  38061. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  38062. };
  38063. /**
  38064. * Adds some particles to the SPS from the model shape.
  38065. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  38066. * @param mesh any Mesh object that will be used as a model for the solid particles.
  38067. * @param nb the number of particles to be created from this model
  38068. * @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
  38069. */
  38070. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38071. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38072. var meshInd = mesh.getIndices();
  38073. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38074. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38075. var shape = this._posToShape(meshPos);
  38076. var shapeUV = this._uvsToShapeUV(meshUV);
  38077. var posfunc = options ? options.positionFunction : null;
  38078. var vtxfunc = options ? options.vertexFunction : null;
  38079. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38080. // particles
  38081. var idx = this.nbParticles;
  38082. for (var i = 0; i < nb; i++) {
  38083. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  38084. if (this._updatable) {
  38085. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  38086. }
  38087. this._index += shape.length;
  38088. idx++;
  38089. }
  38090. this.nbParticles += nb;
  38091. this._shapeCounter++;
  38092. return this._shapeCounter - 1;
  38093. };
  38094. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38095. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38096. this._resetCopy();
  38097. if (particle._model._positionFunction) {
  38098. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38099. }
  38100. if (this._copy.quaternion) {
  38101. this._quaternion.x = this._copy.quaternion.x;
  38102. this._quaternion.y = this._copy.quaternion.y;
  38103. this._quaternion.z = this._copy.quaternion.z;
  38104. this._quaternion.w = this._copy.quaternion.w;
  38105. }
  38106. else {
  38107. this._yaw = this._copy.rotation.y;
  38108. this._pitch = this._copy.rotation.x;
  38109. this._roll = this._copy.rotation.z;
  38110. this._quaternionRotationYPR();
  38111. }
  38112. this._quaternionToRotationMatrix();
  38113. this._shape = particle._model._shape;
  38114. for (var pt = 0; pt < this._shape.length; pt++) {
  38115. this._vertex.x = this._shape[pt].x;
  38116. this._vertex.y = this._shape[pt].y;
  38117. this._vertex.z = this._shape[pt].z;
  38118. if (particle._model._vertexFunction) {
  38119. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38120. }
  38121. this._vertex.x *= this._copy.scale.x;
  38122. this._vertex.y *= this._copy.scale.y;
  38123. this._vertex.z *= this._copy.scale.z;
  38124. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38125. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38126. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38127. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38128. }
  38129. particle.position.x = 0;
  38130. particle.position.y = 0;
  38131. particle.position.z = 0;
  38132. particle.rotation.x = 0;
  38133. particle.rotation.y = 0;
  38134. particle.rotation.z = 0;
  38135. particle.quaternion = null;
  38136. particle.scale.x = 1;
  38137. particle.scale.y = 1;
  38138. particle.scale.z = 1;
  38139. };
  38140. /**
  38141. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38142. */
  38143. SolidParticleSystem.prototype.rebuildMesh = function () {
  38144. for (var p = 0; p < this.particles.length; p++) {
  38145. this._rebuildParticle(this.particles[p]);
  38146. }
  38147. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38148. };
  38149. /**
  38150. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38151. * This method calls updateParticle() for each particles of the SPS.
  38152. * For an animated SPS, it is usually called within the render loop.
  38153. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38154. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38155. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38156. */
  38157. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38158. if (start === void 0) { start = 0; }
  38159. if (end === void 0) { end = this.nbParticles - 1; }
  38160. if (update === void 0) { update = true; }
  38161. if (!this._updatable) {
  38162. return;
  38163. }
  38164. // custom beforeUpdate
  38165. this.beforeUpdateParticles(start, end, update);
  38166. this._cam_axisX.x = 1;
  38167. this._cam_axisX.y = 0;
  38168. this._cam_axisX.z = 0;
  38169. this._cam_axisY.x = 0;
  38170. this._cam_axisY.y = 1;
  38171. this._cam_axisY.z = 0;
  38172. this._cam_axisZ.x = 0;
  38173. this._cam_axisZ.y = 0;
  38174. this._cam_axisZ.z = 1;
  38175. // if the particles will always face the camera
  38176. if (this.billboard) {
  38177. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38178. this._yaw = this.mesh.rotation.y;
  38179. this._pitch = this.mesh.rotation.x;
  38180. this._roll = this.mesh.rotation.z;
  38181. this._quaternionRotationYPR();
  38182. this._quaternionToRotationMatrix();
  38183. this._rotMatrix.invertToRef(this._invertMatrix);
  38184. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38185. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38186. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38187. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38188. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38189. this._cam_axisY.normalize();
  38190. this._cam_axisX.normalize();
  38191. this._cam_axisZ.normalize();
  38192. }
  38193. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38194. var idx = 0;
  38195. var index = 0;
  38196. var colidx = 0;
  38197. var colorIndex = 0;
  38198. var uvidx = 0;
  38199. var uvIndex = 0;
  38200. if (this._computeBoundingBox) {
  38201. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38202. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38203. }
  38204. // particle loop
  38205. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38206. for (var p = start; p <= end; p++) {
  38207. this._particle = this.particles[p];
  38208. this._shape = this._particle._model._shape;
  38209. this._shapeUV = this._particle._model._shapeUV;
  38210. // call to custom user function to update the particle properties
  38211. this.updateParticle(this._particle);
  38212. // particle rotation matrix
  38213. if (this.billboard) {
  38214. this._particle.rotation.x = 0.0;
  38215. this._particle.rotation.y = 0.0;
  38216. }
  38217. if (this._computeParticleRotation) {
  38218. if (this._particle.quaternion) {
  38219. this._quaternion.x = this._particle.quaternion.x;
  38220. this._quaternion.y = this._particle.quaternion.y;
  38221. this._quaternion.z = this._particle.quaternion.z;
  38222. this._quaternion.w = this._particle.quaternion.w;
  38223. }
  38224. else {
  38225. this._yaw = this._particle.rotation.y;
  38226. this._pitch = this._particle.rotation.x;
  38227. this._roll = this._particle.rotation.z;
  38228. this._quaternionRotationYPR();
  38229. }
  38230. this._quaternionToRotationMatrix();
  38231. }
  38232. for (var pt = 0; pt < this._shape.length; pt++) {
  38233. idx = index + pt * 3;
  38234. colidx = colorIndex + pt * 4;
  38235. uvidx = uvIndex + pt * 2;
  38236. this._vertex.x = this._shape[pt].x;
  38237. this._vertex.y = this._shape[pt].y;
  38238. this._vertex.z = this._shape[pt].z;
  38239. if (this._computeParticleVertex) {
  38240. this.updateParticleVertex(this._particle, this._vertex, pt);
  38241. }
  38242. // positions
  38243. this._vertex.x *= this._particle.scale.x;
  38244. this._vertex.y *= this._particle.scale.y;
  38245. this._vertex.z *= this._particle.scale.z;
  38246. 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];
  38247. 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;
  38248. 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;
  38249. 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;
  38250. 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;
  38251. 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;
  38252. 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;
  38253. if (this._computeBoundingBox) {
  38254. if (this._positions32[idx] < this._minimum.x) {
  38255. this._minimum.x = this._positions32[idx];
  38256. }
  38257. if (this._positions32[idx] > this._maximum.x) {
  38258. this._maximum.x = this._positions32[idx];
  38259. }
  38260. if (this._positions32[idx + 1] < this._minimum.y) {
  38261. this._minimum.y = this._positions32[idx + 1];
  38262. }
  38263. if (this._positions32[idx + 1] > this._maximum.y) {
  38264. this._maximum.y = this._positions32[idx + 1];
  38265. }
  38266. if (this._positions32[idx + 2] < this._minimum.z) {
  38267. this._minimum.z = this._positions32[idx + 2];
  38268. }
  38269. if (this._positions32[idx + 2] > this._maximum.z) {
  38270. this._maximum.z = this._positions32[idx + 2];
  38271. }
  38272. }
  38273. // normals : if the particles can't be morphed then just rotate the normals
  38274. if (!this._computeParticleVertex && !this.billboard) {
  38275. this._normal.x = this._fixedNormal32[idx];
  38276. this._normal.y = this._fixedNormal32[idx + 1];
  38277. this._normal.z = this._fixedNormal32[idx + 2];
  38278. 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];
  38279. 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;
  38280. 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;
  38281. 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;
  38282. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38283. 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;
  38284. 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;
  38285. }
  38286. if (this._computeParticleColor) {
  38287. this._colors32[colidx] = this._particle.color.r;
  38288. this._colors32[colidx + 1] = this._particle.color.g;
  38289. this._colors32[colidx + 2] = this._particle.color.b;
  38290. this._colors32[colidx + 3] = this._particle.color.a;
  38291. }
  38292. if (this._computeParticleTexture) {
  38293. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38294. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38295. }
  38296. }
  38297. index = idx + 3;
  38298. colorIndex = colidx + 4;
  38299. uvIndex = uvidx + 2;
  38300. }
  38301. if (update) {
  38302. if (this._computeParticleColor) {
  38303. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38304. }
  38305. if (this._computeParticleTexture) {
  38306. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38307. }
  38308. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38309. if (!this.mesh.areNormalsFrozen) {
  38310. if (this._computeParticleVertex || this.billboard) {
  38311. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38312. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38313. for (var i = 0; i < this._normals32.length; i++) {
  38314. this._fixedNormal32[i] = this._normals32[i];
  38315. }
  38316. }
  38317. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38318. }
  38319. }
  38320. if (this._computeBoundingBox) {
  38321. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38322. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38323. }
  38324. this.afterUpdateParticles(start, end, update);
  38325. };
  38326. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38327. this._halfroll = this._roll * 0.5;
  38328. this._halfpitch = this._pitch * 0.5;
  38329. this._halfyaw = this._yaw * 0.5;
  38330. this._sinRoll = Math.sin(this._halfroll);
  38331. this._cosRoll = Math.cos(this._halfroll);
  38332. this._sinPitch = Math.sin(this._halfpitch);
  38333. this._cosPitch = Math.cos(this._halfpitch);
  38334. this._sinYaw = Math.sin(this._halfyaw);
  38335. this._cosYaw = Math.cos(this._halfyaw);
  38336. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38337. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38338. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38339. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38340. };
  38341. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38342. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38343. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38344. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38345. this._rotMatrix.m[3] = 0;
  38346. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38347. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38348. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38349. this._rotMatrix.m[7] = 0;
  38350. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38351. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38352. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38353. this._rotMatrix.m[11] = 0;
  38354. this._rotMatrix.m[12] = 0;
  38355. this._rotMatrix.m[13] = 0;
  38356. this._rotMatrix.m[14] = 0;
  38357. this._rotMatrix.m[15] = 1.0;
  38358. };
  38359. /**
  38360. * Disposes the SPS
  38361. */
  38362. SolidParticleSystem.prototype.dispose = function () {
  38363. this.mesh.dispose();
  38364. this.vars = null;
  38365. // drop references to internal big arrays for the GC
  38366. this._positions = null;
  38367. this._indices = null;
  38368. this._normals = null;
  38369. this._uvs = null;
  38370. this._colors = null;
  38371. this._positions32 = null;
  38372. this._normals32 = null;
  38373. this._fixedNormal32 = null;
  38374. this._uvs32 = null;
  38375. this._colors32 = null;
  38376. this.pickedParticles = null;
  38377. };
  38378. /**
  38379. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38380. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38381. */
  38382. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38383. if (!this._isVisibilityBoxLocked) {
  38384. this.mesh.refreshBoundingInfo();
  38385. }
  38386. };
  38387. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38388. * @param size the size (float) of the visibility box
  38389. * note : this doesn't lock the SPS mesh bounding box.
  38390. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38391. */
  38392. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38393. var vis = size / 2;
  38394. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38395. };
  38396. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38397. // getter and setter
  38398. /**
  38399. * True if the SPS is set as always visible
  38400. */
  38401. get: function () {
  38402. return this._alwaysVisible;
  38403. },
  38404. /**
  38405. * Sets the SPS as always visible or not
  38406. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38407. */
  38408. set: function (val) {
  38409. this._alwaysVisible = val;
  38410. this.mesh.alwaysSelectAsActiveMesh = val;
  38411. },
  38412. enumerable: true,
  38413. configurable: true
  38414. });
  38415. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38416. /**
  38417. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38418. */
  38419. get: function () {
  38420. return this._isVisibilityBoxLocked;
  38421. },
  38422. /**
  38423. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38424. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38425. */
  38426. set: function (val) {
  38427. this._isVisibilityBoxLocked = val;
  38428. this.mesh.getBoundingInfo().isLocked = val;
  38429. },
  38430. enumerable: true,
  38431. configurable: true
  38432. });
  38433. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38434. // getters
  38435. get: function () {
  38436. return this._computeParticleRotation;
  38437. },
  38438. // Optimizer setters
  38439. /**
  38440. * Tells to setParticles() to compute the particle rotations or not.
  38441. * Default value : true. The SPS is faster when it's set to false.
  38442. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38443. */
  38444. set: function (val) {
  38445. this._computeParticleRotation = val;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38451. get: function () {
  38452. return this._computeParticleColor;
  38453. },
  38454. /**
  38455. * Tells to setParticles() to compute the particle colors or not.
  38456. * Default value : true. The SPS is faster when it's set to false.
  38457. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38458. */
  38459. set: function (val) {
  38460. this._computeParticleColor = val;
  38461. },
  38462. enumerable: true,
  38463. configurable: true
  38464. });
  38465. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38466. get: function () {
  38467. return this._computeParticleTexture;
  38468. },
  38469. /**
  38470. * Tells to setParticles() to compute the particle textures or not.
  38471. * Default value : true. The SPS is faster when it's set to false.
  38472. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38473. */
  38474. set: function (val) {
  38475. this._computeParticleTexture = val;
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38481. get: function () {
  38482. return this._computeParticleVertex;
  38483. },
  38484. /**
  38485. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38486. * Default value : false. The SPS is faster when it's set to false.
  38487. * Note : the particle custom vertex positions aren't stored values.
  38488. */
  38489. set: function (val) {
  38490. this._computeParticleVertex = val;
  38491. },
  38492. enumerable: true,
  38493. configurable: true
  38494. });
  38495. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38496. get: function () {
  38497. return this._computeBoundingBox;
  38498. },
  38499. /**
  38500. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38501. */
  38502. set: function (val) {
  38503. this._computeBoundingBox = val;
  38504. },
  38505. enumerable: true,
  38506. configurable: true
  38507. });
  38508. // =======================================================================
  38509. // Particle behavior logic
  38510. // these following methods may be overwritten by the user to fit his needs
  38511. /**
  38512. * This function does nothing. It may be overwritten to set all the particles first values.
  38513. * The SPS doesn't call this function, you may have to call it by your own.
  38514. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38515. */
  38516. SolidParticleSystem.prototype.initParticles = function () {
  38517. };
  38518. /**
  38519. * This function does nothing. It may be overwritten to recycle a particle.
  38520. * The SPS doesn't call this function, you may have to call it by your own.
  38521. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38522. */
  38523. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38524. return particle;
  38525. };
  38526. /**
  38527. * Updates a particle : this function should be overwritten by the user.
  38528. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38529. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38530. * ex : just set a particle position or velocity and recycle conditions
  38531. */
  38532. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38533. return particle;
  38534. };
  38535. /**
  38536. * Updates a vertex of a particle : it can be overwritten by the user.
  38537. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38538. * @param particle the current particle
  38539. * @param vertex the current index of the current particle
  38540. * @param pt the index of the current vertex in the particle shape
  38541. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38542. * ex : just set a vertex particle position
  38543. */
  38544. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38545. return vertex;
  38546. };
  38547. /**
  38548. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38549. * This does nothing and may be overwritten by the user.
  38550. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38551. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38552. * @param update the boolean update value actually passed to setParticles()
  38553. */
  38554. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38555. };
  38556. /**
  38557. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38558. * This will be passed three parameters.
  38559. * This does nothing and may be overwritten by the user.
  38560. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38561. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38562. * @param update the boolean update value actually passed to setParticles()
  38563. */
  38564. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38565. };
  38566. return SolidParticleSystem;
  38567. })();
  38568. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38569. })(BABYLON || (BABYLON = {}));
  38570. var BABYLON;
  38571. (function (BABYLON) {
  38572. // We're mainly based on the logic defined into the FreeCamera code
  38573. var UniversalCamera = (function (_super) {
  38574. __extends(UniversalCamera, _super);
  38575. function UniversalCamera(name, position, scene) {
  38576. var _this = this;
  38577. _super.call(this, name, position, scene);
  38578. this.gamepadAngularSensibility = 200;
  38579. this.gamepadMoveSensibility = 40;
  38580. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38581. }
  38582. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38583. // Only the first gamepad can control the camera
  38584. if (gamepad.index === 0) {
  38585. this.gamepad = gamepad;
  38586. }
  38587. };
  38588. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38589. _super.prototype.attachControl.call(this, canvas, false);
  38590. };
  38591. UniversalCamera.prototype.detachControl = function (canvas) {
  38592. _super.prototype.detachControl.call(this, canvas);
  38593. };
  38594. UniversalCamera.prototype._checkInputs = function () {
  38595. if (this.gamepad) {
  38596. var LSValues = this.gamepad.leftStick;
  38597. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38598. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38599. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38600. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38601. var RSValues = this.gamepad.rightStick;
  38602. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38603. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38604. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38605. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38606. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38607. var speed = this._computeLocalCameraSpeed() * 50.0;
  38608. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38609. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38610. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38611. }
  38612. _super.prototype._checkInputs.call(this);
  38613. };
  38614. UniversalCamera.prototype.dispose = function () {
  38615. this._gamepads.dispose();
  38616. _super.prototype.dispose.call(this);
  38617. };
  38618. UniversalCamera.prototype.getTypeName = function () {
  38619. return "UniversalCamera";
  38620. };
  38621. __decorate([
  38622. BABYLON.serialize()
  38623. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38624. __decorate([
  38625. BABYLON.serialize()
  38626. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38627. return UniversalCamera;
  38628. })(BABYLON.TouchCamera);
  38629. BABYLON.UniversalCamera = UniversalCamera;
  38630. })(BABYLON || (BABYLON = {}));
  38631. var BABYLON;
  38632. (function (BABYLON) {
  38633. var Gamepads = (function () {
  38634. function Gamepads(ongamedpadconnected) {
  38635. var _this = this;
  38636. this.babylonGamepads = [];
  38637. this.oneGamepadConnected = false;
  38638. this.isMonitoring = false;
  38639. this.gamepadEventSupported = 'GamepadEvent' in window;
  38640. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38641. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38642. this._callbackGamepadConnected = ongamedpadconnected;
  38643. if (this.gamepadSupportAvailable) {
  38644. // Checking if the gamepad connected event is supported (like in Firefox)
  38645. if (this.gamepadEventSupported) {
  38646. window.addEventListener('gamepadconnected', function (evt) {
  38647. _this._onGamepadConnected(evt);
  38648. }, false);
  38649. window.addEventListener('gamepaddisconnected', function (evt) {
  38650. _this._onGamepadDisconnected(evt);
  38651. }, false);
  38652. }
  38653. else {
  38654. this._startMonitoringGamepads();
  38655. }
  38656. }
  38657. }
  38658. Gamepads.prototype.dispose = function () {
  38659. if (Gamepads.gamepadDOMInfo) {
  38660. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38661. }
  38662. };
  38663. Gamepads.prototype._onGamepadConnected = function (evt) {
  38664. var newGamepad = this._addNewGamepad(evt.gamepad);
  38665. if (this._callbackGamepadConnected)
  38666. this._callbackGamepadConnected(newGamepad);
  38667. this._startMonitoringGamepads();
  38668. };
  38669. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38670. if (!this.oneGamepadConnected) {
  38671. this.oneGamepadConnected = true;
  38672. if (Gamepads.gamepadDOMInfo) {
  38673. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38674. Gamepads.gamepadDOMInfo = null;
  38675. }
  38676. }
  38677. var newGamepad;
  38678. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38679. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38680. }
  38681. else {
  38682. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38683. }
  38684. this.babylonGamepads.push(newGamepad);
  38685. return newGamepad;
  38686. };
  38687. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38688. // Remove the gamepad from the list of gamepads to monitor.
  38689. for (var i in this.babylonGamepads) {
  38690. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38691. this.babylonGamepads.splice(+i, 1);
  38692. break;
  38693. }
  38694. }
  38695. // If no gamepads are left, stop the polling loop.
  38696. if (this.babylonGamepads.length == 0) {
  38697. this._stopMonitoringGamepads();
  38698. }
  38699. };
  38700. Gamepads.prototype._startMonitoringGamepads = function () {
  38701. if (!this.isMonitoring) {
  38702. this.isMonitoring = true;
  38703. this._checkGamepadsStatus();
  38704. }
  38705. };
  38706. Gamepads.prototype._stopMonitoringGamepads = function () {
  38707. this.isMonitoring = false;
  38708. };
  38709. Gamepads.prototype._checkGamepadsStatus = function () {
  38710. var _this = this;
  38711. // updating gamepad objects
  38712. this._updateGamepadObjects();
  38713. for (var i in this.babylonGamepads) {
  38714. this.babylonGamepads[i].update();
  38715. }
  38716. if (this.isMonitoring) {
  38717. if (window.requestAnimationFrame) {
  38718. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38719. }
  38720. else if (window.mozRequestAnimationFrame) {
  38721. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38722. }
  38723. else if (window.webkitRequestAnimationFrame) {
  38724. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38725. }
  38726. }
  38727. };
  38728. // This function is called only on Chrome, which does not yet support
  38729. // connection/disconnection events, but requires you to monitor
  38730. // an array for changes.
  38731. Gamepads.prototype._updateGamepadObjects = function () {
  38732. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38733. for (var i = 0; i < gamepads.length; i++) {
  38734. if (gamepads[i]) {
  38735. if (!(gamepads[i].index in this.babylonGamepads)) {
  38736. var newGamepad = this._addNewGamepad(gamepads[i]);
  38737. if (this._callbackGamepadConnected) {
  38738. this._callbackGamepadConnected(newGamepad);
  38739. }
  38740. }
  38741. else {
  38742. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38743. }
  38744. }
  38745. }
  38746. };
  38747. return Gamepads;
  38748. })();
  38749. BABYLON.Gamepads = Gamepads;
  38750. var StickValues = (function () {
  38751. function StickValues(x, y) {
  38752. this.x = x;
  38753. this.y = y;
  38754. }
  38755. return StickValues;
  38756. })();
  38757. BABYLON.StickValues = StickValues;
  38758. var Gamepad = (function () {
  38759. function Gamepad(id, index, browserGamepad) {
  38760. this.id = id;
  38761. this.index = index;
  38762. this.browserGamepad = browserGamepad;
  38763. if (this.browserGamepad.axes.length >= 2) {
  38764. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38765. }
  38766. if (this.browserGamepad.axes.length >= 4) {
  38767. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38768. }
  38769. }
  38770. Gamepad.prototype.onleftstickchanged = function (callback) {
  38771. this._onleftstickchanged = callback;
  38772. };
  38773. Gamepad.prototype.onrightstickchanged = function (callback) {
  38774. this._onrightstickchanged = callback;
  38775. };
  38776. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38777. get: function () {
  38778. return this._leftStick;
  38779. },
  38780. set: function (newValues) {
  38781. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38782. this._onleftstickchanged(newValues);
  38783. }
  38784. this._leftStick = newValues;
  38785. },
  38786. enumerable: true,
  38787. configurable: true
  38788. });
  38789. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38790. get: function () {
  38791. return this._rightStick;
  38792. },
  38793. set: function (newValues) {
  38794. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38795. this._onrightstickchanged(newValues);
  38796. }
  38797. this._rightStick = newValues;
  38798. },
  38799. enumerable: true,
  38800. configurable: true
  38801. });
  38802. Gamepad.prototype.update = function () {
  38803. if (this._leftStick) {
  38804. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38805. }
  38806. if (this._rightStick) {
  38807. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38808. }
  38809. };
  38810. return Gamepad;
  38811. })();
  38812. BABYLON.Gamepad = Gamepad;
  38813. var GenericPad = (function (_super) {
  38814. __extends(GenericPad, _super);
  38815. function GenericPad(id, index, gamepad) {
  38816. _super.call(this, id, index, gamepad);
  38817. this.id = id;
  38818. this.index = index;
  38819. this.gamepad = gamepad;
  38820. this._buttons = new Array(gamepad.buttons.length);
  38821. }
  38822. GenericPad.prototype.onbuttondown = function (callback) {
  38823. this._onbuttondown = callback;
  38824. };
  38825. GenericPad.prototype.onbuttonup = function (callback) {
  38826. this._onbuttonup = callback;
  38827. };
  38828. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38829. if (newValue !== currentValue) {
  38830. if (this._onbuttondown && newValue === 1) {
  38831. this._onbuttondown(buttonIndex);
  38832. }
  38833. if (this._onbuttonup && newValue === 0) {
  38834. this._onbuttonup(buttonIndex);
  38835. }
  38836. }
  38837. return newValue;
  38838. };
  38839. GenericPad.prototype.update = function () {
  38840. _super.prototype.update.call(this);
  38841. for (var index = 0; index < this._buttons.length; index++) {
  38842. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38843. }
  38844. };
  38845. return GenericPad;
  38846. })(Gamepad);
  38847. BABYLON.GenericPad = GenericPad;
  38848. (function (Xbox360Button) {
  38849. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38850. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38851. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38852. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38853. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38854. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38855. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38856. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38857. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38858. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38859. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38860. var Xbox360Button = BABYLON.Xbox360Button;
  38861. (function (Xbox360Dpad) {
  38862. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38863. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38864. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38865. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38866. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38867. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38868. var Xbox360Pad = (function (_super) {
  38869. __extends(Xbox360Pad, _super);
  38870. function Xbox360Pad() {
  38871. _super.apply(this, arguments);
  38872. this._leftTrigger = 0;
  38873. this._rightTrigger = 0;
  38874. this._buttonA = 0;
  38875. this._buttonB = 0;
  38876. this._buttonX = 0;
  38877. this._buttonY = 0;
  38878. this._buttonBack = 0;
  38879. this._buttonStart = 0;
  38880. this._buttonLB = 0;
  38881. this._buttonRB = 0;
  38882. this._buttonLeftStick = 0;
  38883. this._buttonRightStick = 0;
  38884. this._dPadUp = 0;
  38885. this._dPadDown = 0;
  38886. this._dPadLeft = 0;
  38887. this._dPadRight = 0;
  38888. }
  38889. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38890. this._onlefttriggerchanged = callback;
  38891. };
  38892. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38893. this._onrighttriggerchanged = callback;
  38894. };
  38895. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38896. get: function () {
  38897. return this._leftTrigger;
  38898. },
  38899. set: function (newValue) {
  38900. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38901. this._onlefttriggerchanged(newValue);
  38902. }
  38903. this._leftTrigger = newValue;
  38904. },
  38905. enumerable: true,
  38906. configurable: true
  38907. });
  38908. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38909. get: function () {
  38910. return this._rightTrigger;
  38911. },
  38912. set: function (newValue) {
  38913. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38914. this._onrighttriggerchanged(newValue);
  38915. }
  38916. this._rightTrigger = newValue;
  38917. },
  38918. enumerable: true,
  38919. configurable: true
  38920. });
  38921. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38922. this._onbuttondown = callback;
  38923. };
  38924. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38925. this._onbuttonup = callback;
  38926. };
  38927. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38928. this._ondpaddown = callback;
  38929. };
  38930. Xbox360Pad.prototype.ondpadup = function (callback) {
  38931. this._ondpadup = callback;
  38932. };
  38933. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38934. if (newValue !== currentValue) {
  38935. if (this._onbuttondown && newValue === 1) {
  38936. this._onbuttondown(buttonType);
  38937. }
  38938. if (this._onbuttonup && newValue === 0) {
  38939. this._onbuttonup(buttonType);
  38940. }
  38941. }
  38942. return newValue;
  38943. };
  38944. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38945. if (newValue !== currentValue) {
  38946. if (this._ondpaddown && newValue === 1) {
  38947. this._ondpaddown(buttonType);
  38948. }
  38949. if (this._ondpadup && newValue === 0) {
  38950. this._ondpadup(buttonType);
  38951. }
  38952. }
  38953. return newValue;
  38954. };
  38955. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38956. get: function () {
  38957. return this._buttonA;
  38958. },
  38959. set: function (value) {
  38960. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38966. get: function () {
  38967. return this._buttonB;
  38968. },
  38969. set: function (value) {
  38970. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38971. },
  38972. enumerable: true,
  38973. configurable: true
  38974. });
  38975. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38976. get: function () {
  38977. return this._buttonX;
  38978. },
  38979. set: function (value) {
  38980. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38981. },
  38982. enumerable: true,
  38983. configurable: true
  38984. });
  38985. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38986. get: function () {
  38987. return this._buttonY;
  38988. },
  38989. set: function (value) {
  38990. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38991. },
  38992. enumerable: true,
  38993. configurable: true
  38994. });
  38995. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38996. get: function () {
  38997. return this._buttonStart;
  38998. },
  38999. set: function (value) {
  39000. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39001. },
  39002. enumerable: true,
  39003. configurable: true
  39004. });
  39005. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39006. get: function () {
  39007. return this._buttonBack;
  39008. },
  39009. set: function (value) {
  39010. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39011. },
  39012. enumerable: true,
  39013. configurable: true
  39014. });
  39015. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39016. get: function () {
  39017. return this._buttonLB;
  39018. },
  39019. set: function (value) {
  39020. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39021. },
  39022. enumerable: true,
  39023. configurable: true
  39024. });
  39025. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39026. get: function () {
  39027. return this._buttonRB;
  39028. },
  39029. set: function (value) {
  39030. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39036. get: function () {
  39037. return this._buttonLeftStick;
  39038. },
  39039. set: function (value) {
  39040. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39041. },
  39042. enumerable: true,
  39043. configurable: true
  39044. });
  39045. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39046. get: function () {
  39047. return this._buttonRightStick;
  39048. },
  39049. set: function (value) {
  39050. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39051. },
  39052. enumerable: true,
  39053. configurable: true
  39054. });
  39055. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39056. get: function () {
  39057. return this._dPadUp;
  39058. },
  39059. set: function (value) {
  39060. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39061. },
  39062. enumerable: true,
  39063. configurable: true
  39064. });
  39065. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39066. get: function () {
  39067. return this._dPadDown;
  39068. },
  39069. set: function (value) {
  39070. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39071. },
  39072. enumerable: true,
  39073. configurable: true
  39074. });
  39075. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39076. get: function () {
  39077. return this._dPadLeft;
  39078. },
  39079. set: function (value) {
  39080. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39081. },
  39082. enumerable: true,
  39083. configurable: true
  39084. });
  39085. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39086. get: function () {
  39087. return this._dPadRight;
  39088. },
  39089. set: function (value) {
  39090. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39091. },
  39092. enumerable: true,
  39093. configurable: true
  39094. });
  39095. Xbox360Pad.prototype.update = function () {
  39096. _super.prototype.update.call(this);
  39097. this.buttonA = this.browserGamepad.buttons[0].value;
  39098. this.buttonB = this.browserGamepad.buttons[1].value;
  39099. this.buttonX = this.browserGamepad.buttons[2].value;
  39100. this.buttonY = this.browserGamepad.buttons[3].value;
  39101. this.buttonLB = this.browserGamepad.buttons[4].value;
  39102. this.buttonRB = this.browserGamepad.buttons[5].value;
  39103. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39104. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39105. this.buttonBack = this.browserGamepad.buttons[8].value;
  39106. this.buttonStart = this.browserGamepad.buttons[9].value;
  39107. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39108. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39109. this.dPadUp = this.browserGamepad.buttons[12].value;
  39110. this.dPadDown = this.browserGamepad.buttons[13].value;
  39111. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39112. this.dPadRight = this.browserGamepad.buttons[15].value;
  39113. };
  39114. return Xbox360Pad;
  39115. })(Gamepad);
  39116. BABYLON.Xbox360Pad = Xbox360Pad;
  39117. })(BABYLON || (BABYLON = {}));
  39118. var BABYLON;
  39119. (function (BABYLON) {
  39120. // We're mainly based on the logic defined into the FreeCamera code
  39121. var GamepadCamera = (function (_super) {
  39122. __extends(GamepadCamera, _super);
  39123. function GamepadCamera(name, position, scene) {
  39124. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39125. _super.call(this, name, position, scene);
  39126. }
  39127. GamepadCamera.prototype.getTypeName = function () {
  39128. return "GamepadCamera";
  39129. };
  39130. return GamepadCamera;
  39131. })(BABYLON.UniversalCamera);
  39132. BABYLON.GamepadCamera = GamepadCamera;
  39133. })(BABYLON || (BABYLON = {}));
  39134. var BABYLON;
  39135. (function (BABYLON) {
  39136. var AnaglyphFreeCamera = (function (_super) {
  39137. __extends(AnaglyphFreeCamera, _super);
  39138. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39139. _super.call(this, name, position, scene);
  39140. this.interaxialDistance = interaxialDistance;
  39141. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39142. }
  39143. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39144. return "AnaglyphFreeCamera";
  39145. };
  39146. return AnaglyphFreeCamera;
  39147. })(BABYLON.FreeCamera);
  39148. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39149. var AnaglyphArcRotateCamera = (function (_super) {
  39150. __extends(AnaglyphArcRotateCamera, _super);
  39151. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39152. _super.call(this, name, alpha, beta, radius, target, scene);
  39153. this.interaxialDistance = interaxialDistance;
  39154. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39155. }
  39156. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39157. return "AnaglyphArcRotateCamera";
  39158. };
  39159. return AnaglyphArcRotateCamera;
  39160. })(BABYLON.ArcRotateCamera);
  39161. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39162. var AnaglyphGamepadCamera = (function (_super) {
  39163. __extends(AnaglyphGamepadCamera, _super);
  39164. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39165. _super.call(this, name, position, scene);
  39166. this.interaxialDistance = interaxialDistance;
  39167. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39168. }
  39169. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39170. return "AnaglyphGamepadCamera";
  39171. };
  39172. return AnaglyphGamepadCamera;
  39173. })(BABYLON.GamepadCamera);
  39174. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39175. var AnaglyphUniversalCamera = (function (_super) {
  39176. __extends(AnaglyphUniversalCamera, _super);
  39177. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39178. _super.call(this, name, position, scene);
  39179. this.interaxialDistance = interaxialDistance;
  39180. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39181. }
  39182. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39183. return "AnaglyphUniversalCamera";
  39184. };
  39185. return AnaglyphUniversalCamera;
  39186. })(BABYLON.UniversalCamera);
  39187. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39188. var StereoscopicFreeCamera = (function (_super) {
  39189. __extends(StereoscopicFreeCamera, _super);
  39190. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39191. _super.call(this, name, position, scene);
  39192. this.interaxialDistance = interaxialDistance;
  39193. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39194. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39195. }
  39196. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39197. return "StereoscopicFreeCamera";
  39198. };
  39199. return StereoscopicFreeCamera;
  39200. })(BABYLON.FreeCamera);
  39201. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39202. var StereoscopicArcRotateCamera = (function (_super) {
  39203. __extends(StereoscopicArcRotateCamera, _super);
  39204. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39205. _super.call(this, name, alpha, beta, radius, target, scene);
  39206. this.interaxialDistance = interaxialDistance;
  39207. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39208. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39209. }
  39210. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39211. return "StereoscopicArcRotateCamera";
  39212. };
  39213. return StereoscopicArcRotateCamera;
  39214. })(BABYLON.ArcRotateCamera);
  39215. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39216. var StereoscopicGamepadCamera = (function (_super) {
  39217. __extends(StereoscopicGamepadCamera, _super);
  39218. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39219. _super.call(this, name, position, scene);
  39220. this.interaxialDistance = interaxialDistance;
  39221. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39222. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39223. }
  39224. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39225. return "StereoscopicGamepadCamera";
  39226. };
  39227. return StereoscopicGamepadCamera;
  39228. })(BABYLON.GamepadCamera);
  39229. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39230. var StereoscopicUniversalCamera = (function (_super) {
  39231. __extends(StereoscopicUniversalCamera, _super);
  39232. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39233. _super.call(this, name, position, scene);
  39234. this.interaxialDistance = interaxialDistance;
  39235. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39236. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39237. }
  39238. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39239. return "StereoscopicUniversalCamera";
  39240. };
  39241. return StereoscopicUniversalCamera;
  39242. })(BABYLON.UniversalCamera);
  39243. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39244. })(BABYLON || (BABYLON = {}));
  39245. //_______________________________________________________________
  39246. // Extracted from CubeMapGen:
  39247. // https://code.google.com/archive/p/cubemapgen/
  39248. //
  39249. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39250. //_______________________________________________________________
  39251. var BABYLON;
  39252. (function (BABYLON) {
  39253. var Internals;
  39254. (function (Internals) {
  39255. /**
  39256. * The bounding box information used during the conversion process.
  39257. */
  39258. var CMGBoundinBox = (function () {
  39259. function CMGBoundinBox() {
  39260. this.min = new BABYLON.Vector3(0, 0, 0);
  39261. this.max = new BABYLON.Vector3(0, 0, 0);
  39262. this.clear();
  39263. }
  39264. CMGBoundinBox.prototype.clear = function () {
  39265. this.min.x = CMGBoundinBox.MAX;
  39266. this.min.y = CMGBoundinBox.MAX;
  39267. this.min.z = CMGBoundinBox.MAX;
  39268. this.max.x = CMGBoundinBox.MIN;
  39269. this.max.y = CMGBoundinBox.MIN;
  39270. this.max.z = CMGBoundinBox.MIN;
  39271. };
  39272. CMGBoundinBox.prototype.augment = function (x, y, z) {
  39273. this.min.x = Math.min(this.min.x, x);
  39274. this.min.y = Math.min(this.min.y, y);
  39275. this.min.z = Math.min(this.min.z, z);
  39276. this.max.x = Math.max(this.max.x, x);
  39277. this.max.y = Math.max(this.max.y, y);
  39278. this.max.z = Math.max(this.max.z, z);
  39279. };
  39280. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  39281. this.min.x = Math.max(this.min.x, x);
  39282. this.min.y = Math.max(this.min.y, y);
  39283. this.min.z = Math.max(this.min.z, z);
  39284. };
  39285. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  39286. this.max.x = Math.min(this.max.x, x);
  39287. this.max.y = Math.min(this.max.y, y);
  39288. this.max.z = Math.min(this.max.z, z);
  39289. };
  39290. CMGBoundinBox.prototype.empty = function () {
  39291. if ((this.min.x > this.max.y) ||
  39292. (this.min.y > this.max.y) ||
  39293. (this.min.z > this.max.y)) {
  39294. return true;
  39295. }
  39296. else {
  39297. return false;
  39298. }
  39299. };
  39300. CMGBoundinBox.MAX = Number.MAX_VALUE;
  39301. CMGBoundinBox.MIN = Number.MIN_VALUE;
  39302. return CMGBoundinBox;
  39303. })();
  39304. /**
  39305. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  39306. * required by the glossinees of a material.
  39307. *
  39308. * This only supports the cosine drop power as well as Warp fixup generation method.
  39309. *
  39310. * This is using the process from CubeMapGen described here:
  39311. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39312. */
  39313. var PMREMGenerator = (function () {
  39314. /**
  39315. * Constructor of the generator.
  39316. *
  39317. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  39318. * @param inputSize The size of the cubemap faces
  39319. * @param outputSize The size of the output cubemap faces
  39320. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  39321. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  39322. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  39323. * @param specularPower The max specular level of the desired cubemap
  39324. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  39325. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  39326. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  39327. */
  39328. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  39329. this.input = input;
  39330. this.inputSize = inputSize;
  39331. this.outputSize = outputSize;
  39332. this.maxNumMipLevels = maxNumMipLevels;
  39333. this.numChannels = numChannels;
  39334. this.isFloat = isFloat;
  39335. this.specularPower = specularPower;
  39336. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  39337. this.excludeBase = excludeBase;
  39338. this.fixup = fixup;
  39339. this._outputSurface = [];
  39340. this._numMipLevels = 0;
  39341. }
  39342. /**
  39343. * Launches the filter process and return the result.
  39344. *
  39345. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  39346. */
  39347. PMREMGenerator.prototype.filterCubeMap = function () {
  39348. // Init cubemap processor
  39349. this.init();
  39350. // Filters the cubemap
  39351. this.filterCubeMapMipChain();
  39352. // Returns the filtered mips.
  39353. return this._outputSurface;
  39354. };
  39355. PMREMGenerator.prototype.init = function () {
  39356. var i;
  39357. var j;
  39358. var mipLevelSize;
  39359. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  39360. if (this.maxNumMipLevels == 0) {
  39361. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  39362. }
  39363. //first miplevel size
  39364. mipLevelSize = this.outputSize;
  39365. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  39366. for (j = 0; j < this.maxNumMipLevels; j++) {
  39367. this._outputSurface.length++;
  39368. this._outputSurface[j] = [];
  39369. //Iterate over faces for output images
  39370. for (i = 0; i < 6; i++) {
  39371. this._outputSurface[j].length++;
  39372. // Initializes a new array for the output.
  39373. if (this.isFloat) {
  39374. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39375. }
  39376. else {
  39377. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39378. }
  39379. }
  39380. //next mip level is half size
  39381. mipLevelSize >>= 1;
  39382. this._numMipLevels++;
  39383. //terminate if mip chain becomes too small
  39384. if (mipLevelSize == 0) {
  39385. this.maxNumMipLevels = j;
  39386. return;
  39387. }
  39388. }
  39389. };
  39390. //--------------------------------------------------------------------------------------
  39391. //Cube map filtering and mip chain generation.
  39392. // the cube map filtereing is specified using a number of parameters:
  39393. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  39394. // indicates the region of the hemisphere to filter over for each tap.
  39395. //
  39396. // Note that the top mip level is also a filtered version of the original input images
  39397. // as well in order to create mip chains for diffuse environment illumination.
  39398. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  39399. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  39400. //
  39401. // Then the mip angle used to genreate the next level of the mip chain from the first level
  39402. // is a_InitialMipAngle
  39403. //
  39404. // The angle for the subsequent levels of the mip chain are specified by their parents
  39405. // filtering angle and a per-level scale and bias
  39406. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  39407. //
  39408. //--------------------------------------------------------------------------------------
  39409. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  39410. // First, take count of the lighting model to modify SpecularPower
  39411. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  39412. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  39413. //Cone angle start (for generating subsequent mip levels)
  39414. var currentSpecularPower = this.specularPower;
  39415. //Build filter lookup tables based on the source miplevel size
  39416. this.precomputeFilterLookupTables(this.inputSize);
  39417. // Note that we need to filter the first level before generating mipmap
  39418. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  39419. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  39420. // TODO : Write a function to copy and scale the base mipmap in output
  39421. // I am just lazy here and just put a high specular power value, and do some if.
  39422. if (this.excludeBase && (levelIndex == 0)) {
  39423. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  39424. currentSpecularPower = 100000.0;
  39425. }
  39426. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  39427. var srcCubeImage = this.input;
  39428. var dstCubeImage = this._outputSurface[levelIndex];
  39429. var dstSize = this.outputSize >> levelIndex;
  39430. // Compute required angle.
  39431. var angle = this.getBaseFilterAngle(currentSpecularPower);
  39432. // filter cube surfaces
  39433. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  39434. // fix seams
  39435. if (this.fixup) {
  39436. this.fixupCubeEdges(dstCubeImage, dstSize);
  39437. }
  39438. // Decrease the specular power to generate the mipmap chain
  39439. // TODO : Use another method for Exclude (see first comment at start of the function
  39440. if (this.excludeBase && (levelIndex == 0)) {
  39441. currentSpecularPower = this.specularPower;
  39442. }
  39443. currentSpecularPower *= this.cosinePowerDropPerMip;
  39444. }
  39445. };
  39446. //--------------------------------------------------------------------------------------
  39447. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  39448. // It allow to optimize the texel to access base on the specular power.
  39449. //--------------------------------------------------------------------------------------
  39450. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  39451. // We want to find the alpha such that:
  39452. // cos(alpha)^cosinePower = epsilon
  39453. // That's: acos(epsilon^(1/cosinePower))
  39454. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  39455. var angle = 180.0;
  39456. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  39457. angle *= 180.0 / Math.PI; // Convert to degree
  39458. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  39459. return angle;
  39460. };
  39461. //--------------------------------------------------------------------------------------
  39462. //Builds the following lookup tables prior to filtering:
  39463. // -normalizer cube map
  39464. // -tap weight lookup table
  39465. //
  39466. //--------------------------------------------------------------------------------------
  39467. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  39468. var srcTexelAngle;
  39469. var iCubeFace;
  39470. //clear pre-existing normalizer cube map
  39471. this._normCubeMap = [];
  39472. //Normalized vectors per cubeface and per-texel solid angle
  39473. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  39474. };
  39475. //--------------------------------------------------------------------------------------
  39476. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  39477. //
  39478. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  39479. //
  39480. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  39481. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  39482. // below
  39483. //--------------------------------------------------------------------------------------
  39484. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  39485. var iCubeFace;
  39486. var u;
  39487. var v;
  39488. //iterate over cube faces
  39489. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39490. //First three channels for norm cube, and last channel for solid angle
  39491. this._normCubeMap.push(new Float32Array(size * size * 4));
  39492. //fast texture walk, build normalizer cube map
  39493. var facesData = this.input[iCubeFace];
  39494. for (v = 0; v < size; v++) {
  39495. for (u = 0; u < size; u++) {
  39496. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  39497. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  39498. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  39499. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  39500. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  39501. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  39502. }
  39503. }
  39504. }
  39505. };
  39506. //--------------------------------------------------------------------------------------
  39507. // Convert cubemap face texel coordinates and face idx to 3D vector
  39508. // note the U and V coords are integer coords and range from 0 to size-1
  39509. // this routine can be used to generate a normalizer cube map
  39510. //--------------------------------------------------------------------------------------
  39511. // SL BEGIN
  39512. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  39513. var nvcU;
  39514. var nvcV;
  39515. var tempVec;
  39516. // Change from original AMD code
  39517. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39518. // + 0.5f is for texel center addressing
  39519. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  39520. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  39521. // warp fixup
  39522. if (fixup && size > 1) {
  39523. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  39524. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  39525. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  39526. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  39527. }
  39528. // Get current vector
  39529. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  39530. // U contribution
  39531. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39532. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  39533. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  39534. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  39535. // V contribution and Sum
  39536. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39537. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  39538. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  39539. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  39540. //add face axis
  39541. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  39542. PMREMGenerator._vectorTemp.x += faceAxis[0];
  39543. PMREMGenerator._vectorTemp.y += faceAxis[1];
  39544. PMREMGenerator._vectorTemp.z += faceAxis[2];
  39545. //normalize vector
  39546. PMREMGenerator._vectorTemp.normalize();
  39547. return PMREMGenerator._vectorTemp;
  39548. };
  39549. //--------------------------------------------------------------------------------------
  39550. // Convert 3D vector to cubemap face texel coordinates and face idx
  39551. // note the U and V coords are integer coords and range from 0 to size-1
  39552. // this routine can be used to generate a normalizer cube map
  39553. //
  39554. // returns face IDX and texel coords
  39555. //--------------------------------------------------------------------------------------
  39556. // SL BEGIN
  39557. /*
  39558. Mapping Texture Coordinates to Cube Map Faces
  39559. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  39560. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  39561. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  39562. map arrangement in Pixar's RenderMan package.
  39563. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  39564. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  39565. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  39566. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  39567. the major axis direction). The target column in the table below explains how the major axis direction
  39568. maps to the 2D image of a particular cube map target.
  39569. major axis
  39570. direction target sc tc ma
  39571. ---------- --------------------------------- --- --- ---
  39572. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  39573. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  39574. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  39575. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  39576. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  39577. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  39578. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  39579. an updated (s,t) is calculated as follows
  39580. s = ( sc/|ma| + 1 ) / 2
  39581. t = ( tc/|ma| + 1 ) / 2
  39582. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  39583. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  39584. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  39585. */
  39586. // Note this method return U and V in range from 0 to size-1
  39587. // SL END
  39588. // Store the information in vector3 for convenience (faceindex, u, v)
  39589. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  39590. var maxCoord;
  39591. var faceIdx;
  39592. //absolute value 3
  39593. var absX = Math.abs(x);
  39594. var absY = Math.abs(y);
  39595. var absZ = Math.abs(z);
  39596. if (absX >= absY && absX >= absZ) {
  39597. maxCoord = absX;
  39598. if (x >= 0) {
  39599. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  39600. }
  39601. else {
  39602. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39603. }
  39604. }
  39605. else if (absY >= absX && absY >= absZ) {
  39606. maxCoord = absY;
  39607. if (y >= 0) {
  39608. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39609. }
  39610. else {
  39611. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39612. }
  39613. }
  39614. else {
  39615. maxCoord = absZ;
  39616. if (z >= 0) {
  39617. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39618. }
  39619. else {
  39620. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39621. }
  39622. }
  39623. //divide through by max coord so face vector lies on cube face
  39624. var scale = 1 / maxCoord;
  39625. x *= scale;
  39626. y *= scale;
  39627. z *= scale;
  39628. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39629. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  39630. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39631. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  39632. // Modify original AMD code to return value from 0 to Size - 1
  39633. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  39634. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  39635. PMREMGenerator._vectorTemp.x = faceIdx;
  39636. PMREMGenerator._vectorTemp.y = u;
  39637. PMREMGenerator._vectorTemp.z = v;
  39638. return PMREMGenerator._vectorTemp;
  39639. };
  39640. //--------------------------------------------------------------------------------------
  39641. //Original code from Ignacio CastaÒo
  39642. // This formula is from Manne ÷hrstrˆm's thesis.
  39643. // Take two coordiantes in the range [-1, 1] that define a portion of a
  39644. // cube face and return the area of the projection of that portion on the
  39645. // surface of the sphere.
  39646. //--------------------------------------------------------------------------------------
  39647. PMREMGenerator.prototype.areaElement = function (x, y) {
  39648. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  39649. };
  39650. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  39651. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39652. // (+ 0.5f is for texel center addressing)
  39653. u = (2.0 * (u + 0.5) / size) - 1.0;
  39654. v = (2.0 * (v + 0.5) / size) - 1.0;
  39655. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  39656. var invResolution = 1.0 / size;
  39657. // U and V are the -1..1 texture coordinate on the current face.
  39658. // Get projected area for this texel
  39659. var x0 = u - invResolution;
  39660. var y0 = v - invResolution;
  39661. var x1 = u + invResolution;
  39662. var y1 = v + invResolution;
  39663. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  39664. return solidAngle;
  39665. };
  39666. //--------------------------------------------------------------------------------------
  39667. //The key to the speed of these filtering routines is to quickly define a per-face
  39668. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  39669. // Later these pixels are selectively processed based on their dot products to see if
  39670. // they reside within the filtering cone.
  39671. //
  39672. //This is done by computing the smallest per-texel angle to get a conservative estimate
  39673. // of the number of texels needed to be covered in width and height order to filter the
  39674. // region. the bounding box for the center taps face is defined first, and if the
  39675. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  39676. // defined next
  39677. //--------------------------------------------------------------------------------------
  39678. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  39679. // note that pixels within these regions may be rejected
  39680. // based on the anlge
  39681. var iCubeFace;
  39682. var u;
  39683. var v;
  39684. // bounding box per face to specify region to process
  39685. var filterExtents = [];
  39686. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39687. filterExtents.push(new CMGBoundinBox());
  39688. }
  39689. // min angle a src texel can cover (in degrees)
  39690. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  39691. // angle about center tap to define filter cone
  39692. // filter angle is 1/2 the cone angle
  39693. var filterAngle = filterConeAngle / 2.0;
  39694. //ensure filter angle is larger than a texel
  39695. if (filterAngle < srcTexelAngle) {
  39696. filterAngle = srcTexelAngle;
  39697. }
  39698. //ensure filter cone is always smaller than the hemisphere
  39699. if (filterAngle > 90.0) {
  39700. filterAngle = 90.0;
  39701. }
  39702. // the maximum number of texels in 1D the filter cone angle will cover
  39703. // used to determine bounding box size for filter extents
  39704. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  39705. // ensure conservative region always covers at least one texel
  39706. if (filterSize < 1) {
  39707. filterSize = 1;
  39708. }
  39709. // dotProdThresh threshold based on cone angle to determine whether or not taps
  39710. // reside within the cone angle
  39711. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  39712. // process required faces
  39713. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39714. //iterate over dst cube map face texel
  39715. for (v = 0; v < dstSize; v++) {
  39716. for (u = 0; u < dstSize; u++) {
  39717. //get center tap direction
  39718. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  39719. //clear old per-face filter extents
  39720. this.clearFilterExtents(filterExtents);
  39721. //define per-face filter extents
  39722. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  39723. //perform filtering of src faces using filter extents
  39724. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  39725. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  39726. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  39727. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  39728. }
  39729. }
  39730. }
  39731. };
  39732. //--------------------------------------------------------------------------------------
  39733. //Clear filter extents for the 6 cube map faces
  39734. //--------------------------------------------------------------------------------------
  39735. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  39736. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  39737. filterExtents[iCubeFaces].clear();
  39738. }
  39739. };
  39740. //--------------------------------------------------------------------------------------
  39741. //Define per-face bounding box filter extents
  39742. //
  39743. // These define conservative texel regions in each of the faces the filter can possibly
  39744. // process. When the pixels in the regions are actually processed, the dot product
  39745. // between the tap vector and the center tap vector is used to determine the weight of
  39746. // the tap and whether or not the tap is within the cone.
  39747. //
  39748. //--------------------------------------------------------------------------------------
  39749. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  39750. //neighboring face and bleed over amount, and width of BBOX for
  39751. // left, right, top, and bottom edges of this face
  39752. var bleedOverAmount = [0, 0, 0, 0];
  39753. var bleedOverBBoxMin = [0, 0, 0, 0];
  39754. var bleedOverBBoxMax = [0, 0, 0, 0];
  39755. var neighborFace;
  39756. var neighborEdge;
  39757. var oppositeFaceIdx;
  39758. //get face idx, and u, v info from center tap dir
  39759. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  39760. var faceIdx = result.x;
  39761. var u = result.y;
  39762. var v = result.z;
  39763. //define bbox size within face
  39764. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  39765. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  39766. filterExtents[faceIdx].clampMin(0, 0, 0);
  39767. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  39768. //u and v extent in face corresponding to center tap
  39769. var minU = filterExtents[faceIdx].min.x;
  39770. var minV = filterExtents[faceIdx].min.y;
  39771. var maxU = filterExtents[faceIdx].max.x;
  39772. var maxV = filterExtents[faceIdx].max.y;
  39773. //bleed over amounts for face across u=0 edge (left)
  39774. bleedOverAmount[0] = (bboxSize - u);
  39775. bleedOverBBoxMin[0] = minV;
  39776. bleedOverBBoxMax[0] = maxV;
  39777. //bleed over amounts for face across u=1 edge (right)
  39778. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  39779. bleedOverBBoxMin[1] = minV;
  39780. bleedOverBBoxMax[1] = maxV;
  39781. //bleed over to face across v=0 edge (up)
  39782. bleedOverAmount[2] = (bboxSize - v);
  39783. bleedOverBBoxMin[2] = minU;
  39784. bleedOverBBoxMax[2] = maxU;
  39785. //bleed over to face across v=1 edge (down)
  39786. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  39787. bleedOverBBoxMin[3] = minU;
  39788. bleedOverBBoxMax[3] = maxU;
  39789. //compute bleed over regions in neighboring faces
  39790. for (var i = 0; i < 4; i++) {
  39791. if (bleedOverAmount[i] > 0) {
  39792. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  39793. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  39794. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  39795. // be flipped: the cases are
  39796. // if a left edge mates with a left or bottom edge on the neighbor
  39797. // if a top edge mates with a top or right edge on the neighbor
  39798. // if a right edge mates with a right or top edge on the neighbor
  39799. // if a bottom edge mates with a bottom or left edge on the neighbor
  39800. //Seeing as the edges are enumerated as follows
  39801. // left =0
  39802. // right =1
  39803. // top =2
  39804. // bottom =3
  39805. //
  39806. // so if the edge enums are the same, or the sum of the enums == 3,
  39807. // the bbox needs to be flipped
  39808. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  39809. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  39810. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  39811. }
  39812. //The way the bounding box is extended onto the neighboring face
  39813. // depends on which edge of neighboring face abuts with this one
  39814. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  39815. case PMREMGenerator.CP_EDGE_LEFT:
  39816. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  39817. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39818. break;
  39819. case PMREMGenerator.CP_EDGE_RIGHT:
  39820. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  39821. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39822. break;
  39823. case PMREMGenerator.CP_EDGE_TOP:
  39824. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  39825. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  39826. break;
  39827. case PMREMGenerator.CP_EDGE_BOTTOM:
  39828. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  39829. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  39830. break;
  39831. }
  39832. //clamp filter extents in non-center tap faces to remain within surface
  39833. filterExtents[neighborFace].clampMin(0, 0, 0);
  39834. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  39835. }
  39836. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  39837. // from the center tap face, then process the opposite face entirely for now.
  39838. //Note that the cases in which this happens, what usually happens is that
  39839. // more than one edge bleeds onto the opposite face, and the bounding box
  39840. // encompasses the entire cube map face.
  39841. if (bleedOverAmount[i] > srcSize) {
  39842. //determine opposite face
  39843. switch (faceIdx) {
  39844. case PMREMGenerator.CP_FACE_X_POS:
  39845. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39846. break;
  39847. case PMREMGenerator.CP_FACE_X_NEG:
  39848. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  39849. break;
  39850. case PMREMGenerator.CP_FACE_Y_POS:
  39851. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39852. break;
  39853. case PMREMGenerator.CP_FACE_Y_NEG:
  39854. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39855. break;
  39856. case PMREMGenerator.CP_FACE_Z_POS:
  39857. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39858. break;
  39859. case PMREMGenerator.CP_FACE_Z_NEG:
  39860. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39861. break;
  39862. default:
  39863. break;
  39864. }
  39865. //just encompass entire face for now
  39866. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  39867. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  39868. }
  39869. }
  39870. };
  39871. //--------------------------------------------------------------------------------------
  39872. //ProcessFilterExtents
  39873. // Process bounding box in each cube face
  39874. //
  39875. //--------------------------------------------------------------------------------------
  39876. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  39877. //accumulators are 64-bit floats in order to have the precision needed
  39878. // over a summation of a large number of pixels
  39879. var dstAccum = [0, 0, 0, 0];
  39880. var weightAccum = 0;
  39881. var k = 0;
  39882. var nSrcChannels = this.numChannels;
  39883. // norm cube map and srcCubeMap have same face width
  39884. var faceWidth = srcSize;
  39885. //amount to add to pointer to move to next scanline in images
  39886. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  39887. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  39888. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  39889. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  39890. // iterate over cubefaces
  39891. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  39892. //if bbox is non empty
  39893. if (!filterExtents[iFaceIdx].empty()) {
  39894. var uStart = filterExtents[iFaceIdx].min.x;
  39895. var vStart = filterExtents[iFaceIdx].min.y;
  39896. var uEnd = filterExtents[iFaceIdx].max.x;
  39897. var vEnd = filterExtents[iFaceIdx].max.y;
  39898. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  39899. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  39900. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  39901. for (var v = vStart; v <= vEnd; v++) {
  39902. var normCubeRowWalk = 0;
  39903. var srcCubeRowWalk = 0;
  39904. for (var u = uStart; u <= uEnd; u++) {
  39905. //pointer to direction in cube map associated with texel
  39906. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  39907. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  39908. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  39909. //check dot product to see if texel is within cone
  39910. var tapDotProd = texelVectX * centerTapDir.x +
  39911. texelVectY * centerTapDir.y +
  39912. texelVectZ * centerTapDir.z;
  39913. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  39914. //solid angle stored in 4th channel of normalizer/solid angle cube map
  39915. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  39916. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  39917. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  39918. // so just adding one to specularpower do the trick.
  39919. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  39920. //iterate over channels
  39921. for (k = 0; k < nSrcChannels; k++) {
  39922. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  39923. srcCubeRowWalk++;
  39924. }
  39925. weightAccum += weight; //accumulate weight
  39926. }
  39927. else {
  39928. //step across source pixel
  39929. srcCubeRowWalk += nSrcChannels;
  39930. }
  39931. normCubeRowWalk += 4; // 4 channels per norm cube map.
  39932. }
  39933. startIndexNormCubeMap += normCubePitch;
  39934. startIndexSrcCubeMap += srcCubePitch;
  39935. }
  39936. }
  39937. }
  39938. //divide through by weights if weight is non zero
  39939. if (weightAccum != 0.0) {
  39940. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  39941. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  39942. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  39943. if (this.numChannels > 3) {
  39944. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  39945. }
  39946. }
  39947. else {
  39948. // otherwise sample nearest
  39949. // get face idx and u, v texel coordinate in face
  39950. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  39951. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  39952. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  39953. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  39954. if (this.numChannels > 3) {
  39955. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  39956. }
  39957. }
  39958. return PMREMGenerator._vectorTemp;
  39959. };
  39960. //--------------------------------------------------------------------------------------
  39961. // Fixup cube edges
  39962. //
  39963. // average texels on cube map faces across the edges
  39964. // WARP/BENT Method Only.
  39965. //--------------------------------------------------------------------------------------
  39966. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  39967. var k;
  39968. var j;
  39969. var i;
  39970. var iFace;
  39971. var iCorner = 0;
  39972. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  39973. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  39974. // note that if functionality to filter across the three texels for each corner, then
  39975. //indexed by corner and face idx. the array contains the face the start points belongs to.
  39976. var cornerPtr = [
  39977. [[], [], []],
  39978. [[], [], []],
  39979. [[], [], []],
  39980. [[], [], []],
  39981. [[], [], []],
  39982. [[], [], []],
  39983. [[], [], []],
  39984. [[], [], []]
  39985. ];
  39986. //if there is no fixup, or fixup width = 0, do nothing
  39987. if (cubeMapSize < 1) {
  39988. return;
  39989. }
  39990. //special case 1x1 cubemap, average face colors
  39991. if (cubeMapSize == 1) {
  39992. //iterate over channels
  39993. for (k = 0; k < this.numChannels; k++) {
  39994. var accum = 0.0;
  39995. //iterate over faces to accumulate face colors
  39996. for (iFace = 0; iFace < 6; iFace++) {
  39997. accum += cubeMap[iFace][k];
  39998. }
  39999. //compute average over 6 face colors
  40000. accum /= 6.0;
  40001. //iterate over faces to distribute face colors
  40002. for (iFace = 0; iFace < 6; iFace++) {
  40003. cubeMap[iFace][k] = accum;
  40004. }
  40005. }
  40006. return;
  40007. }
  40008. //iterate over faces to collect list of corner texel pointers
  40009. for (iFace = 0; iFace < 6; iFace++) {
  40010. //the 4 corner pointers for this face
  40011. faceCornerStartIndicies[0] = [iFace, 0];
  40012. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  40013. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  40014. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  40015. //iterate over face corners to collect cube corner pointers
  40016. for (iCorner = 0; iCorner < 4; iCorner++) {
  40017. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  40018. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  40019. cornerNumPtrs[corner]++;
  40020. }
  40021. }
  40022. //iterate over corners to average across corner tap values
  40023. for (iCorner = 0; iCorner < 8; iCorner++) {
  40024. for (k = 0; k < this.numChannels; k++) {
  40025. var cornerTapAccum = 0.0;
  40026. //iterate over corner texels and average results
  40027. for (i = 0; i < 3; i++) {
  40028. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  40029. }
  40030. //divide by 3 to compute average of corner tap values
  40031. cornerTapAccum *= (1.0 / 3.0);
  40032. //iterate over corner texels and average results
  40033. for (i = 0; i < 3; i++) {
  40034. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  40035. }
  40036. }
  40037. }
  40038. //iterate over the twelve edges of the cube to average across edges
  40039. for (i = 0; i < 12; i++) {
  40040. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  40041. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  40042. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  40043. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  40044. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  40045. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  40046. var edgeWalk = 0;
  40047. var neighborEdgeWalk = 0;
  40048. //Determine walking pointers based on edge type
  40049. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  40050. switch (edge) {
  40051. case PMREMGenerator.CP_EDGE_LEFT:
  40052. // no change to faceEdgeStartPtr
  40053. edgeWalk = this.numChannels * cubeMapSize;
  40054. break;
  40055. case PMREMGenerator.CP_EDGE_RIGHT:
  40056. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40057. edgeWalk = this.numChannels * cubeMapSize;
  40058. break;
  40059. case PMREMGenerator.CP_EDGE_TOP:
  40060. // no change to faceEdgeStartPtr
  40061. edgeWalk = this.numChannels;
  40062. break;
  40063. case PMREMGenerator.CP_EDGE_BOTTOM:
  40064. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40065. edgeWalk = this.numChannels;
  40066. break;
  40067. }
  40068. //For certain types of edge abutments, the neighbor edge walk needs to
  40069. // be flipped: the cases are
  40070. // if a left edge mates with a left or bottom edge on the neighbor
  40071. // if a top edge mates with a top or right edge on the neighbor
  40072. // if a right edge mates with a right or top edge on the neighbor
  40073. // if a bottom edge mates with a bottom or left edge on the neighbor
  40074. //Seeing as the edges are enumerated as follows
  40075. // left =0
  40076. // right =1
  40077. // top =2
  40078. // bottom =3
  40079. //
  40080. //If the edge enums are the same, or the sum of the enums == 3,
  40081. // the neighbor edge walk needs to be flipped
  40082. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  40083. switch (neighborEdge) {
  40084. case PMREMGenerator.CP_EDGE_LEFT:
  40085. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  40086. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40087. break;
  40088. case PMREMGenerator.CP_EDGE_RIGHT:
  40089. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40090. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40091. break;
  40092. case PMREMGenerator.CP_EDGE_TOP:
  40093. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40094. neighborEdgeWalk = -this.numChannels;
  40095. break;
  40096. case PMREMGenerator.CP_EDGE_BOTTOM:
  40097. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40098. neighborEdgeWalk = -this.numChannels;
  40099. break;
  40100. }
  40101. }
  40102. else {
  40103. //swapped direction neighbor edge walk
  40104. switch (neighborEdge) {
  40105. case PMREMGenerator.CP_EDGE_LEFT:
  40106. //no change to neighborEdgeStartPtr for this case since it points
  40107. // to the upper left corner already
  40108. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40109. break;
  40110. case PMREMGenerator.CP_EDGE_RIGHT:
  40111. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40112. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40113. break;
  40114. case PMREMGenerator.CP_EDGE_TOP:
  40115. //no change to neighborEdgeStartPtr for this case since it points
  40116. // to the upper left corner already
  40117. neighborEdgeWalk = this.numChannels;
  40118. break;
  40119. case PMREMGenerator.CP_EDGE_BOTTOM:
  40120. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40121. neighborEdgeWalk = this.numChannels;
  40122. break;
  40123. }
  40124. }
  40125. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  40126. //nearby neighborhood
  40127. //step ahead one texel on edge
  40128. edgeStartIndex += edgeWalk;
  40129. neighborEdgeStartIndex += neighborEdgeWalk;
  40130. // note that this loop does not process the corner texels, since they have already been
  40131. // averaged across faces across earlier
  40132. for (j = 1; j < (cubeMapSize - 1); j++) {
  40133. //for each set of taps along edge, average them
  40134. // and rewrite the results into the edges
  40135. for (k = 0; k < this.numChannels; k++) {
  40136. var edgeTap = cubeMap[face][edgeStartIndex + k];
  40137. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  40138. //compute average of tap intensity values
  40139. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  40140. //propagate average of taps to edge taps
  40141. cubeMap[face][edgeStartIndex + k] = avgTap;
  40142. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  40143. }
  40144. edgeStartIndex += edgeWalk;
  40145. neighborEdgeStartIndex += neighborEdgeWalk;
  40146. }
  40147. }
  40148. };
  40149. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  40150. PMREMGenerator.CP_UDIR = 0;
  40151. PMREMGenerator.CP_VDIR = 1;
  40152. PMREMGenerator.CP_FACEAXIS = 2;
  40153. //used to index cube faces
  40154. PMREMGenerator.CP_FACE_X_POS = 0;
  40155. PMREMGenerator.CP_FACE_X_NEG = 1;
  40156. PMREMGenerator.CP_FACE_Y_POS = 2;
  40157. PMREMGenerator.CP_FACE_Y_NEG = 3;
  40158. PMREMGenerator.CP_FACE_Z_POS = 4;
  40159. PMREMGenerator.CP_FACE_Z_NEG = 5;
  40160. //used to index image edges
  40161. // NOTE.. the actual number corresponding to the edge is important
  40162. // do not change these, or the code will break
  40163. //
  40164. // CP_EDGE_LEFT is u = 0
  40165. // CP_EDGE_RIGHT is u = width-1
  40166. // CP_EDGE_TOP is v = 0
  40167. // CP_EDGE_BOTTOM is v = height-1
  40168. PMREMGenerator.CP_EDGE_LEFT = 0;
  40169. PMREMGenerator.CP_EDGE_RIGHT = 1;
  40170. PMREMGenerator.CP_EDGE_TOP = 2;
  40171. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  40172. //corners of CUBE map (P or N specifys if it corresponds to the
  40173. // positive or negative direction each of X, Y, and Z
  40174. PMREMGenerator.CP_CORNER_NNN = 0;
  40175. PMREMGenerator.CP_CORNER_NNP = 1;
  40176. PMREMGenerator.CP_CORNER_NPN = 2;
  40177. PMREMGenerator.CP_CORNER_NPP = 3;
  40178. PMREMGenerator.CP_CORNER_PNN = 4;
  40179. PMREMGenerator.CP_CORNER_PNP = 5;
  40180. PMREMGenerator.CP_CORNER_PPN = 6;
  40181. PMREMGenerator.CP_CORNER_PPP = 7;
  40182. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  40183. //3x2 matrices that map cube map indexing vectors in 3d
  40184. // (after face selection and divide through by the
  40185. // _ABSOLUTE VALUE_ of the max coord)
  40186. // into NVC space
  40187. //Note this currently assumes the D3D cube face ordering and orientation
  40188. PMREMGenerator._sgFace2DMapping = [
  40189. //XPOS face
  40190. [[0, 0, -1],
  40191. [0, -1, 0],
  40192. [1, 0, 0]],
  40193. //XNEG face
  40194. [[0, 0, 1],
  40195. [0, -1, 0],
  40196. [-1, 0, 0]],
  40197. //YPOS face
  40198. [[1, 0, 0],
  40199. [0, 0, 1],
  40200. [0, 1, 0]],
  40201. //YNEG face
  40202. [[1, 0, 0],
  40203. [0, 0, -1],
  40204. [0, -1, 0]],
  40205. //ZPOS face
  40206. [[1, 0, 0],
  40207. [0, -1, 0],
  40208. [0, 0, 1]],
  40209. //ZNEG face
  40210. [[-1, 0, 0],
  40211. [0, -1, 0],
  40212. [0, 0, -1]],
  40213. ];
  40214. //------------------------------------------------------------------------------
  40215. // D3D cube map face specification
  40216. // mapping from 3D x,y,z cube map lookup coordinates
  40217. // to 2D within face u,v coordinates
  40218. //
  40219. // --------------------> U direction
  40220. // | (within-face texture space)
  40221. // | _____
  40222. // | | |
  40223. // | | +Y |
  40224. // | _____|_____|_____ _____
  40225. // | | | | | |
  40226. // | | -X | +Z | +X | -Z |
  40227. // | |_____|_____|_____|_____|
  40228. // | | |
  40229. // | | -Y |
  40230. // | |_____|
  40231. // |
  40232. // v V direction
  40233. // (within-face texture space)
  40234. //------------------------------------------------------------------------------
  40235. //Information about neighbors and how texture coorrdinates change across faces
  40236. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  40237. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  40238. //Note this currently assumes the D3D cube face ordering and orientation
  40239. PMREMGenerator._sgCubeNgh = [
  40240. //XPOS face
  40241. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40242. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40243. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40244. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  40245. //XNEG face
  40246. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40247. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  40248. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  40249. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  40250. //YPOS face
  40251. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40252. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40253. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40254. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  40255. //YNEG face
  40256. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40257. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40258. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40259. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  40260. //ZPOS face
  40261. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40262. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40263. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40264. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  40265. //ZNEG face
  40266. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40267. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40268. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  40269. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  40270. ];
  40271. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  40272. // this table is used to average over the edges.
  40273. PMREMGenerator._sgCubeEdgeList = [
  40274. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40275. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40276. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40277. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40278. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40279. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40280. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40281. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40282. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  40283. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40284. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40285. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  40286. ];
  40287. //Information about which of the 8 cube corners are correspond to the
  40288. // the 4 corners in each cube face
  40289. // the order is upper left, upper right, lower left, lower right
  40290. PMREMGenerator._sgCubeCornerList = [
  40291. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  40292. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  40293. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  40294. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  40295. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  40296. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  40297. ];
  40298. return PMREMGenerator;
  40299. })();
  40300. Internals.PMREMGenerator = PMREMGenerator;
  40301. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40302. })(BABYLON || (BABYLON = {}));
  40303. var BABYLON;
  40304. (function (BABYLON) {
  40305. var Internals;
  40306. (function (Internals) {
  40307. var FileFaceOrientation = (function () {
  40308. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40309. this.name = name;
  40310. this.worldAxisForNormal = worldAxisForNormal;
  40311. this.worldAxisForFileX = worldAxisForFileX;
  40312. this.worldAxisForFileY = worldAxisForFileY;
  40313. }
  40314. return FileFaceOrientation;
  40315. })();
  40316. ;
  40317. /**
  40318. * Helper class dealing with the extraction of spherical polynomial dataArray
  40319. * from a cube map.
  40320. */
  40321. var CubeMapToSphericalPolynomialTools = (function () {
  40322. function CubeMapToSphericalPolynomialTools() {
  40323. }
  40324. /**
  40325. * Converts a cubemap to the according Spherical Polynomial data.
  40326. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40327. *
  40328. * @param cubeInfo The Cube map to extract the information from.
  40329. * @return The Spherical Polynomial data.
  40330. */
  40331. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40332. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40333. var totalSolidAngle = 0.0;
  40334. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40335. var du = 2.0 / cubeInfo.size;
  40336. var dv = du;
  40337. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40338. var minUV = du * 0.5 - 1.0;
  40339. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40340. var fileFace = this.FileFaces[faceIndex];
  40341. var dataArray = cubeInfo[fileFace.name];
  40342. var v = minUV;
  40343. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40344. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40345. // Because SP is still linear, so summation is fine in that basis.
  40346. for (var y = 0; y < cubeInfo.size; y++) {
  40347. var u = minUV;
  40348. for (var x = 0; x < cubeInfo.size; x++) {
  40349. // World direction (not normalised)
  40350. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40351. worldDirection.normalize();
  40352. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40353. if (1) {
  40354. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40355. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40356. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40357. var color = new BABYLON.Color3(r, g, b);
  40358. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40359. }
  40360. else {
  40361. if (faceIndex == 0) {
  40362. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40363. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40364. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40365. }
  40366. else if (faceIndex == 1) {
  40367. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40368. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40369. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40370. }
  40371. else if (faceIndex == 2) {
  40372. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40373. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40374. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40375. }
  40376. else if (faceIndex == 3) {
  40377. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40378. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40379. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40380. }
  40381. else if (faceIndex == 4) {
  40382. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40383. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40384. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40385. }
  40386. else if (faceIndex == 5) {
  40387. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40388. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40389. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40390. }
  40391. 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]);
  40392. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40393. }
  40394. totalSolidAngle += deltaSolidAngle;
  40395. u += du;
  40396. }
  40397. v += dv;
  40398. }
  40399. }
  40400. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40401. var correction = correctSolidAngle / totalSolidAngle;
  40402. sphericalHarmonics.scale(correction);
  40403. // Additionally scale by pi -- audit needed
  40404. sphericalHarmonics.scale(1.0 / Math.PI);
  40405. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40406. };
  40407. CubeMapToSphericalPolynomialTools.FileFaces = [
  40408. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40409. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40410. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40411. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40412. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40413. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40414. ];
  40415. return CubeMapToSphericalPolynomialTools;
  40416. })();
  40417. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40418. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40419. })(BABYLON || (BABYLON = {}));
  40420. var BABYLON;
  40421. (function (BABYLON) {
  40422. var Internals;
  40423. (function (Internals) {
  40424. /**
  40425. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40426. */
  40427. var PanoramaToCubeMapTools = (function () {
  40428. function PanoramaToCubeMapTools() {
  40429. }
  40430. /**
  40431. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40432. *
  40433. * @param float32Array The source data.
  40434. * @param inputWidth The width of the input panorama.
  40435. * @param inputhHeight The height of the input panorama.
  40436. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40437. * @return The cubemap data
  40438. */
  40439. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40440. if (!float32Array) {
  40441. throw "ConvertPanoramaToCubemap: input cannot be null";
  40442. }
  40443. if (float32Array.length != inputWidth * inputHeight * 3) {
  40444. throw "ConvertPanoramaToCubemap: input size is wrong";
  40445. }
  40446. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40447. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40448. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40449. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40450. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40451. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40452. return {
  40453. front: textureFront,
  40454. back: textureBack,
  40455. left: textureLeft,
  40456. right: textureRight,
  40457. up: textureUp,
  40458. down: textureDown,
  40459. size: size
  40460. };
  40461. };
  40462. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40463. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40464. var textureArray = new Float32Array(buffer);
  40465. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40466. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40467. var dy = 1 / texSize;
  40468. var fy = 0;
  40469. for (var y = 0; y < texSize; y++) {
  40470. var xv1 = faceData[0];
  40471. var xv2 = faceData[2];
  40472. for (var x = 0; x < texSize; x++) {
  40473. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40474. v.normalize();
  40475. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40476. // 3 channels per pixels
  40477. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40478. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40479. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40480. xv1 = xv1.add(rotDX1);
  40481. xv2 = xv2.add(rotDX2);
  40482. }
  40483. fy += dy;
  40484. }
  40485. return textureArray;
  40486. };
  40487. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40488. var theta = Math.atan2(vDir.z, vDir.x);
  40489. var phi = Math.acos(vDir.y);
  40490. while (theta < -Math.PI)
  40491. theta += 2 * Math.PI;
  40492. while (theta > Math.PI)
  40493. theta -= 2 * Math.PI;
  40494. var dx = theta / Math.PI;
  40495. var dy = phi / Math.PI;
  40496. // recenter.
  40497. dx = dx * 0.5 + 0.5;
  40498. var px = Math.round(dx * inputWidth);
  40499. if (px < 0)
  40500. px = 0;
  40501. else if (px >= inputWidth)
  40502. px = inputWidth - 1;
  40503. var py = Math.round(dy * inputHeight);
  40504. if (py < 0)
  40505. py = 0;
  40506. else if (py >= inputHeight)
  40507. py = inputHeight - 1;
  40508. var inputY = (inputHeight - py - 1);
  40509. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40510. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40511. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40512. return {
  40513. r: r,
  40514. g: g,
  40515. b: b
  40516. };
  40517. };
  40518. PanoramaToCubeMapTools.FACE_FRONT = [
  40519. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40520. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40521. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40522. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40523. ];
  40524. PanoramaToCubeMapTools.FACE_BACK = [
  40525. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40526. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40527. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40528. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40529. ];
  40530. PanoramaToCubeMapTools.FACE_RIGHT = [
  40531. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40532. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40533. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40534. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40535. ];
  40536. PanoramaToCubeMapTools.FACE_LEFT = [
  40537. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40538. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40539. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40540. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40541. ];
  40542. PanoramaToCubeMapTools.FACE_DOWN = [
  40543. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40544. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40545. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40546. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40547. ];
  40548. PanoramaToCubeMapTools.FACE_UP = [
  40549. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40550. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40551. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40552. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40553. ];
  40554. return PanoramaToCubeMapTools;
  40555. })();
  40556. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40557. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40558. })(BABYLON || (BABYLON = {}));
  40559. var BABYLON;
  40560. (function (BABYLON) {
  40561. var Internals;
  40562. (function (Internals) {
  40563. ;
  40564. /**
  40565. * This groups tools to convert HDR texture to native colors array.
  40566. */
  40567. var HDRTools = (function () {
  40568. function HDRTools() {
  40569. }
  40570. HDRTools.Ldexp = function (mantissa, exponent) {
  40571. if (exponent > 1023) {
  40572. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40573. }
  40574. if (exponent < -1074) {
  40575. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40576. }
  40577. return mantissa * Math.pow(2, exponent);
  40578. };
  40579. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40580. if (exponent > 0) {
  40581. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40582. float32array[index + 0] = red * exponent;
  40583. float32array[index + 1] = green * exponent;
  40584. float32array[index + 2] = blue * exponent;
  40585. }
  40586. else {
  40587. float32array[index + 0] = 0;
  40588. float32array[index + 1] = 0;
  40589. float32array[index + 2] = 0;
  40590. }
  40591. };
  40592. HDRTools.readStringLine = function (uint8array, startIndex) {
  40593. var line = "";
  40594. var character = "";
  40595. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40596. character = String.fromCharCode(uint8array[i]);
  40597. if (character == "\n") {
  40598. break;
  40599. }
  40600. line += character;
  40601. }
  40602. return line;
  40603. };
  40604. /**
  40605. * Reads header information from an RGBE texture stored in a native array.
  40606. * More information on this format are available here:
  40607. * https://en.wikipedia.org/wiki/RGBE_image_format
  40608. *
  40609. * @param uint8array The binary file stored in native array.
  40610. * @return The header information.
  40611. */
  40612. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40613. var height = 0;
  40614. var width = 0;
  40615. var line = this.readStringLine(uint8array, 0);
  40616. if (line[0] != '#' || line[1] != '?') {
  40617. throw "Bad HDR Format.";
  40618. }
  40619. var endOfHeader = false;
  40620. var findFormat = false;
  40621. var lineIndex = 0;
  40622. do {
  40623. lineIndex += (line.length + 1);
  40624. line = this.readStringLine(uint8array, lineIndex);
  40625. if (line == "FORMAT=32-bit_rle_rgbe") {
  40626. findFormat = true;
  40627. }
  40628. else if (line.length == 0) {
  40629. endOfHeader = true;
  40630. }
  40631. } while (!endOfHeader);
  40632. if (!findFormat) {
  40633. throw "HDR Bad header format, unsupported FORMAT";
  40634. }
  40635. lineIndex += (line.length + 1);
  40636. line = this.readStringLine(uint8array, lineIndex);
  40637. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40638. var match = sizeRegexp.exec(line);
  40639. // TODO. Support +Y and -X if needed.
  40640. if (match.length < 3) {
  40641. throw "HDR Bad header format, no size";
  40642. }
  40643. width = parseInt(match[2]);
  40644. height = parseInt(match[1]);
  40645. if (width < 8 || width > 0x7fff) {
  40646. throw "HDR Bad header format, unsupported size";
  40647. }
  40648. lineIndex += (line.length + 1);
  40649. return {
  40650. height: height,
  40651. width: width,
  40652. dataPosition: lineIndex
  40653. };
  40654. };
  40655. /**
  40656. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  40657. * This RGBE texture needs to store the information as a panorama.
  40658. *
  40659. * More information on this format are available here:
  40660. * https://en.wikipedia.org/wiki/RGBE_image_format
  40661. *
  40662. * @param buffer The binary file stored in an array buffer.
  40663. * @param size The expected size of the extracted cubemap.
  40664. * @return The Cube Map information.
  40665. */
  40666. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40667. var uint8array = new Uint8Array(buffer);
  40668. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40669. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40670. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40671. return cubeMapData;
  40672. };
  40673. /**
  40674. * Returns the pixels data extracted from an RGBE texture.
  40675. * This pixels will be stored left to right up to down in the R G B order in one array.
  40676. *
  40677. * More information on this format are available here:
  40678. * https://en.wikipedia.org/wiki/RGBE_image_format
  40679. *
  40680. * @param uint8array The binary file stored in an array buffer.
  40681. * @param hdrInfo The header information of the file.
  40682. * @return The pixels data in RGB right to left up to down order.
  40683. */
  40684. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40685. // Keep for multi format supports.
  40686. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40687. };
  40688. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40689. var num_scanlines = hdrInfo.height;
  40690. var scanline_width = hdrInfo.width;
  40691. var a, b, c, d, count;
  40692. var dataIndex = hdrInfo.dataPosition;
  40693. var index = 0, endIndex = 0, i = 0;
  40694. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40695. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40696. // 3 channels of 4 bytes per pixel in float.
  40697. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40698. var resultArray = new Float32Array(resultBuffer);
  40699. // read in each successive scanline
  40700. while (num_scanlines > 0) {
  40701. a = uint8array[dataIndex++];
  40702. b = uint8array[dataIndex++];
  40703. c = uint8array[dataIndex++];
  40704. d = uint8array[dataIndex++];
  40705. if (a != 2 || b != 2 || (c & 0x80)) {
  40706. // this file is not run length encoded
  40707. throw "HDR Bad header format, not RLE";
  40708. }
  40709. if (((c << 8) | d) != scanline_width) {
  40710. throw "HDR Bad header format, wrong scan line width";
  40711. }
  40712. index = 0;
  40713. // read each of the four channels for the scanline into the buffer
  40714. for (i = 0; i < 4; i++) {
  40715. endIndex = (i + 1) * scanline_width;
  40716. while (index < endIndex) {
  40717. a = uint8array[dataIndex++];
  40718. b = uint8array[dataIndex++];
  40719. if (a > 128) {
  40720. // a run of the same value
  40721. count = a - 128;
  40722. if ((count == 0) || (count > endIndex - index)) {
  40723. throw "HDR Bad Format, bad scanline data (run)";
  40724. }
  40725. while (count-- > 0) {
  40726. scanLineArray[index++] = b;
  40727. }
  40728. }
  40729. else {
  40730. // a non-run
  40731. count = a;
  40732. if ((count == 0) || (count > endIndex - index)) {
  40733. throw "HDR Bad Format, bad scanline data (non-run)";
  40734. }
  40735. scanLineArray[index++] = b;
  40736. if (--count > 0) {
  40737. for (var j = 0; j < count; j++) {
  40738. scanLineArray[index++] = uint8array[dataIndex++];
  40739. }
  40740. }
  40741. }
  40742. }
  40743. }
  40744. // now convert data from buffer into floats
  40745. for (i = 0; i < scanline_width; i++) {
  40746. a = scanLineArray[i];
  40747. b = scanLineArray[i + scanline_width];
  40748. c = scanLineArray[i + 2 * scanline_width];
  40749. d = scanLineArray[i + 3 * scanline_width];
  40750. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40751. }
  40752. num_scanlines--;
  40753. }
  40754. return resultArray;
  40755. };
  40756. return HDRTools;
  40757. })();
  40758. Internals.HDRTools = HDRTools;
  40759. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40760. })(BABYLON || (BABYLON = {}));
  40761. var BABYLON;
  40762. (function (BABYLON) {
  40763. /**
  40764. * This represents a texture coming from an HDR input.
  40765. *
  40766. * The only supported format is currently panorama picture stored in RGBE format.
  40767. * Example of such files can be found on HDRLib: http://hdrlib.com/
  40768. */
  40769. var HDRCubeTexture = (function (_super) {
  40770. __extends(HDRCubeTexture, _super);
  40771. /**
  40772. * Instantiates an HDRTexture from the following parameters.
  40773. *
  40774. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  40775. * @param scene The scene the texture will be used in
  40776. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  40777. * @param noMipmap Forces to not generate the mipmap if true
  40778. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  40779. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  40780. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  40781. */
  40782. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  40783. if (noMipmap === void 0) { noMipmap = false; }
  40784. if (generateHarmonics === void 0) { generateHarmonics = true; }
  40785. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  40786. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  40787. _super.call(this, scene);
  40788. this._useInGammaSpace = false;
  40789. this._generateHarmonics = true;
  40790. /**
  40791. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  40792. */
  40793. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40794. /**
  40795. * The spherical polynomial data extracted from the texture.
  40796. */
  40797. this.sphericalPolynomial = null;
  40798. /**
  40799. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  40800. * This is usefull at run time to apply the good shader.
  40801. */
  40802. this.isPMREM = false;
  40803. this.name = url;
  40804. this.url = url;
  40805. this._noMipmap = noMipmap;
  40806. this.hasAlpha = false;
  40807. this._size = size;
  40808. this._useInGammaSpace = useInGammaSpace;
  40809. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  40810. this.isPMREM = this._usePMREMGenerator;
  40811. if (!url) {
  40812. return;
  40813. }
  40814. this._texture = this._getFromCache(url, noMipmap);
  40815. if (!this._texture) {
  40816. if (!scene.useDelayedTextureLoading) {
  40817. this.loadTexture();
  40818. }
  40819. else {
  40820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40821. }
  40822. }
  40823. this.isCube = true;
  40824. this._textureMatrix = BABYLON.Matrix.Identity();
  40825. }
  40826. HDRCubeTexture.prototype.loadTexture = function () {
  40827. var _this = this;
  40828. var callback = function (buffer) {
  40829. // Extract the raw linear data.
  40830. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  40831. // Generate harmonics if needed.
  40832. if (_this._generateHarmonics) {
  40833. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  40834. }
  40835. var results = [];
  40836. var byteArray = null;
  40837. // Create uintarray fallback.
  40838. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  40839. // 3 channels of 1 bytes per pixel in bytes.
  40840. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  40841. byteArray = new Uint8Array(byteBuffer);
  40842. }
  40843. // Push each faces.
  40844. for (var j = 0; j < 6; j++) {
  40845. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  40846. // If special cases.
  40847. if (_this._useInGammaSpace || byteArray) {
  40848. for (var i = 0; i < _this._size * _this._size; i++) {
  40849. // Put in gamma space if requested.
  40850. if (_this._useInGammaSpace) {
  40851. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  40852. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  40853. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  40854. }
  40855. // Convert to int texture for fallback.
  40856. if (byteArray) {
  40857. // R
  40858. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  40859. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  40860. // G
  40861. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  40862. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  40863. // B
  40864. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  40865. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  40866. }
  40867. }
  40868. }
  40869. results.push(dataFace);
  40870. }
  40871. return results;
  40872. };
  40873. var mipmapGenerator = null;
  40874. if (!this._noMipmap && this._usePMREMGenerator) {
  40875. mipmapGenerator = function (data) {
  40876. // Custom setup of the generator matching with the PBR shader values.
  40877. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  40878. return generator.filterCubeMap();
  40879. };
  40880. }
  40881. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  40882. };
  40883. HDRCubeTexture.prototype.clone = function () {
  40884. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  40885. // Base texture
  40886. newTexture.level = this.level;
  40887. newTexture.wrapU = this.wrapU;
  40888. newTexture.wrapV = this.wrapV;
  40889. newTexture.coordinatesIndex = this.coordinatesIndex;
  40890. newTexture.coordinatesMode = this.coordinatesMode;
  40891. return newTexture;
  40892. };
  40893. // Methods
  40894. HDRCubeTexture.prototype.delayLoad = function () {
  40895. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40896. return;
  40897. }
  40898. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40899. this._texture = this._getFromCache(this.url, this._noMipmap);
  40900. if (!this._texture) {
  40901. this.loadTexture();
  40902. }
  40903. };
  40904. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  40905. return this._textureMatrix;
  40906. };
  40907. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40908. var texture = null;
  40909. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40910. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  40911. texture.name = parsedTexture.name;
  40912. texture.hasAlpha = parsedTexture.hasAlpha;
  40913. texture.level = parsedTexture.level;
  40914. texture.coordinatesMode = parsedTexture.coordinatesMode;
  40915. }
  40916. return texture;
  40917. };
  40918. HDRCubeTexture.prototype.serialize = function () {
  40919. if (!this.name) {
  40920. return null;
  40921. }
  40922. var serializationObject = {};
  40923. serializationObject.name = this.name;
  40924. serializationObject.hasAlpha = this.hasAlpha;
  40925. serializationObject.isCube = true;
  40926. serializationObject.level = this.level;
  40927. serializationObject.size = this._size;
  40928. serializationObject.coordinatesMode = this.coordinatesMode;
  40929. serializationObject.useInGammaSpace = this._useInGammaSpace;
  40930. serializationObject.generateHarmonics = this._generateHarmonics;
  40931. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  40932. return serializationObject;
  40933. };
  40934. HDRCubeTexture._facesMapping = [
  40935. "right",
  40936. "up",
  40937. "front",
  40938. "left",
  40939. "down",
  40940. "back"
  40941. ];
  40942. return HDRCubeTexture;
  40943. })(BABYLON.BaseTexture);
  40944. BABYLON.HDRCubeTexture = HDRCubeTexture;
  40945. })(BABYLON || (BABYLON = {}));
  40946. var BABYLON;
  40947. (function (BABYLON) {
  40948. var Debug;
  40949. (function (Debug) {
  40950. /**
  40951. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  40952. */
  40953. var SkeletonViewer = (function () {
  40954. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  40955. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  40956. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  40957. this.skeleton = skeleton;
  40958. this.mesh = mesh;
  40959. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  40960. this.renderingGroupId = renderingGroupId;
  40961. this.color = BABYLON.Color3.White();
  40962. this._debugLines = [];
  40963. this._isEnabled = false;
  40964. this._scene = scene;
  40965. this.update();
  40966. this._renderFunction = this.update.bind(this);
  40967. }
  40968. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  40969. get: function () {
  40970. return this._isEnabled;
  40971. },
  40972. set: function (value) {
  40973. if (this._isEnabled === value) {
  40974. return;
  40975. }
  40976. this._isEnabled = value;
  40977. if (value) {
  40978. this._scene.registerBeforeRender(this._renderFunction);
  40979. }
  40980. else {
  40981. this._scene.unregisterBeforeRender(this._renderFunction);
  40982. }
  40983. },
  40984. enumerable: true,
  40985. configurable: true
  40986. });
  40987. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  40988. if (x === void 0) { x = 0; }
  40989. if (y === void 0) { y = 0; }
  40990. if (z === void 0) { z = 0; }
  40991. var tmat = BABYLON.Tmp.Matrix[0];
  40992. var parentBone = bone.getParent();
  40993. tmat.copyFrom(bone.getLocalMatrix());
  40994. if (x !== 0 || y !== 0 || z !== 0) {
  40995. var tmat2 = BABYLON.Tmp.Matrix[1];
  40996. BABYLON.Matrix.IdentityToRef(tmat2);
  40997. tmat2.m[12] = x;
  40998. tmat2.m[13] = y;
  40999. tmat2.m[14] = z;
  41000. tmat2.multiplyToRef(tmat, tmat);
  41001. }
  41002. if (parentBone) {
  41003. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  41004. }
  41005. tmat.multiplyToRef(meshMat, tmat);
  41006. position.x = tmat.m[12];
  41007. position.y = tmat.m[13];
  41008. position.z = tmat.m[14];
  41009. };
  41010. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  41011. var len = bones.length;
  41012. for (var i = 0; i < len; i++) {
  41013. var bone = bones[i];
  41014. var points = this._debugLines[i];
  41015. if (!points) {
  41016. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  41017. this._debugLines[i] = points;
  41018. }
  41019. this._getBonePosition(points[0], bone, meshMat);
  41020. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  41021. }
  41022. };
  41023. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  41024. var len = bones.length;
  41025. var boneNum = 0;
  41026. for (var i = len - 1; i >= 0; i--) {
  41027. var childBone = bones[i];
  41028. var parentBone = childBone.getParent();
  41029. if (!parentBone) {
  41030. continue;
  41031. }
  41032. var points = this._debugLines[boneNum];
  41033. if (!points) {
  41034. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  41035. this._debugLines[boneNum] = points;
  41036. }
  41037. this._getBonePosition(points[0], childBone, meshMat);
  41038. this._getBonePosition(points[1], parentBone, meshMat);
  41039. boneNum++;
  41040. }
  41041. };
  41042. SkeletonViewer.prototype.update = function () {
  41043. if (this.autoUpdateBonesMatrices) {
  41044. this._updateBoneMatrix(this.skeleton.bones[0]);
  41045. }
  41046. if (this.skeleton.bones[0].length === undefined) {
  41047. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  41048. }
  41049. else {
  41050. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  41051. }
  41052. if (!this._debugMesh) {
  41053. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  41054. this._debugMesh.renderingGroupId = this.renderingGroupId;
  41055. }
  41056. else {
  41057. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  41058. }
  41059. this._debugMesh.color = this.color;
  41060. };
  41061. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  41062. if (bone.getParent()) {
  41063. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  41064. }
  41065. var children = bone.children;
  41066. var len = children.length;
  41067. for (var i = 0; i < len; i++) {
  41068. this._updateBoneMatrix(children[i]);
  41069. }
  41070. };
  41071. SkeletonViewer.prototype.dispose = function () {
  41072. if (this._debugMesh) {
  41073. this.isEnabled = false;
  41074. this._debugMesh.dispose();
  41075. this._debugMesh = null;
  41076. }
  41077. };
  41078. return SkeletonViewer;
  41079. })();
  41080. Debug.SkeletonViewer = SkeletonViewer;
  41081. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  41082. })(BABYLON || (BABYLON = {}));
  41083. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\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) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_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\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<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\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\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\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>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\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{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#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(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform 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) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_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) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\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) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#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<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\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\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\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) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\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{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\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\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\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) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn 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\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\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\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\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) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform 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) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const 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{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform 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) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#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)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);\nfloat alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  41084. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(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 n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.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},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.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},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.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},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.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},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.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},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.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},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.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},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.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},n.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},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.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]},n.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]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.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},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.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},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.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},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=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.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},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=s.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,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}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],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.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},t.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)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*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,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*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*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.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},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],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],S=t.m[14],I=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*S,i[n+3]=r*T+o*F+s*P+e*I,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*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,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*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=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=t.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 h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);\ni.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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.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},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){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.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},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.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,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.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},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,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},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.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},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(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=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],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],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.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 s.Dot(n,i)+r},t}();t.Plane=u;var m=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,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(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=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;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,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=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 r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((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,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.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},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(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 n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.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},n.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]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.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},n.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},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var 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;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,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 s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.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=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(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=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.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=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  41085. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;\n}\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.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{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn 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)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn 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)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  41086. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  41087. module.exports = BABYLON;
  41088. };