babylon.max.js 2.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = 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.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. 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);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = 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.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. })();
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = function (other) {
  1310. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1311. };
  1312. Quaternion.prototype.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. 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));
  1551. };
  1552. return Quaternion;
  1553. })();
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. 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]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. 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);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. 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);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. 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);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. })();
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. })();
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. })();
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. })();
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. })();
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. })();
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. })();
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. 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);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. })();
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. })();
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. })();
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. 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)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. 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;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. 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)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. })();
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. })();
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. })();
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. })();
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. })();
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. })();
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. })();
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. var Observer = (function () {
  3078. function Observer(callback) {
  3079. this.callback = callback;
  3080. }
  3081. return Observer;
  3082. })();
  3083. BABYLON.Observer = Observer;
  3084. var Observable = (function () {
  3085. function Observable() {
  3086. this._observers = new Array();
  3087. }
  3088. /**
  3089. * Create a new Observer with the specified callback
  3090. * @param callback the callback that will be executed for that Observer
  3091. */
  3092. Observable.prototype.add = function (callback) {
  3093. if (!callback) {
  3094. return null;
  3095. }
  3096. var observer = new Observer(callback);
  3097. this._observers.push(observer);
  3098. return observer;
  3099. };
  3100. /**
  3101. * Remove an Observer from the Observable object
  3102. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3103. */
  3104. Observable.prototype.remove = function (observer) {
  3105. var index = this._observers.indexOf(observer);
  3106. if (index !== -1) {
  3107. this._observers.splice(index, 1);
  3108. return true;
  3109. }
  3110. return false;
  3111. };
  3112. /**
  3113. * Remove a callback from the Observable object
  3114. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3115. */
  3116. Observable.prototype.removeCallback = function (callback) {
  3117. for (var index = 0; index < this._observers.length; index++) {
  3118. if (this._observers[index].callback === callback) {
  3119. this._observers.splice(index, 1);
  3120. return true;
  3121. }
  3122. }
  3123. return false;
  3124. };
  3125. /**
  3126. * Notify all Observers by calling their respective callback with the given data
  3127. * @param eventData
  3128. */
  3129. Observable.prototype.notifyObservers = function (eventData) {
  3130. this._observers.forEach(function (observer) {
  3131. observer.callback(eventData);
  3132. });
  3133. };
  3134. /**
  3135. * Clear the list of observers
  3136. */
  3137. Observable.prototype.clear = function () {
  3138. this._observers = new Array();
  3139. };
  3140. /**
  3141. * Clone the current observable
  3142. */
  3143. Observable.prototype.clone = function () {
  3144. var result = new Observable();
  3145. result._observers = this._observers.slice(0);
  3146. return result;
  3147. };
  3148. return Observable;
  3149. })();
  3150. BABYLON.Observable = Observable;
  3151. })(BABYLON || (BABYLON = {}));
  3152. var BABYLON;
  3153. (function (BABYLON) {
  3154. var Database = (function () {
  3155. function Database(urlToScene, callbackManifestChecked) {
  3156. // Handling various flavors of prefixed version of IndexedDB
  3157. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3158. this.callbackManifestChecked = callbackManifestChecked;
  3159. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3160. this.db = null;
  3161. this.enableSceneOffline = false;
  3162. this.enableTexturesOffline = false;
  3163. this.manifestVersionFound = 0;
  3164. this.mustUpdateRessources = false;
  3165. this.hasReachedQuota = false;
  3166. if (!Database.IDBStorageEnabled) {
  3167. this.callbackManifestChecked(true);
  3168. }
  3169. else {
  3170. this.checkManifestFile();
  3171. }
  3172. }
  3173. Database.prototype.checkManifestFile = function () {
  3174. var _this = this;
  3175. function noManifestFile() {
  3176. that.enableSceneOffline = false;
  3177. that.enableTexturesOffline = false;
  3178. that.callbackManifestChecked(false);
  3179. }
  3180. var that = this;
  3181. var timeStampUsed = false;
  3182. var manifestURL = this.currentSceneUrl + ".manifest";
  3183. var xhr = new XMLHttpRequest();
  3184. if (navigator.onLine) {
  3185. // Adding a timestamp to by-pass browsers' cache
  3186. timeStampUsed = true;
  3187. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3188. }
  3189. xhr.open("GET", manifestURL, true);
  3190. xhr.addEventListener("load", function () {
  3191. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3192. try {
  3193. var manifestFile = JSON.parse(xhr.response);
  3194. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3195. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3196. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3197. _this.manifestVersionFound = manifestFile.version;
  3198. }
  3199. if (_this.callbackManifestChecked) {
  3200. _this.callbackManifestChecked(true);
  3201. }
  3202. }
  3203. catch (ex) {
  3204. noManifestFile();
  3205. }
  3206. }
  3207. else {
  3208. noManifestFile();
  3209. }
  3210. }, false);
  3211. xhr.addEventListener("error", function (event) {
  3212. if (timeStampUsed) {
  3213. timeStampUsed = false;
  3214. // Let's retry without the timeStamp
  3215. // It could fail when coupled with HTML5 Offline API
  3216. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3217. xhr.open("GET", retryManifestURL, true);
  3218. xhr.send();
  3219. }
  3220. else {
  3221. noManifestFile();
  3222. }
  3223. }, false);
  3224. try {
  3225. xhr.send();
  3226. }
  3227. catch (ex) {
  3228. BABYLON.Tools.Error("Error on XHR send request.");
  3229. that.callbackManifestChecked(false);
  3230. }
  3231. };
  3232. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3233. var _this = this;
  3234. function handleError() {
  3235. that.isSupported = false;
  3236. if (errorCallback)
  3237. errorCallback();
  3238. }
  3239. var that = this;
  3240. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3241. // Your browser doesn't support IndexedDB
  3242. this.isSupported = false;
  3243. if (errorCallback)
  3244. errorCallback();
  3245. }
  3246. else {
  3247. // If the DB hasn't been opened or created yet
  3248. if (!this.db) {
  3249. this.hasReachedQuota = false;
  3250. this.isSupported = true;
  3251. var request = this.idbFactory.open("babylonjs", 1);
  3252. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3253. request.onerror = function (event) {
  3254. handleError();
  3255. };
  3256. // executes when a version change transaction cannot complete due to other active transactions
  3257. request.onblocked = function (event) {
  3258. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3259. handleError();
  3260. };
  3261. // DB has been opened successfully
  3262. request.onsuccess = function (event) {
  3263. _this.db = request.result;
  3264. successCallback();
  3265. };
  3266. // Initialization of the DB. Creating Scenes & Textures stores
  3267. request.onupgradeneeded = function (event) {
  3268. _this.db = (event.target).result;
  3269. try {
  3270. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3271. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3272. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3273. }
  3274. catch (ex) {
  3275. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3276. handleError();
  3277. }
  3278. };
  3279. }
  3280. else {
  3281. if (successCallback)
  3282. successCallback();
  3283. }
  3284. }
  3285. };
  3286. Database.prototype.loadImageFromDB = function (url, image) {
  3287. var _this = this;
  3288. var completeURL = Database.ReturnFullUrlLocation(url);
  3289. var saveAndLoadImage = function () {
  3290. if (!_this.hasReachedQuota && _this.db !== null) {
  3291. // the texture is not yet in the DB, let's try to save it
  3292. _this._saveImageIntoDBAsync(completeURL, image);
  3293. }
  3294. else {
  3295. image.src = url;
  3296. }
  3297. };
  3298. if (!this.mustUpdateRessources) {
  3299. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3300. }
  3301. else {
  3302. saveAndLoadImage();
  3303. }
  3304. };
  3305. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3306. if (this.isSupported && this.db !== null) {
  3307. var texture;
  3308. var transaction = this.db.transaction(["textures"]);
  3309. transaction.onabort = function (event) {
  3310. image.src = url;
  3311. };
  3312. transaction.oncomplete = function (event) {
  3313. var blobTextureURL;
  3314. if (texture) {
  3315. var URL = window.URL || window.webkitURL;
  3316. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3317. image.onerror = function () {
  3318. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3319. image.src = url;
  3320. };
  3321. image.src = blobTextureURL;
  3322. }
  3323. else {
  3324. notInDBCallback();
  3325. }
  3326. };
  3327. var getRequest = transaction.objectStore("textures").get(url);
  3328. getRequest.onsuccess = function (event) {
  3329. texture = (event.target).result;
  3330. };
  3331. getRequest.onerror = function (event) {
  3332. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3333. image.src = url;
  3334. };
  3335. }
  3336. else {
  3337. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3338. image.src = url;
  3339. }
  3340. };
  3341. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3342. var _this = this;
  3343. if (this.isSupported) {
  3344. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3345. var generateBlobUrl = function () {
  3346. var blobTextureURL;
  3347. if (blob) {
  3348. var URL = window.URL || window.webkitURL;
  3349. try {
  3350. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3351. }
  3352. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3353. catch (ex) {
  3354. blobTextureURL = URL.createObjectURL(blob);
  3355. }
  3356. }
  3357. image.src = blobTextureURL;
  3358. };
  3359. if (Database.IsUASupportingBlobStorage) {
  3360. var xhr = new XMLHttpRequest(), blob;
  3361. xhr.open("GET", url, true);
  3362. xhr.responseType = "blob";
  3363. xhr.addEventListener("load", function () {
  3364. if (xhr.status === 200) {
  3365. // Blob as response (XHR2)
  3366. blob = xhr.response;
  3367. var transaction = _this.db.transaction(["textures"], "readwrite");
  3368. // the transaction could abort because of a QuotaExceededError error
  3369. transaction.onabort = function (event) {
  3370. try {
  3371. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3372. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3373. this.hasReachedQuota = true;
  3374. }
  3375. }
  3376. catch (ex) { }
  3377. generateBlobUrl();
  3378. };
  3379. transaction.oncomplete = function (event) {
  3380. generateBlobUrl();
  3381. };
  3382. var newTexture = { textureUrl: url, data: blob };
  3383. try {
  3384. // Put the blob into the dabase
  3385. var addRequest = transaction.objectStore("textures").put(newTexture);
  3386. addRequest.onsuccess = function (event) {
  3387. };
  3388. addRequest.onerror = function (event) {
  3389. generateBlobUrl();
  3390. };
  3391. }
  3392. catch (ex) {
  3393. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3394. if (ex.code === 25) {
  3395. Database.IsUASupportingBlobStorage = false;
  3396. }
  3397. image.src = url;
  3398. }
  3399. }
  3400. else {
  3401. image.src = url;
  3402. }
  3403. }, false);
  3404. xhr.addEventListener("error", function (event) {
  3405. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3406. image.src = url;
  3407. }, false);
  3408. xhr.send();
  3409. }
  3410. else {
  3411. image.src = url;
  3412. }
  3413. }
  3414. else {
  3415. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3416. image.src = url;
  3417. }
  3418. };
  3419. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3420. var _this = this;
  3421. var updateVersion = function (event) {
  3422. // the version is not yet in the DB or we need to update it
  3423. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3424. };
  3425. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3426. };
  3427. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3428. var _this = this;
  3429. if (this.isSupported) {
  3430. var version;
  3431. try {
  3432. var transaction = this.db.transaction(["versions"]);
  3433. transaction.oncomplete = function (event) {
  3434. if (version) {
  3435. // If the version in the JSON file is > than the version in DB
  3436. if (_this.manifestVersionFound > version.data) {
  3437. _this.mustUpdateRessources = true;
  3438. updateInDBCallback();
  3439. }
  3440. else {
  3441. callback(version.data);
  3442. }
  3443. }
  3444. else {
  3445. _this.mustUpdateRessources = true;
  3446. updateInDBCallback();
  3447. }
  3448. };
  3449. transaction.onabort = function (event) {
  3450. callback(-1);
  3451. };
  3452. var getRequest = transaction.objectStore("versions").get(url);
  3453. getRequest.onsuccess = function (event) {
  3454. version = (event.target).result;
  3455. };
  3456. getRequest.onerror = function (event) {
  3457. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3458. callback(-1);
  3459. };
  3460. }
  3461. catch (ex) {
  3462. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3463. callback(-1);
  3464. }
  3465. }
  3466. else {
  3467. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3468. callback(-1);
  3469. }
  3470. };
  3471. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3472. var _this = this;
  3473. if (this.isSupported && !this.hasReachedQuota) {
  3474. try {
  3475. // Open a transaction to the database
  3476. var transaction = this.db.transaction(["versions"], "readwrite");
  3477. // the transaction could abort because of a QuotaExceededError error
  3478. transaction.onabort = function (event) {
  3479. try {
  3480. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3481. _this.hasReachedQuota = true;
  3482. }
  3483. }
  3484. catch (ex) { }
  3485. callback(-1);
  3486. };
  3487. transaction.oncomplete = function (event) {
  3488. callback(_this.manifestVersionFound);
  3489. };
  3490. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3491. // Put the scene into the database
  3492. var addRequest = transaction.objectStore("versions").put(newVersion);
  3493. addRequest.onsuccess = function (event) {
  3494. };
  3495. addRequest.onerror = function (event) {
  3496. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3497. };
  3498. }
  3499. catch (ex) {
  3500. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3501. callback(-1);
  3502. }
  3503. }
  3504. else {
  3505. callback(-1);
  3506. }
  3507. };
  3508. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3509. var _this = this;
  3510. var completeUrl = Database.ReturnFullUrlLocation(url);
  3511. var saveAndLoadFile = function (event) {
  3512. // the scene is not yet in the DB, let's try to save it
  3513. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3514. };
  3515. this._checkVersionFromDB(completeUrl, function (version) {
  3516. if (version !== -1) {
  3517. if (!_this.mustUpdateRessources) {
  3518. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3519. }
  3520. else {
  3521. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3522. }
  3523. }
  3524. else {
  3525. errorCallback();
  3526. }
  3527. });
  3528. };
  3529. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3530. if (this.isSupported) {
  3531. var targetStore;
  3532. if (url.indexOf(".babylon") !== -1) {
  3533. targetStore = "scenes";
  3534. }
  3535. else {
  3536. targetStore = "textures";
  3537. }
  3538. var file;
  3539. var transaction = this.db.transaction([targetStore]);
  3540. transaction.oncomplete = function (event) {
  3541. if (file) {
  3542. callback(file.data);
  3543. }
  3544. else {
  3545. notInDBCallback();
  3546. }
  3547. };
  3548. transaction.onabort = function (event) {
  3549. notInDBCallback();
  3550. };
  3551. var getRequest = transaction.objectStore(targetStore).get(url);
  3552. getRequest.onsuccess = function (event) {
  3553. file = (event.target).result;
  3554. };
  3555. getRequest.onerror = function (event) {
  3556. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3557. notInDBCallback();
  3558. };
  3559. }
  3560. else {
  3561. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3562. callback();
  3563. }
  3564. };
  3565. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3566. var _this = this;
  3567. if (this.isSupported) {
  3568. var targetStore;
  3569. if (url.indexOf(".babylon") !== -1) {
  3570. targetStore = "scenes";
  3571. }
  3572. else {
  3573. targetStore = "textures";
  3574. }
  3575. // Create XHR
  3576. var xhr = new XMLHttpRequest(), fileData;
  3577. xhr.open("GET", url, true);
  3578. if (useArrayBuffer) {
  3579. xhr.responseType = "arraybuffer";
  3580. }
  3581. xhr.onprogress = progressCallback;
  3582. xhr.addEventListener("load", function () {
  3583. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3584. // Blob as response (XHR2)
  3585. //fileData = xhr.responseText;
  3586. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3587. if (!_this.hasReachedQuota) {
  3588. // Open a transaction to the database
  3589. var transaction = _this.db.transaction([targetStore], "readwrite");
  3590. // the transaction could abort because of a QuotaExceededError error
  3591. transaction.onabort = function (event) {
  3592. try {
  3593. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3594. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3595. this.hasReachedQuota = true;
  3596. }
  3597. }
  3598. catch (ex) { }
  3599. callback(fileData);
  3600. };
  3601. transaction.oncomplete = function (event) {
  3602. callback(fileData);
  3603. };
  3604. var newFile;
  3605. if (targetStore === "scenes") {
  3606. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3607. }
  3608. else {
  3609. newFile = { textureUrl: url, data: fileData };
  3610. }
  3611. try {
  3612. // Put the scene into the database
  3613. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3614. addRequest.onsuccess = function (event) {
  3615. };
  3616. addRequest.onerror = function (event) {
  3617. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3618. };
  3619. }
  3620. catch (ex) {
  3621. callback(fileData);
  3622. }
  3623. }
  3624. else {
  3625. callback(fileData);
  3626. }
  3627. }
  3628. else {
  3629. callback();
  3630. }
  3631. }, false);
  3632. xhr.addEventListener("error", function (event) {
  3633. BABYLON.Tools.Error("error on XHR request.");
  3634. callback();
  3635. }, false);
  3636. xhr.send();
  3637. }
  3638. else {
  3639. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3640. callback();
  3641. }
  3642. };
  3643. Database.IsUASupportingBlobStorage = true;
  3644. Database.IDBStorageEnabled = true;
  3645. Database.parseURL = function (url) {
  3646. var a = document.createElement('a');
  3647. a.href = url;
  3648. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3649. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3650. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3651. return absLocation;
  3652. };
  3653. Database.ReturnFullUrlLocation = function (url) {
  3654. if (url.indexOf("http:/") === -1) {
  3655. return (Database.parseURL(window.location.href) + url);
  3656. }
  3657. else {
  3658. return url;
  3659. }
  3660. };
  3661. return Database;
  3662. })();
  3663. BABYLON.Database = Database;
  3664. })(BABYLON || (BABYLON = {}));
  3665. var BABYLON;
  3666. (function (BABYLON) {
  3667. var Internals;
  3668. (function (Internals) {
  3669. /*
  3670. * Based on jsTGALoader - Javascript loader for TGA file
  3671. * By Vincent Thibault
  3672. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3673. */
  3674. var TGATools = (function () {
  3675. function TGATools() {
  3676. }
  3677. TGATools.GetTGAHeader = function (data) {
  3678. var offset = 0;
  3679. var header = {
  3680. id_length: data[offset++],
  3681. colormap_type: data[offset++],
  3682. image_type: data[offset++],
  3683. colormap_index: data[offset++] | data[offset++] << 8,
  3684. colormap_length: data[offset++] | data[offset++] << 8,
  3685. colormap_size: data[offset++],
  3686. origin: [
  3687. data[offset++] | data[offset++] << 8,
  3688. data[offset++] | data[offset++] << 8
  3689. ],
  3690. width: data[offset++] | data[offset++] << 8,
  3691. height: data[offset++] | data[offset++] << 8,
  3692. pixel_size: data[offset++],
  3693. flags: data[offset++]
  3694. };
  3695. return header;
  3696. };
  3697. TGATools.UploadContent = function (gl, data) {
  3698. // Not enough data to contain header ?
  3699. if (data.length < 19) {
  3700. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3701. return;
  3702. }
  3703. // Read Header
  3704. var offset = 18;
  3705. var header = TGATools.GetTGAHeader(data);
  3706. // Assume it's a valid Targa file.
  3707. if (header.id_length + offset > data.length) {
  3708. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3709. return;
  3710. }
  3711. // Skip not needed data
  3712. offset += header.id_length;
  3713. var use_rle = false;
  3714. var use_pal = false;
  3715. var use_rgb = false;
  3716. var use_grey = false;
  3717. // Get some informations.
  3718. switch (header.image_type) {
  3719. case TGATools._TYPE_RLE_INDEXED:
  3720. use_rle = true;
  3721. case TGATools._TYPE_INDEXED:
  3722. use_pal = true;
  3723. break;
  3724. case TGATools._TYPE_RLE_RGB:
  3725. use_rle = true;
  3726. case TGATools._TYPE_RGB:
  3727. use_rgb = true;
  3728. break;
  3729. case TGATools._TYPE_RLE_GREY:
  3730. use_rle = true;
  3731. case TGATools._TYPE_GREY:
  3732. use_grey = true;
  3733. break;
  3734. }
  3735. var pixel_data;
  3736. var numAlphaBits = header.flags & 0xf;
  3737. var pixel_size = header.pixel_size >> 3;
  3738. var pixel_total = header.width * header.height * pixel_size;
  3739. // Read palettes
  3740. var palettes;
  3741. if (use_pal) {
  3742. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3743. }
  3744. // Read LRE
  3745. if (use_rle) {
  3746. pixel_data = new Uint8Array(pixel_total);
  3747. var c, count, i;
  3748. var localOffset = 0;
  3749. var pixels = new Uint8Array(pixel_size);
  3750. while (offset < pixel_total && localOffset < pixel_total) {
  3751. c = data[offset++];
  3752. count = (c & 0x7f) + 1;
  3753. // RLE pixels
  3754. if (c & 0x80) {
  3755. // Bind pixel tmp array
  3756. for (i = 0; i < pixel_size; ++i) {
  3757. pixels[i] = data[offset++];
  3758. }
  3759. // Copy pixel array
  3760. for (i = 0; i < count; ++i) {
  3761. pixel_data.set(pixels, localOffset + i * pixel_size);
  3762. }
  3763. localOffset += pixel_size * count;
  3764. }
  3765. else {
  3766. count *= pixel_size;
  3767. for (i = 0; i < count; ++i) {
  3768. pixel_data[localOffset + i] = data[offset++];
  3769. }
  3770. localOffset += count;
  3771. }
  3772. }
  3773. }
  3774. else {
  3775. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3776. }
  3777. // Load to texture
  3778. var x_start, y_start, x_step, y_step, y_end, x_end;
  3779. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3780. default:
  3781. case TGATools._ORIGIN_UL:
  3782. x_start = 0;
  3783. x_step = 1;
  3784. x_end = header.width;
  3785. y_start = 0;
  3786. y_step = 1;
  3787. y_end = header.height;
  3788. break;
  3789. case TGATools._ORIGIN_BL:
  3790. x_start = 0;
  3791. x_step = 1;
  3792. x_end = header.width;
  3793. y_start = header.height - 1;
  3794. y_step = -1;
  3795. y_end = -1;
  3796. break;
  3797. case TGATools._ORIGIN_UR:
  3798. x_start = header.width - 1;
  3799. x_step = -1;
  3800. x_end = -1;
  3801. y_start = 0;
  3802. y_step = 1;
  3803. y_end = header.height;
  3804. break;
  3805. case TGATools._ORIGIN_BR:
  3806. x_start = header.width - 1;
  3807. x_step = -1;
  3808. x_end = -1;
  3809. y_start = header.height - 1;
  3810. y_step = -1;
  3811. y_end = -1;
  3812. break;
  3813. }
  3814. // Load the specify method
  3815. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3816. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3817. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3818. };
  3819. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3820. var image = pixel_data, colormap = palettes;
  3821. var width = header.width, height = header.height;
  3822. var color, i = 0, x, y;
  3823. var imageData = new Uint8Array(width * height * 4);
  3824. for (y = y_start; y !== y_end; y += y_step) {
  3825. for (x = x_start; x !== x_end; x += x_step, i++) {
  3826. color = image[i];
  3827. imageData[(x + width * y) * 4 + 3] = 255;
  3828. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3829. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3830. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3831. }
  3832. }
  3833. return imageData;
  3834. };
  3835. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3836. var image = pixel_data;
  3837. var width = header.width, height = header.height;
  3838. var color, i = 0, x, y;
  3839. var imageData = new Uint8Array(width * height * 4);
  3840. for (y = y_start; y !== y_end; y += y_step) {
  3841. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3842. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3843. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3844. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3845. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3846. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3847. }
  3848. }
  3849. return imageData;
  3850. };
  3851. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3852. var image = pixel_data;
  3853. var width = header.width, height = header.height;
  3854. var i = 0, x, y;
  3855. var imageData = new Uint8Array(width * height * 4);
  3856. for (y = y_start; y !== y_end; y += y_step) {
  3857. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3858. imageData[(x + width * y) * 4 + 3] = 255;
  3859. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3860. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3861. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3862. }
  3863. }
  3864. return imageData;
  3865. };
  3866. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3867. var image = pixel_data;
  3868. var width = header.width, height = header.height;
  3869. var i = 0, x, y;
  3870. var imageData = new Uint8Array(width * height * 4);
  3871. for (y = y_start; y !== y_end; y += y_step) {
  3872. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3873. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3874. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3875. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3876. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3877. }
  3878. }
  3879. return imageData;
  3880. };
  3881. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3882. var image = pixel_data;
  3883. var width = header.width, height = header.height;
  3884. var color, i = 0, x, y;
  3885. var imageData = new Uint8Array(width * height * 4);
  3886. for (y = y_start; y !== y_end; y += y_step) {
  3887. for (x = x_start; x !== x_end; x += x_step, i++) {
  3888. color = image[i];
  3889. imageData[(x + width * y) * 4 + 0] = color;
  3890. imageData[(x + width * y) * 4 + 1] = color;
  3891. imageData[(x + width * y) * 4 + 2] = color;
  3892. imageData[(x + width * y) * 4 + 3] = 255;
  3893. }
  3894. }
  3895. return imageData;
  3896. };
  3897. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3898. var image = pixel_data;
  3899. var width = header.width, height = header.height;
  3900. var i = 0, x, y;
  3901. var imageData = new Uint8Array(width * height * 4);
  3902. for (y = y_start; y !== y_end; y += y_step) {
  3903. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3904. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3905. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3906. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3907. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3908. }
  3909. }
  3910. return imageData;
  3911. };
  3912. TGATools._TYPE_NO_DATA = 0;
  3913. TGATools._TYPE_INDEXED = 1;
  3914. TGATools._TYPE_RGB = 2;
  3915. TGATools._TYPE_GREY = 3;
  3916. TGATools._TYPE_RLE_INDEXED = 9;
  3917. TGATools._TYPE_RLE_RGB = 10;
  3918. TGATools._TYPE_RLE_GREY = 11;
  3919. TGATools._ORIGIN_MASK = 0x30;
  3920. TGATools._ORIGIN_SHIFT = 0x04;
  3921. TGATools._ORIGIN_BL = 0x00;
  3922. TGATools._ORIGIN_BR = 0x01;
  3923. TGATools._ORIGIN_UL = 0x02;
  3924. TGATools._ORIGIN_UR = 0x03;
  3925. return TGATools;
  3926. })();
  3927. Internals.TGATools = TGATools;
  3928. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3929. })(BABYLON || (BABYLON = {}));
  3930. var BABYLON;
  3931. (function (BABYLON) {
  3932. var SmartArray = (function () {
  3933. function SmartArray(capacity) {
  3934. this.length = 0;
  3935. this._duplicateId = 0;
  3936. this.data = new Array(capacity);
  3937. this._id = SmartArray._GlobalId++;
  3938. }
  3939. SmartArray.prototype.push = function (value) {
  3940. this.data[this.length++] = value;
  3941. if (this.length > this.data.length) {
  3942. this.data.length *= 2;
  3943. }
  3944. if (!value.__smartArrayFlags) {
  3945. value.__smartArrayFlags = {};
  3946. }
  3947. value.__smartArrayFlags[this._id] = this._duplicateId;
  3948. };
  3949. SmartArray.prototype.pushNoDuplicate = function (value) {
  3950. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3951. return;
  3952. }
  3953. this.push(value);
  3954. };
  3955. SmartArray.prototype.sort = function (compareFn) {
  3956. this.data.sort(compareFn);
  3957. };
  3958. SmartArray.prototype.reset = function () {
  3959. this.length = 0;
  3960. this._duplicateId++;
  3961. };
  3962. SmartArray.prototype.concat = function (array) {
  3963. if (array.length === 0) {
  3964. return;
  3965. }
  3966. if (this.length + array.length > this.data.length) {
  3967. this.data.length = (this.length + array.length) * 2;
  3968. }
  3969. for (var index = 0; index < array.length; index++) {
  3970. this.data[this.length++] = (array.data || array)[index];
  3971. }
  3972. };
  3973. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3974. if (array.length === 0) {
  3975. return;
  3976. }
  3977. if (this.length + array.length > this.data.length) {
  3978. this.data.length = (this.length + array.length) * 2;
  3979. }
  3980. for (var index = 0; index < array.length; index++) {
  3981. var item = (array.data || array)[index];
  3982. this.pushNoDuplicate(item);
  3983. }
  3984. };
  3985. SmartArray.prototype.indexOf = function (value) {
  3986. var position = this.data.indexOf(value);
  3987. if (position >= this.length) {
  3988. return -1;
  3989. }
  3990. return position;
  3991. };
  3992. // Statics
  3993. SmartArray._GlobalId = 0;
  3994. return SmartArray;
  3995. })();
  3996. BABYLON.SmartArray = SmartArray;
  3997. })(BABYLON || (BABYLON = {}));
  3998. var BABYLON;
  3999. (function (BABYLON) {
  4000. var SmartCollection = (function () {
  4001. function SmartCollection(capacity) {
  4002. if (capacity === void 0) { capacity = 10; }
  4003. this.count = 0;
  4004. this._initialCapacity = capacity;
  4005. this.items = {};
  4006. this._keys = new Array(this._initialCapacity);
  4007. }
  4008. SmartCollection.prototype.add = function (key, item) {
  4009. if (this.items[key] != undefined) {
  4010. return -1;
  4011. }
  4012. this.items[key] = item;
  4013. //literal keys are always strings, but we keep source type of key in _keys array
  4014. this._keys[this.count++] = key;
  4015. if (this.count > this._keys.length) {
  4016. this._keys.length *= 2;
  4017. }
  4018. return this.count;
  4019. };
  4020. SmartCollection.prototype.remove = function (key) {
  4021. if (this.items[key] == undefined) {
  4022. return -1;
  4023. }
  4024. return this.removeItemOfIndex(this.indexOf(key));
  4025. };
  4026. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4027. if (index < this.count && index > -1) {
  4028. delete this.items[this._keys[index]];
  4029. //here, shifting by hand is better optimised than .splice
  4030. while (index < this.count) {
  4031. this._keys[index] = this._keys[index + 1];
  4032. index++;
  4033. }
  4034. }
  4035. else {
  4036. return -1;
  4037. }
  4038. return --this.count;
  4039. };
  4040. SmartCollection.prototype.indexOf = function (key) {
  4041. for (var i = 0; i !== this.count; i++) {
  4042. if (this._keys[i] === key) {
  4043. return i;
  4044. }
  4045. }
  4046. return -1;
  4047. };
  4048. SmartCollection.prototype.item = function (key) {
  4049. return this.items[key];
  4050. };
  4051. SmartCollection.prototype.getAllKeys = function () {
  4052. if (this.count > 0) {
  4053. var keys = new Array(this.count);
  4054. for (var i = 0; i < this.count; i++) {
  4055. keys[i] = this._keys[i];
  4056. }
  4057. return keys;
  4058. }
  4059. else {
  4060. return undefined;
  4061. }
  4062. };
  4063. SmartCollection.prototype.getKeyByIndex = function (index) {
  4064. if (index < this.count && index > -1) {
  4065. return this._keys[index];
  4066. }
  4067. else {
  4068. return undefined;
  4069. }
  4070. };
  4071. SmartCollection.prototype.getItemByIndex = function (index) {
  4072. if (index < this.count && index > -1) {
  4073. return this.items[this._keys[index]];
  4074. }
  4075. else {
  4076. return undefined;
  4077. }
  4078. };
  4079. SmartCollection.prototype.empty = function () {
  4080. if (this.count > 0) {
  4081. this.count = 0;
  4082. this.items = {};
  4083. this._keys = new Array(this._initialCapacity);
  4084. }
  4085. };
  4086. SmartCollection.prototype.forEach = function (block) {
  4087. var key;
  4088. for (key in this.items) {
  4089. if (this.items.hasOwnProperty(key)) {
  4090. block(this.items[key]);
  4091. }
  4092. }
  4093. };
  4094. return SmartCollection;
  4095. })();
  4096. BABYLON.SmartCollection = SmartCollection;
  4097. })(BABYLON || (BABYLON = {}));
  4098. var BABYLON;
  4099. (function (BABYLON) {
  4100. // Screenshots
  4101. var screenshotCanvas;
  4102. var cloneValue = function (source, destinationObject) {
  4103. if (!source)
  4104. return null;
  4105. if (source instanceof BABYLON.Mesh) {
  4106. return null;
  4107. }
  4108. if (source instanceof BABYLON.SubMesh) {
  4109. return source.clone(destinationObject);
  4110. }
  4111. else if (source.clone) {
  4112. return source.clone();
  4113. }
  4114. return null;
  4115. };
  4116. var Tools = (function () {
  4117. function Tools() {
  4118. }
  4119. Tools.Instantiate = function (className) {
  4120. var arr = className.split(".");
  4121. var fn = (window || this);
  4122. for (var i = 0, len = arr.length; i < len; i++) {
  4123. fn = fn[arr[i]];
  4124. }
  4125. if (typeof fn !== "function") {
  4126. return null;
  4127. }
  4128. return fn;
  4129. };
  4130. Tools.SetImmediate = function (action) {
  4131. if (window.setImmediate) {
  4132. window.setImmediate(action);
  4133. }
  4134. else {
  4135. setTimeout(action, 1);
  4136. }
  4137. };
  4138. Tools.IsExponentOfTwo = function (value) {
  4139. var count = 1;
  4140. do {
  4141. count *= 2;
  4142. } while (count < value);
  4143. return count === value;
  4144. };
  4145. Tools.GetExponentOfTwo = function (value, max) {
  4146. var count = 1;
  4147. do {
  4148. count *= 2;
  4149. } while (count < value);
  4150. if (count > max)
  4151. count = max;
  4152. return count;
  4153. };
  4154. Tools.GetFilename = function (path) {
  4155. var index = path.lastIndexOf("/");
  4156. if (index < 0)
  4157. return path;
  4158. return path.substring(index + 1);
  4159. };
  4160. Tools.GetDOMTextContent = function (element) {
  4161. var result = "";
  4162. var child = element.firstChild;
  4163. while (child) {
  4164. if (child.nodeType === 3) {
  4165. result += child.textContent;
  4166. }
  4167. child = child.nextSibling;
  4168. }
  4169. return result;
  4170. };
  4171. Tools.ToDegrees = function (angle) {
  4172. return angle * 180 / Math.PI;
  4173. };
  4174. Tools.ToRadians = function (angle) {
  4175. return angle * Math.PI / 180;
  4176. };
  4177. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4178. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4179. var output = "";
  4180. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4181. var i = 0;
  4182. var bytes = new Uint8Array(buffer);
  4183. while (i < bytes.length) {
  4184. chr1 = bytes[i++];
  4185. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4186. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4187. enc1 = chr1 >> 2;
  4188. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4189. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4190. enc4 = chr3 & 63;
  4191. if (isNaN(chr2)) {
  4192. enc3 = enc4 = 64;
  4193. }
  4194. else if (isNaN(chr3)) {
  4195. enc4 = 64;
  4196. }
  4197. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4198. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4199. }
  4200. return "data:image/png;base64," + output;
  4201. };
  4202. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4205. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4206. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4209. }
  4210. return {
  4211. minimum: minimum,
  4212. maximum: maximum
  4213. };
  4214. };
  4215. Tools.ExtractMinAndMax = function (positions, start, count) {
  4216. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4217. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4218. for (var index = start; index < start + count; index++) {
  4219. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4220. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4221. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4222. }
  4223. return {
  4224. minimum: minimum,
  4225. maximum: maximum
  4226. };
  4227. };
  4228. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4229. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4230. return undefined;
  4231. return Array.isArray(obj) ? obj : [obj];
  4232. };
  4233. // Misc.
  4234. Tools.GetPointerPrefix = function () {
  4235. var eventPrefix = "pointer";
  4236. // Check if pointer events are supported
  4237. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4238. eventPrefix = "mouse";
  4239. }
  4240. return eventPrefix;
  4241. };
  4242. Tools.QueueNewFrame = function (func) {
  4243. if (window.requestAnimationFrame)
  4244. window.requestAnimationFrame(func);
  4245. else if (window.msRequestAnimationFrame)
  4246. window.msRequestAnimationFrame(func);
  4247. else if (window.webkitRequestAnimationFrame)
  4248. window.webkitRequestAnimationFrame(func);
  4249. else if (window.mozRequestAnimationFrame)
  4250. window.mozRequestAnimationFrame(func);
  4251. else if (window.oRequestAnimationFrame)
  4252. window.oRequestAnimationFrame(func);
  4253. else {
  4254. window.setTimeout(func, 16);
  4255. }
  4256. };
  4257. Tools.RequestFullscreen = function (element) {
  4258. if (element.requestFullscreen)
  4259. element.requestFullscreen();
  4260. else if (element.msRequestFullscreen)
  4261. element.msRequestFullscreen();
  4262. else if (element.webkitRequestFullscreen)
  4263. element.webkitRequestFullscreen();
  4264. else if (element.mozRequestFullScreen)
  4265. element.mozRequestFullScreen();
  4266. };
  4267. Tools.ExitFullscreen = function () {
  4268. if (document.exitFullscreen) {
  4269. document.exitFullscreen();
  4270. }
  4271. else if (document.mozCancelFullScreen) {
  4272. document.mozCancelFullScreen();
  4273. }
  4274. else if (document.webkitCancelFullScreen) {
  4275. document.webkitCancelFullScreen();
  4276. }
  4277. else if (document.msCancelFullScreen) {
  4278. document.msCancelFullScreen();
  4279. }
  4280. };
  4281. // External files
  4282. Tools.CleanUrl = function (url) {
  4283. url = url.replace(/#/mg, "%23");
  4284. return url;
  4285. };
  4286. Tools.LoadImage = function (url, onload, onerror, database) {
  4287. if (url instanceof ArrayBuffer) {
  4288. url = Tools.EncodeArrayBufferTobase64(url);
  4289. }
  4290. url = Tools.CleanUrl(url);
  4291. var img = new Image();
  4292. if (url.substr(0, 5) !== "data:") {
  4293. if (Tools.CorsBehavior) {
  4294. switch (typeof (Tools.CorsBehavior)) {
  4295. case "function":
  4296. var result = Tools.CorsBehavior(url);
  4297. if (result) {
  4298. img.crossOrigin = result;
  4299. }
  4300. break;
  4301. case "string":
  4302. default:
  4303. img.crossOrigin = Tools.CorsBehavior;
  4304. break;
  4305. }
  4306. }
  4307. }
  4308. img.onload = function () {
  4309. onload(img);
  4310. };
  4311. img.onerror = function (err) {
  4312. Tools.Error("Error while trying to load texture: " + url);
  4313. if (Tools.UseFallbackTexture) {
  4314. 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";
  4315. onload(img);
  4316. }
  4317. else {
  4318. onerror();
  4319. }
  4320. };
  4321. var noIndexedDB = function () {
  4322. img.src = url;
  4323. };
  4324. var loadFromIndexedDB = function () {
  4325. database.loadImageFromDB(url, img);
  4326. };
  4327. //ANY database to do!
  4328. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4329. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4330. }
  4331. else {
  4332. if (url.indexOf("file:") === -1) {
  4333. noIndexedDB();
  4334. }
  4335. else {
  4336. try {
  4337. var textureName = url.substring(5);
  4338. var blobURL;
  4339. try {
  4340. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4341. }
  4342. catch (ex) {
  4343. // Chrome doesn't support oneTimeOnly parameter
  4344. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4345. }
  4346. img.src = blobURL;
  4347. }
  4348. catch (e) {
  4349. img.src = null;
  4350. }
  4351. }
  4352. }
  4353. return img;
  4354. };
  4355. //ANY
  4356. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4357. url = Tools.CleanUrl(url);
  4358. var noIndexedDB = function () {
  4359. var request = new XMLHttpRequest();
  4360. var loadUrl = Tools.BaseUrl + url;
  4361. request.open('GET', loadUrl, true);
  4362. if (useArrayBuffer) {
  4363. request.responseType = "arraybuffer";
  4364. }
  4365. request.onprogress = progressCallBack;
  4366. request.onreadystatechange = function () {
  4367. if (request.readyState === 4) {
  4368. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4369. callback(!useArrayBuffer ? request.responseText : request.response);
  4370. }
  4371. else {
  4372. if (onError) {
  4373. onError();
  4374. }
  4375. else {
  4376. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4377. }
  4378. }
  4379. }
  4380. };
  4381. request.send(null);
  4382. };
  4383. var loadFromIndexedDB = function () {
  4384. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4385. };
  4386. if (url.indexOf("file:") !== -1) {
  4387. var fileName = url.substring(5);
  4388. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4389. }
  4390. else {
  4391. // Caching all files
  4392. if (database && database.enableSceneOffline) {
  4393. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4394. }
  4395. else {
  4396. noIndexedDB();
  4397. }
  4398. }
  4399. };
  4400. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4401. var reader = new FileReader();
  4402. reader.onload = function (e) {
  4403. //target doesn't have result from ts 1.3
  4404. callback(e.target['result']);
  4405. };
  4406. reader.onprogress = progressCallback;
  4407. reader.readAsDataURL(fileToLoad);
  4408. };
  4409. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4410. var reader = new FileReader();
  4411. reader.onerror = function (e) {
  4412. Tools.Log("Error while reading file: " + fileToLoad.name);
  4413. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4414. };
  4415. reader.onload = function (e) {
  4416. //target doesn't have result from ts 1.3
  4417. callback(e.target['result']);
  4418. };
  4419. reader.onprogress = progressCallBack;
  4420. if (!useArrayBuffer) {
  4421. // Asynchronous read
  4422. reader.readAsText(fileToLoad);
  4423. }
  4424. else {
  4425. reader.readAsArrayBuffer(fileToLoad);
  4426. }
  4427. };
  4428. //returns a downloadable url to a file content.
  4429. Tools.FileAsURL = function (content) {
  4430. var fileBlob = new Blob([content]);
  4431. var url = window.URL || window.webkitURL;
  4432. var link = url.createObjectURL(fileBlob);
  4433. return link;
  4434. };
  4435. // Misc.
  4436. Tools.Format = function (value, decimals) {
  4437. if (decimals === void 0) { decimals = 2; }
  4438. return value.toFixed(decimals);
  4439. };
  4440. Tools.CheckExtends = function (v, min, max) {
  4441. if (v.x < min.x)
  4442. min.x = v.x;
  4443. if (v.y < min.y)
  4444. min.y = v.y;
  4445. if (v.z < min.z)
  4446. min.z = v.z;
  4447. if (v.x > max.x)
  4448. max.x = v.x;
  4449. if (v.y > max.y)
  4450. max.y = v.y;
  4451. if (v.z > max.z)
  4452. max.z = v.z;
  4453. };
  4454. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4455. for (var prop in source) {
  4456. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4457. continue;
  4458. }
  4459. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4460. continue;
  4461. }
  4462. var sourceValue = source[prop];
  4463. var typeOfSourceValue = typeof sourceValue;
  4464. if (typeOfSourceValue === "function") {
  4465. continue;
  4466. }
  4467. if (typeOfSourceValue === "object") {
  4468. if (sourceValue instanceof Array) {
  4469. destination[prop] = [];
  4470. if (sourceValue.length > 0) {
  4471. if (typeof sourceValue[0] == "object") {
  4472. for (var index = 0; index < sourceValue.length; index++) {
  4473. var clonedValue = cloneValue(sourceValue[index], destination);
  4474. if (destination[prop].indexOf(clonedValue) === -1) {
  4475. destination[prop].push(clonedValue);
  4476. }
  4477. }
  4478. }
  4479. else {
  4480. destination[prop] = sourceValue.slice(0);
  4481. }
  4482. }
  4483. }
  4484. else {
  4485. destination[prop] = cloneValue(sourceValue, destination);
  4486. }
  4487. }
  4488. else {
  4489. destination[prop] = sourceValue;
  4490. }
  4491. }
  4492. };
  4493. Tools.IsEmpty = function (obj) {
  4494. for (var i in obj) {
  4495. return false;
  4496. }
  4497. return true;
  4498. };
  4499. Tools.RegisterTopRootEvents = function (events) {
  4500. for (var index = 0; index < events.length; index++) {
  4501. var event = events[index];
  4502. window.addEventListener(event.name, event.handler, false);
  4503. try {
  4504. if (window.parent) {
  4505. window.parent.addEventListener(event.name, event.handler, false);
  4506. }
  4507. }
  4508. catch (e) {
  4509. }
  4510. }
  4511. };
  4512. Tools.UnregisterTopRootEvents = function (events) {
  4513. for (var index = 0; index < events.length; index++) {
  4514. var event = events[index];
  4515. window.removeEventListener(event.name, event.handler);
  4516. try {
  4517. if (window.parent) {
  4518. window.parent.removeEventListener(event.name, event.handler);
  4519. }
  4520. }
  4521. catch (e) {
  4522. }
  4523. }
  4524. };
  4525. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4526. // Read the contents of the framebuffer
  4527. var numberOfChannelsByLine = width * 4;
  4528. var halfHeight = height / 2;
  4529. //Reading datas from WebGL
  4530. var data = engine.readPixels(0, 0, width, height);
  4531. //To flip image on Y axis.
  4532. for (var i = 0; i < halfHeight; i++) {
  4533. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4534. var currentCell = j + i * numberOfChannelsByLine;
  4535. var targetLine = height - i - 1;
  4536. var targetCell = j + targetLine * numberOfChannelsByLine;
  4537. var temp = data[currentCell];
  4538. data[currentCell] = data[targetCell];
  4539. data[targetCell] = temp;
  4540. }
  4541. }
  4542. // Create a 2D canvas to store the result
  4543. if (!screenshotCanvas) {
  4544. screenshotCanvas = document.createElement('canvas');
  4545. }
  4546. screenshotCanvas.width = width;
  4547. screenshotCanvas.height = height;
  4548. var context = screenshotCanvas.getContext('2d');
  4549. // Copy the pixels to a 2D canvas
  4550. var imageData = context.createImageData(width, height);
  4551. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4552. var castData = imageData.data;
  4553. castData.set(data);
  4554. context.putImageData(imageData, 0, 0);
  4555. var base64Image = screenshotCanvas.toDataURL();
  4556. if (successCallback) {
  4557. successCallback(base64Image);
  4558. }
  4559. else {
  4560. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4561. if (("download" in document.createElement("a"))) {
  4562. var a = window.document.createElement("a");
  4563. a.href = base64Image;
  4564. var date = new Date();
  4565. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4566. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4567. window.document.body.appendChild(a);
  4568. a.addEventListener("click", function () {
  4569. a.parentElement.removeChild(a);
  4570. });
  4571. a.click();
  4572. }
  4573. else {
  4574. var newWindow = window.open("");
  4575. var img = newWindow.document.createElement("img");
  4576. img.src = base64Image;
  4577. newWindow.document.body.appendChild(img);
  4578. }
  4579. }
  4580. };
  4581. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4582. var width;
  4583. var height;
  4584. //If a precision value is specified
  4585. if (size.precision) {
  4586. width = Math.round(engine.getRenderWidth() * size.precision);
  4587. height = Math.round(width / engine.getAspectRatio(camera));
  4588. size = { width: width, height: height };
  4589. }
  4590. else if (size.width && size.height) {
  4591. width = size.width;
  4592. height = size.height;
  4593. }
  4594. else if (size.width && !size.height) {
  4595. width = size.width;
  4596. height = Math.round(width / engine.getAspectRatio(camera));
  4597. size = { width: width, height: height };
  4598. }
  4599. else if (size.height && !size.width) {
  4600. height = size.height;
  4601. width = Math.round(height * engine.getAspectRatio(camera));
  4602. size = { width: width, height: height };
  4603. }
  4604. else if (!isNaN(size)) {
  4605. height = size;
  4606. width = size;
  4607. }
  4608. else {
  4609. Tools.Error("Invalid 'size' parameter !");
  4610. return;
  4611. }
  4612. var scene = camera.getScene();
  4613. var previousCamera = null;
  4614. if (scene.activeCamera !== camera) {
  4615. previousCamera = scene.activeCamera;
  4616. scene.activeCamera = camera;
  4617. }
  4618. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4619. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4620. texture.renderList = scene.meshes;
  4621. texture.onAfterRender = function () {
  4622. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4623. };
  4624. scene.incrementRenderId();
  4625. texture.render(true);
  4626. texture.dispose();
  4627. if (previousCamera) {
  4628. scene.activeCamera = previousCamera;
  4629. }
  4630. camera.getProjectionMatrix(true); // Force cache refresh;
  4631. };
  4632. // XHR response validator for local file scenario
  4633. Tools.ValidateXHRData = function (xhr, dataType) {
  4634. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4635. if (dataType === void 0) { dataType = 7; }
  4636. try {
  4637. if (dataType & 1) {
  4638. if (xhr.responseText && xhr.responseText.length > 0) {
  4639. return true;
  4640. }
  4641. else if (dataType === 1) {
  4642. return false;
  4643. }
  4644. }
  4645. if (dataType & 2) {
  4646. // Check header width and height since there is no "TGA" magic number
  4647. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4648. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4649. return true;
  4650. }
  4651. else if (dataType === 2) {
  4652. return false;
  4653. }
  4654. }
  4655. if (dataType & 4) {
  4656. // Check for the "DDS" magic number
  4657. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4658. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4659. return true;
  4660. }
  4661. else {
  4662. return false;
  4663. }
  4664. }
  4665. }
  4666. catch (e) {
  4667. }
  4668. return false;
  4669. };
  4670. Object.defineProperty(Tools, "NoneLogLevel", {
  4671. get: function () {
  4672. return Tools._NoneLogLevel;
  4673. },
  4674. enumerable: true,
  4675. configurable: true
  4676. });
  4677. Object.defineProperty(Tools, "MessageLogLevel", {
  4678. get: function () {
  4679. return Tools._MessageLogLevel;
  4680. },
  4681. enumerable: true,
  4682. configurable: true
  4683. });
  4684. Object.defineProperty(Tools, "WarningLogLevel", {
  4685. get: function () {
  4686. return Tools._WarningLogLevel;
  4687. },
  4688. enumerable: true,
  4689. configurable: true
  4690. });
  4691. Object.defineProperty(Tools, "ErrorLogLevel", {
  4692. get: function () {
  4693. return Tools._ErrorLogLevel;
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. Object.defineProperty(Tools, "AllLogLevel", {
  4699. get: function () {
  4700. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4701. },
  4702. enumerable: true,
  4703. configurable: true
  4704. });
  4705. Tools._AddLogEntry = function (entry) {
  4706. Tools._LogCache = entry + Tools._LogCache;
  4707. if (Tools.OnNewCacheEntry) {
  4708. Tools.OnNewCacheEntry(entry);
  4709. }
  4710. };
  4711. Tools._FormatMessage = function (message) {
  4712. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4713. var date = new Date();
  4714. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4715. };
  4716. Tools._LogDisabled = function (message) {
  4717. // nothing to do
  4718. };
  4719. Tools._LogEnabled = function (message) {
  4720. var formattedMessage = Tools._FormatMessage(message);
  4721. console.log("BJS - " + formattedMessage);
  4722. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4723. Tools._AddLogEntry(entry);
  4724. };
  4725. Tools._WarnDisabled = function (message) {
  4726. // nothing to do
  4727. };
  4728. Tools._WarnEnabled = function (message) {
  4729. var formattedMessage = Tools._FormatMessage(message);
  4730. console.warn("BJS - " + formattedMessage);
  4731. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4732. Tools._AddLogEntry(entry);
  4733. };
  4734. Tools._ErrorDisabled = function (message) {
  4735. // nothing to do
  4736. };
  4737. Tools._ErrorEnabled = function (message) {
  4738. Tools.errorsCount++;
  4739. var formattedMessage = Tools._FormatMessage(message);
  4740. console.error("BJS - " + formattedMessage);
  4741. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4742. Tools._AddLogEntry(entry);
  4743. };
  4744. Object.defineProperty(Tools, "LogCache", {
  4745. get: function () {
  4746. return Tools._LogCache;
  4747. },
  4748. enumerable: true,
  4749. configurable: true
  4750. });
  4751. Tools.ClearLogCache = function () {
  4752. Tools._LogCache = "";
  4753. Tools.errorsCount = 0;
  4754. };
  4755. Object.defineProperty(Tools, "LogLevels", {
  4756. set: function (level) {
  4757. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4758. Tools.Log = Tools._LogEnabled;
  4759. }
  4760. else {
  4761. Tools.Log = Tools._LogDisabled;
  4762. }
  4763. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4764. Tools.Warn = Tools._WarnEnabled;
  4765. }
  4766. else {
  4767. Tools.Warn = Tools._WarnDisabled;
  4768. }
  4769. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4770. Tools.Error = Tools._ErrorEnabled;
  4771. }
  4772. else {
  4773. Tools.Error = Tools._ErrorDisabled;
  4774. }
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4780. get: function () {
  4781. return Tools._PerformanceNoneLogLevel;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4787. get: function () {
  4788. return Tools._PerformanceUserMarkLogLevel;
  4789. },
  4790. enumerable: true,
  4791. configurable: true
  4792. });
  4793. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4794. get: function () {
  4795. return Tools._PerformanceConsoleLogLevel;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4801. set: function (level) {
  4802. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4803. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4804. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4805. return;
  4806. }
  4807. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4808. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4809. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4810. return;
  4811. }
  4812. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4813. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4814. },
  4815. enumerable: true,
  4816. configurable: true
  4817. });
  4818. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4819. };
  4820. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4821. };
  4822. Tools._StartUserMark = function (counterName, condition) {
  4823. if (condition === void 0) { condition = true; }
  4824. if (!condition || !Tools._performance.mark) {
  4825. return;
  4826. }
  4827. Tools._performance.mark(counterName + "-Begin");
  4828. };
  4829. Tools._EndUserMark = function (counterName, condition) {
  4830. if (condition === void 0) { condition = true; }
  4831. if (!condition || !Tools._performance.mark) {
  4832. return;
  4833. }
  4834. Tools._performance.mark(counterName + "-End");
  4835. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4836. };
  4837. Tools._StartPerformanceConsole = function (counterName, condition) {
  4838. if (condition === void 0) { condition = true; }
  4839. if (!condition) {
  4840. return;
  4841. }
  4842. Tools._StartUserMark(counterName, condition);
  4843. if (console.time) {
  4844. console.time(counterName);
  4845. }
  4846. };
  4847. Tools._EndPerformanceConsole = function (counterName, condition) {
  4848. if (condition === void 0) { condition = true; }
  4849. if (!condition) {
  4850. return;
  4851. }
  4852. Tools._EndUserMark(counterName, condition);
  4853. if (console.time) {
  4854. console.timeEnd(counterName);
  4855. }
  4856. };
  4857. Object.defineProperty(Tools, "Now", {
  4858. get: function () {
  4859. if (window.performance && window.performance.now) {
  4860. return window.performance.now();
  4861. }
  4862. return new Date().getTime();
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Tools.BaseUrl = "";
  4868. Tools.CorsBehavior = "anonymous";
  4869. Tools.UseFallbackTexture = true;
  4870. // Logs
  4871. Tools._NoneLogLevel = 0;
  4872. Tools._MessageLogLevel = 1;
  4873. Tools._WarningLogLevel = 2;
  4874. Tools._ErrorLogLevel = 4;
  4875. Tools._LogCache = "";
  4876. Tools.errorsCount = 0;
  4877. Tools.Log = Tools._LogEnabled;
  4878. Tools.Warn = Tools._WarnEnabled;
  4879. Tools.Error = Tools._ErrorEnabled;
  4880. // Performances
  4881. Tools._PerformanceNoneLogLevel = 0;
  4882. Tools._PerformanceUserMarkLogLevel = 1;
  4883. Tools._PerformanceConsoleLogLevel = 2;
  4884. Tools._performance = window.performance;
  4885. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4886. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4887. return Tools;
  4888. })();
  4889. BABYLON.Tools = Tools;
  4890. /**
  4891. * An implementation of a loop for asynchronous functions.
  4892. */
  4893. var AsyncLoop = (function () {
  4894. /**
  4895. * Constroctor.
  4896. * @param iterations the number of iterations.
  4897. * @param _fn the function to run each iteration
  4898. * @param _successCallback the callback that will be called upon succesful execution
  4899. * @param offset starting offset.
  4900. */
  4901. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4902. if (offset === void 0) { offset = 0; }
  4903. this.iterations = iterations;
  4904. this._fn = _fn;
  4905. this._successCallback = _successCallback;
  4906. this.index = offset - 1;
  4907. this._done = false;
  4908. }
  4909. /**
  4910. * Execute the next iteration. Must be called after the last iteration was finished.
  4911. */
  4912. AsyncLoop.prototype.executeNext = function () {
  4913. if (!this._done) {
  4914. if (this.index + 1 < this.iterations) {
  4915. ++this.index;
  4916. this._fn(this);
  4917. }
  4918. else {
  4919. this.breakLoop();
  4920. }
  4921. }
  4922. };
  4923. /**
  4924. * Break the loop and run the success callback.
  4925. */
  4926. AsyncLoop.prototype.breakLoop = function () {
  4927. this._done = true;
  4928. this._successCallback();
  4929. };
  4930. /**
  4931. * Helper function
  4932. */
  4933. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4934. if (offset === void 0) { offset = 0; }
  4935. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4936. loop.executeNext();
  4937. return loop;
  4938. };
  4939. /**
  4940. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4941. * @param iterations total number of iterations
  4942. * @param syncedIterations number of synchronous iterations in each async iteration.
  4943. * @param fn the function to call each iteration.
  4944. * @param callback a success call back that will be called when iterating stops.
  4945. * @param breakFunction a break condition (optional)
  4946. * @param timeout timeout settings for the setTimeout function. default - 0.
  4947. * @constructor
  4948. */
  4949. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4950. if (timeout === void 0) { timeout = 0; }
  4951. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4952. if (breakFunction && breakFunction())
  4953. loop.breakLoop();
  4954. else {
  4955. setTimeout(function () {
  4956. for (var i = 0; i < syncedIterations; ++i) {
  4957. var iteration = (loop.index * syncedIterations) + i;
  4958. if (iteration >= iterations)
  4959. break;
  4960. fn(iteration);
  4961. if (breakFunction && breakFunction()) {
  4962. loop.breakLoop();
  4963. break;
  4964. }
  4965. }
  4966. loop.executeNext();
  4967. }, timeout);
  4968. }
  4969. }, callback);
  4970. };
  4971. return AsyncLoop;
  4972. })();
  4973. BABYLON.AsyncLoop = AsyncLoop;
  4974. })(BABYLON || (BABYLON = {}));
  4975. var BABYLON;
  4976. (function (BABYLON) {
  4977. var Internals;
  4978. (function (Internals) {
  4979. var _AlphaState = (function () {
  4980. function _AlphaState() {
  4981. this._isAlphaBlendDirty = false;
  4982. this._isBlendFunctionParametersDirty = false;
  4983. this._alphaBlend = false;
  4984. this._blendFunctionParameters = new Array(4);
  4985. }
  4986. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4987. get: function () {
  4988. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4989. },
  4990. enumerable: true,
  4991. configurable: true
  4992. });
  4993. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4994. get: function () {
  4995. return this._alphaBlend;
  4996. },
  4997. set: function (value) {
  4998. if (this._alphaBlend === value) {
  4999. return;
  5000. }
  5001. this._alphaBlend = value;
  5002. this._isAlphaBlendDirty = true;
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5008. if (this._blendFunctionParameters[0] === value0 &&
  5009. this._blendFunctionParameters[1] === value1 &&
  5010. this._blendFunctionParameters[2] === value2 &&
  5011. this._blendFunctionParameters[3] === value3) {
  5012. return;
  5013. }
  5014. this._blendFunctionParameters[0] = value0;
  5015. this._blendFunctionParameters[1] = value1;
  5016. this._blendFunctionParameters[2] = value2;
  5017. this._blendFunctionParameters[3] = value3;
  5018. this._isBlendFunctionParametersDirty = true;
  5019. };
  5020. _AlphaState.prototype.reset = function () {
  5021. this._alphaBlend = false;
  5022. this._blendFunctionParameters[0] = null;
  5023. this._blendFunctionParameters[1] = null;
  5024. this._blendFunctionParameters[2] = null;
  5025. this._blendFunctionParameters[3] = null;
  5026. this._isAlphaBlendDirty = true;
  5027. this._isBlendFunctionParametersDirty = false;
  5028. };
  5029. _AlphaState.prototype.apply = function (gl) {
  5030. if (!this.isDirty) {
  5031. return;
  5032. }
  5033. // Alpha blend
  5034. if (this._isAlphaBlendDirty) {
  5035. if (this._alphaBlend) {
  5036. gl.enable(gl.BLEND);
  5037. }
  5038. else {
  5039. gl.disable(gl.BLEND);
  5040. }
  5041. this._isAlphaBlendDirty = false;
  5042. }
  5043. // Alpha function
  5044. if (this._isBlendFunctionParametersDirty) {
  5045. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5046. this._isBlendFunctionParametersDirty = false;
  5047. }
  5048. };
  5049. return _AlphaState;
  5050. })();
  5051. Internals._AlphaState = _AlphaState;
  5052. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5053. })(BABYLON || (BABYLON = {}));
  5054. var BABYLON;
  5055. (function (BABYLON) {
  5056. var Internals;
  5057. (function (Internals) {
  5058. var _DepthCullingState = (function () {
  5059. function _DepthCullingState() {
  5060. this._isDepthTestDirty = false;
  5061. this._isDepthMaskDirty = false;
  5062. this._isDepthFuncDirty = false;
  5063. this._isCullFaceDirty = false;
  5064. this._isCullDirty = false;
  5065. this._isZOffsetDirty = false;
  5066. }
  5067. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5068. get: function () {
  5069. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5070. },
  5071. enumerable: true,
  5072. configurable: true
  5073. });
  5074. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5075. get: function () {
  5076. return this._zOffset;
  5077. },
  5078. set: function (value) {
  5079. if (this._zOffset === value) {
  5080. return;
  5081. }
  5082. this._zOffset = value;
  5083. this._isZOffsetDirty = true;
  5084. },
  5085. enumerable: true,
  5086. configurable: true
  5087. });
  5088. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5089. get: function () {
  5090. return this._cullFace;
  5091. },
  5092. set: function (value) {
  5093. if (this._cullFace === value) {
  5094. return;
  5095. }
  5096. this._cullFace = value;
  5097. this._isCullFaceDirty = true;
  5098. },
  5099. enumerable: true,
  5100. configurable: true
  5101. });
  5102. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5103. get: function () {
  5104. return this._cull;
  5105. },
  5106. set: function (value) {
  5107. if (this._cull === value) {
  5108. return;
  5109. }
  5110. this._cull = value;
  5111. this._isCullDirty = true;
  5112. },
  5113. enumerable: true,
  5114. configurable: true
  5115. });
  5116. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5117. get: function () {
  5118. return this._depthFunc;
  5119. },
  5120. set: function (value) {
  5121. if (this._depthFunc === value) {
  5122. return;
  5123. }
  5124. this._depthFunc = value;
  5125. this._isDepthFuncDirty = true;
  5126. },
  5127. enumerable: true,
  5128. configurable: true
  5129. });
  5130. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5131. get: function () {
  5132. return this._depthMask;
  5133. },
  5134. set: function (value) {
  5135. if (this._depthMask === value) {
  5136. return;
  5137. }
  5138. this._depthMask = value;
  5139. this._isDepthMaskDirty = true;
  5140. },
  5141. enumerable: true,
  5142. configurable: true
  5143. });
  5144. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5145. get: function () {
  5146. return this._depthTest;
  5147. },
  5148. set: function (value) {
  5149. if (this._depthTest === value) {
  5150. return;
  5151. }
  5152. this._depthTest = value;
  5153. this._isDepthTestDirty = true;
  5154. },
  5155. enumerable: true,
  5156. configurable: true
  5157. });
  5158. _DepthCullingState.prototype.reset = function () {
  5159. this._depthMask = true;
  5160. this._depthTest = true;
  5161. this._depthFunc = null;
  5162. this._cull = null;
  5163. this._cullFace = null;
  5164. this._zOffset = 0;
  5165. this._isDepthTestDirty = true;
  5166. this._isDepthMaskDirty = true;
  5167. this._isDepthFuncDirty = false;
  5168. this._isCullFaceDirty = false;
  5169. this._isCullDirty = false;
  5170. this._isZOffsetDirty = false;
  5171. };
  5172. _DepthCullingState.prototype.apply = function (gl) {
  5173. if (!this.isDirty) {
  5174. return;
  5175. }
  5176. // Cull
  5177. if (this._isCullDirty) {
  5178. if (this.cull) {
  5179. gl.enable(gl.CULL_FACE);
  5180. }
  5181. else {
  5182. gl.disable(gl.CULL_FACE);
  5183. }
  5184. this._isCullDirty = false;
  5185. }
  5186. // Cull face
  5187. if (this._isCullFaceDirty) {
  5188. gl.cullFace(this.cullFace);
  5189. this._isCullFaceDirty = false;
  5190. }
  5191. // Depth mask
  5192. if (this._isDepthMaskDirty) {
  5193. gl.depthMask(this.depthMask);
  5194. this._isDepthMaskDirty = false;
  5195. }
  5196. // Depth test
  5197. if (this._isDepthTestDirty) {
  5198. if (this.depthTest) {
  5199. gl.enable(gl.DEPTH_TEST);
  5200. }
  5201. else {
  5202. gl.disable(gl.DEPTH_TEST);
  5203. }
  5204. this._isDepthTestDirty = false;
  5205. }
  5206. // Depth func
  5207. if (this._isDepthFuncDirty) {
  5208. gl.depthFunc(this.depthFunc);
  5209. this._isDepthFuncDirty = false;
  5210. }
  5211. // zOffset
  5212. if (this._isZOffsetDirty) {
  5213. if (this.zOffset) {
  5214. gl.enable(gl.POLYGON_OFFSET_FILL);
  5215. gl.polygonOffset(this.zOffset, 0);
  5216. }
  5217. else {
  5218. gl.disable(gl.POLYGON_OFFSET_FILL);
  5219. }
  5220. this._isZOffsetDirty = false;
  5221. }
  5222. };
  5223. return _DepthCullingState;
  5224. })();
  5225. Internals._DepthCullingState = _DepthCullingState;
  5226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5227. })(BABYLON || (BABYLON = {}));
  5228. var BABYLON;
  5229. (function (BABYLON) {
  5230. var compileShader = function (gl, source, type, defines) {
  5231. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5232. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5233. gl.compileShader(shader);
  5234. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5235. throw new Error(gl.getShaderInfoLog(shader));
  5236. }
  5237. return shader;
  5238. };
  5239. var getWebGLTextureType = function (gl, type) {
  5240. var textureType = gl.UNSIGNED_BYTE;
  5241. if (type === Engine.TEXTURETYPE_FLOAT)
  5242. textureType = gl.FLOAT;
  5243. return textureType;
  5244. };
  5245. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5246. var magFilter = gl.NEAREST;
  5247. var minFilter = gl.NEAREST;
  5248. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5249. magFilter = gl.LINEAR;
  5250. if (generateMipMaps) {
  5251. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5252. }
  5253. else {
  5254. minFilter = gl.LINEAR;
  5255. }
  5256. }
  5257. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5258. magFilter = gl.LINEAR;
  5259. if (generateMipMaps) {
  5260. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5261. }
  5262. else {
  5263. minFilter = gl.LINEAR;
  5264. }
  5265. }
  5266. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5267. magFilter = gl.NEAREST;
  5268. if (generateMipMaps) {
  5269. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5270. }
  5271. else {
  5272. minFilter = gl.NEAREST;
  5273. }
  5274. }
  5275. return {
  5276. min: minFilter,
  5277. mag: magFilter
  5278. };
  5279. };
  5280. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5282. var engine = scene.getEngine();
  5283. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5284. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5285. gl.bindTexture(gl.TEXTURE_2D, texture);
  5286. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5287. texture._baseWidth = width;
  5288. texture._baseHeight = height;
  5289. texture._width = potWidth;
  5290. texture._height = potHeight;
  5291. texture.isReady = true;
  5292. processFunction(potWidth, potHeight);
  5293. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5296. if (!noMipmap && !isCompressed) {
  5297. gl.generateMipmap(gl.TEXTURE_2D);
  5298. }
  5299. gl.bindTexture(gl.TEXTURE_2D, null);
  5300. engine.resetTextureCache();
  5301. scene._removePendingData(texture);
  5302. if (onLoad) {
  5303. onLoad();
  5304. }
  5305. };
  5306. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5307. var img;
  5308. var onload = function () {
  5309. loadedImages[index] = img;
  5310. loadedImages._internalCount++;
  5311. scene._removePendingData(img);
  5312. if (loadedImages._internalCount === 6) {
  5313. onfinish(loadedImages);
  5314. }
  5315. };
  5316. var onerror = function () {
  5317. scene._removePendingData(img);
  5318. };
  5319. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5320. scene._addPendingData(img);
  5321. };
  5322. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5323. var loadedImages = [];
  5324. loadedImages._internalCount = 0;
  5325. for (var index = 0; index < 6; index++) {
  5326. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5327. }
  5328. };
  5329. var EngineCapabilities = (function () {
  5330. function EngineCapabilities() {
  5331. }
  5332. return EngineCapabilities;
  5333. })();
  5334. BABYLON.EngineCapabilities = EngineCapabilities;
  5335. /**
  5336. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5337. */
  5338. var Engine = (function () {
  5339. /**
  5340. * @constructor
  5341. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5342. * @param {boolean} [antialias] - enable antialias
  5343. * @param options - further options to be sent to the getContext function
  5344. */
  5345. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5346. var _this = this;
  5347. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5348. // Public members
  5349. this.isFullscreen = false;
  5350. this.isPointerLock = false;
  5351. this.cullBackFaces = true;
  5352. this.renderEvenInBackground = true;
  5353. // To enable/disable IDB support and avoid XHR on .manifest
  5354. this.enableOfflineSupport = true;
  5355. this.scenes = new Array();
  5356. this._windowIsBackground = false;
  5357. this._webGLVersion = "1.0";
  5358. this._drawCalls = 0;
  5359. this._renderingQueueLaunched = false;
  5360. this._activeRenderLoops = [];
  5361. // FPS
  5362. this.fpsRange = 60;
  5363. this.previousFramesDuration = [];
  5364. this.fps = 60;
  5365. this.deltaTime = 0;
  5366. // States
  5367. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5368. this._alphaState = new BABYLON.Internals._AlphaState();
  5369. this._alphaMode = Engine.ALPHA_DISABLE;
  5370. // Cache
  5371. this._loadedTexturesCache = new Array();
  5372. this._maxTextureChannels = 16;
  5373. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5374. this._compiledEffects = {};
  5375. this._uintIndicesCurrentlySet = false;
  5376. this._renderingCanvas = canvas;
  5377. options = options || {};
  5378. options.antialias = antialias;
  5379. if (options.preserveDrawingBuffer === undefined) {
  5380. options.preserveDrawingBuffer = false;
  5381. }
  5382. // GL
  5383. //try {
  5384. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5385. // if (this._gl) {
  5386. // this._webGLVersion = "2.0";
  5387. // }
  5388. //} catch (e) {
  5389. // // Do nothing
  5390. //}
  5391. if (!this._gl) {
  5392. try {
  5393. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5394. }
  5395. catch (e) {
  5396. throw new Error("WebGL not supported");
  5397. }
  5398. }
  5399. if (!this._gl) {
  5400. throw new Error("WebGL not supported");
  5401. }
  5402. this._onBlur = function () {
  5403. _this._windowIsBackground = true;
  5404. };
  5405. this._onFocus = function () {
  5406. _this._windowIsBackground = false;
  5407. };
  5408. window.addEventListener("blur", this._onBlur);
  5409. window.addEventListener("focus", this._onFocus);
  5410. // Viewport
  5411. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5412. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5413. this.resize();
  5414. // Caps
  5415. this._caps = new EngineCapabilities();
  5416. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5417. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5418. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5419. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5420. // Infos
  5421. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5422. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5423. if (rendererInfo != null) {
  5424. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5425. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5426. }
  5427. if (!this._glVendor) {
  5428. this._glVendor = "Unknown vendor";
  5429. }
  5430. if (!this._glRenderer) {
  5431. this._glRenderer = "Unknown renderer";
  5432. }
  5433. // Extensions
  5434. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5435. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5436. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5437. 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');
  5438. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5439. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5440. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5441. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5442. this._caps.highPrecisionShaderSupported = true;
  5443. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5444. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5445. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5446. if (this._gl.getShaderPrecisionFormat) {
  5447. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5448. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5449. }
  5450. // Depth buffer
  5451. this.setDepthBuffer(true);
  5452. this.setDepthFunctionToLessOrEqual();
  5453. this.setDepthWrite(true);
  5454. // Fullscreen
  5455. this._onFullscreenChange = function () {
  5456. if (document.fullscreen !== undefined) {
  5457. _this.isFullscreen = document.fullscreen;
  5458. }
  5459. else if (document.mozFullScreen !== undefined) {
  5460. _this.isFullscreen = document.mozFullScreen;
  5461. }
  5462. else if (document.webkitIsFullScreen !== undefined) {
  5463. _this.isFullscreen = document.webkitIsFullScreen;
  5464. }
  5465. else if (document.msIsFullScreen !== undefined) {
  5466. _this.isFullscreen = document.msIsFullScreen;
  5467. }
  5468. // Pointer lock
  5469. if (_this.isFullscreen && _this._pointerLockRequested) {
  5470. canvas.requestPointerLock = canvas.requestPointerLock ||
  5471. canvas.msRequestPointerLock ||
  5472. canvas.mozRequestPointerLock ||
  5473. canvas.webkitRequestPointerLock;
  5474. if (canvas.requestPointerLock) {
  5475. canvas.requestPointerLock();
  5476. }
  5477. }
  5478. };
  5479. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5480. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5481. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5482. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5483. // Pointer lock
  5484. this._onPointerLockChange = function () {
  5485. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5486. document.webkitPointerLockElement === canvas ||
  5487. document.msPointerLockElement === canvas ||
  5488. document.pointerLockElement === canvas);
  5489. };
  5490. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5491. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5492. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5493. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5494. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5495. Engine.audioEngine = new BABYLON.AudioEngine();
  5496. }
  5497. //default loading screen
  5498. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5499. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5500. }
  5501. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5502. get: function () {
  5503. return Engine._ALPHA_DISABLE;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5509. get: function () {
  5510. return Engine._ALPHA_ONEONE;
  5511. },
  5512. enumerable: true,
  5513. configurable: true
  5514. });
  5515. Object.defineProperty(Engine, "ALPHA_ADD", {
  5516. get: function () {
  5517. return Engine._ALPHA_ADD;
  5518. },
  5519. enumerable: true,
  5520. configurable: true
  5521. });
  5522. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5523. get: function () {
  5524. return Engine._ALPHA_COMBINE;
  5525. },
  5526. enumerable: true,
  5527. configurable: true
  5528. });
  5529. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5530. get: function () {
  5531. return Engine._ALPHA_SUBTRACT;
  5532. },
  5533. enumerable: true,
  5534. configurable: true
  5535. });
  5536. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5537. get: function () {
  5538. return Engine._ALPHA_MULTIPLY;
  5539. },
  5540. enumerable: true,
  5541. configurable: true
  5542. });
  5543. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5544. get: function () {
  5545. return Engine._ALPHA_MAXIMIZED;
  5546. },
  5547. enumerable: true,
  5548. configurable: true
  5549. });
  5550. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5551. get: function () {
  5552. return Engine._DELAYLOADSTATE_NONE;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5558. get: function () {
  5559. return Engine._DELAYLOADSTATE_LOADED;
  5560. },
  5561. enumerable: true,
  5562. configurable: true
  5563. });
  5564. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5565. get: function () {
  5566. return Engine._DELAYLOADSTATE_LOADING;
  5567. },
  5568. enumerable: true,
  5569. configurable: true
  5570. });
  5571. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5572. get: function () {
  5573. return Engine._DELAYLOADSTATE_NOTLOADED;
  5574. },
  5575. enumerable: true,
  5576. configurable: true
  5577. });
  5578. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5579. get: function () {
  5580. return Engine._TEXTUREFORMAT_ALPHA;
  5581. },
  5582. enumerable: true,
  5583. configurable: true
  5584. });
  5585. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5586. get: function () {
  5587. return Engine._TEXTUREFORMAT_LUMINANCE;
  5588. },
  5589. enumerable: true,
  5590. configurable: true
  5591. });
  5592. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5593. get: function () {
  5594. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5595. },
  5596. enumerable: true,
  5597. configurable: true
  5598. });
  5599. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5600. get: function () {
  5601. return Engine._TEXTUREFORMAT_RGB;
  5602. },
  5603. enumerable: true,
  5604. configurable: true
  5605. });
  5606. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5607. get: function () {
  5608. return Engine._TEXTUREFORMAT_RGBA;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5614. get: function () {
  5615. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5621. get: function () {
  5622. return Engine._TEXTURETYPE_FLOAT;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. Object.defineProperty(Engine, "Version", {
  5628. get: function () {
  5629. return "2.4.0-alpha";
  5630. },
  5631. enumerable: true,
  5632. configurable: true
  5633. });
  5634. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5635. get: function () {
  5636. return this._webGLVersion;
  5637. },
  5638. enumerable: true,
  5639. configurable: true
  5640. });
  5641. Engine.prototype._prepareWorkingCanvas = function () {
  5642. if (this._workingCanvas) {
  5643. return;
  5644. }
  5645. this._workingCanvas = document.createElement("canvas");
  5646. this._workingContext = this._workingCanvas.getContext("2d");
  5647. };
  5648. Engine.prototype.resetTextureCache = function () {
  5649. for (var index = 0; index < this._maxTextureChannels; index++) {
  5650. this._activeTexturesCache[index] = null;
  5651. }
  5652. };
  5653. Engine.prototype.getGlInfo = function () {
  5654. return {
  5655. vendor: this._glVendor,
  5656. renderer: this._glRenderer,
  5657. version: this._glVersion
  5658. };
  5659. };
  5660. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5661. if (useScreen === void 0) { useScreen = false; }
  5662. var viewport = camera.viewport;
  5663. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5664. };
  5665. Engine.prototype.getRenderWidth = function (useScreen) {
  5666. if (useScreen === void 0) { useScreen = false; }
  5667. if (!useScreen && this._currentRenderTarget) {
  5668. return this._currentRenderTarget._width;
  5669. }
  5670. return this._renderingCanvas.width;
  5671. };
  5672. Engine.prototype.getRenderHeight = function (useScreen) {
  5673. if (useScreen === void 0) { useScreen = false; }
  5674. if (!useScreen && this._currentRenderTarget) {
  5675. return this._currentRenderTarget._height;
  5676. }
  5677. return this._renderingCanvas.height;
  5678. };
  5679. Engine.prototype.getRenderingCanvas = function () {
  5680. return this._renderingCanvas;
  5681. };
  5682. Engine.prototype.getRenderingCanvasClientRect = function () {
  5683. return this._renderingCanvas.getBoundingClientRect();
  5684. };
  5685. Engine.prototype.setHardwareScalingLevel = function (level) {
  5686. this._hardwareScalingLevel = level;
  5687. this.resize();
  5688. };
  5689. Engine.prototype.getHardwareScalingLevel = function () {
  5690. return this._hardwareScalingLevel;
  5691. };
  5692. Engine.prototype.getLoadedTexturesCache = function () {
  5693. return this._loadedTexturesCache;
  5694. };
  5695. Engine.prototype.getCaps = function () {
  5696. return this._caps;
  5697. };
  5698. Object.defineProperty(Engine.prototype, "drawCalls", {
  5699. get: function () {
  5700. return this._drawCalls;
  5701. },
  5702. enumerable: true,
  5703. configurable: true
  5704. });
  5705. // Methods
  5706. Engine.prototype.resetDrawCalls = function () {
  5707. this._drawCalls = 0;
  5708. };
  5709. Engine.prototype.setDepthFunctionToGreater = function () {
  5710. this._depthCullingState.depthFunc = this._gl.GREATER;
  5711. };
  5712. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5713. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5714. };
  5715. Engine.prototype.setDepthFunctionToLess = function () {
  5716. this._depthCullingState.depthFunc = this._gl.LESS;
  5717. };
  5718. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5719. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5720. };
  5721. /**
  5722. * stop executing a render loop function and remove it from the execution array
  5723. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5724. */
  5725. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5726. if (!renderFunction) {
  5727. this._activeRenderLoops = [];
  5728. return;
  5729. }
  5730. var index = this._activeRenderLoops.indexOf(renderFunction);
  5731. if (index >= 0) {
  5732. this._activeRenderLoops.splice(index, 1);
  5733. }
  5734. };
  5735. Engine.prototype._renderLoop = function () {
  5736. var shouldRender = true;
  5737. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5738. shouldRender = false;
  5739. }
  5740. if (shouldRender) {
  5741. // Start new frame
  5742. this.beginFrame();
  5743. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5744. var renderFunction = this._activeRenderLoops[index];
  5745. renderFunction();
  5746. }
  5747. // Present
  5748. this.endFrame();
  5749. }
  5750. if (this._activeRenderLoops.length > 0) {
  5751. // Register new frame
  5752. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5753. }
  5754. else {
  5755. this._renderingQueueLaunched = false;
  5756. }
  5757. };
  5758. /**
  5759. * Register and execute a render loop. The engine can have more than one render function.
  5760. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5761. * @example
  5762. * engine.runRenderLoop(function () {
  5763. * scene.render()
  5764. * })
  5765. */
  5766. Engine.prototype.runRenderLoop = function (renderFunction) {
  5767. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5768. return;
  5769. }
  5770. this._activeRenderLoops.push(renderFunction);
  5771. if (!this._renderingQueueLaunched) {
  5772. this._renderingQueueLaunched = true;
  5773. this._bindedRenderFunction = this._renderLoop.bind(this);
  5774. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5775. }
  5776. };
  5777. /**
  5778. * Toggle full screen mode.
  5779. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5780. */
  5781. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5782. if (this.isFullscreen) {
  5783. BABYLON.Tools.ExitFullscreen();
  5784. }
  5785. else {
  5786. this._pointerLockRequested = requestPointerLock;
  5787. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5788. }
  5789. };
  5790. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5791. this.applyStates();
  5792. if (backBuffer) {
  5793. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5794. }
  5795. if (depthStencil && this._depthCullingState.depthMask) {
  5796. this._gl.clearDepth(1.0);
  5797. }
  5798. var mode = 0;
  5799. if (backBuffer) {
  5800. mode |= this._gl.COLOR_BUFFER_BIT;
  5801. }
  5802. if (depthStencil && this._depthCullingState.depthMask) {
  5803. mode |= this._gl.DEPTH_BUFFER_BIT;
  5804. }
  5805. this._gl.clear(mode);
  5806. };
  5807. /**
  5808. * Set the WebGL's viewport
  5809. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5810. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5811. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5812. */
  5813. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5814. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5815. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5816. var x = viewport.x || 0;
  5817. var y = viewport.y || 0;
  5818. this._cachedViewport = viewport;
  5819. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5820. };
  5821. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5822. this._cachedViewport = null;
  5823. this._gl.viewport(x, y, width, height);
  5824. };
  5825. Engine.prototype.beginFrame = function () {
  5826. this._measureFps();
  5827. };
  5828. Engine.prototype.endFrame = function () {
  5829. //this.flushFramebuffer();
  5830. };
  5831. /**
  5832. * resize the view according to the canvas' size.
  5833. * @example
  5834. * window.addEventListener("resize", function () {
  5835. * engine.resize();
  5836. * });
  5837. */
  5838. Engine.prototype.resize = function () {
  5839. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5840. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5841. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5842. for (var index = 0; index < this.scenes.length; index++) {
  5843. var scene = this.scenes[index];
  5844. if (scene.debugLayer.isVisible()) {
  5845. scene.debugLayer._syncPositions();
  5846. }
  5847. }
  5848. };
  5849. /**
  5850. * force a specific size of the canvas
  5851. * @param {number} width - the new canvas' width
  5852. * @param {number} height - the new canvas' height
  5853. */
  5854. Engine.prototype.setSize = function (width, height) {
  5855. this._renderingCanvas.width = width;
  5856. this._renderingCanvas.height = height;
  5857. for (var index = 0; index < this.scenes.length; index++) {
  5858. var scene = this.scenes[index];
  5859. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5860. var cam = scene.cameras[camIndex];
  5861. cam._currentRenderId = 0;
  5862. }
  5863. }
  5864. };
  5865. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5866. this._currentRenderTarget = texture;
  5867. var gl = this._gl;
  5868. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5869. if (texture.isCube) {
  5870. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5871. }
  5872. else {
  5873. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5874. }
  5875. this._gl.viewport(0, 0, texture._width, texture._height);
  5876. this.wipeCaches();
  5877. };
  5878. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5879. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5880. this._currentRenderTarget = null;
  5881. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5882. var gl = this._gl;
  5883. gl.bindTexture(gl.TEXTURE_2D, texture);
  5884. gl.generateMipmap(gl.TEXTURE_2D);
  5885. gl.bindTexture(gl.TEXTURE_2D, null);
  5886. }
  5887. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5888. };
  5889. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5890. if (texture.generateMipMaps) {
  5891. var gl = this._gl;
  5892. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5894. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5895. }
  5896. };
  5897. Engine.prototype.flushFramebuffer = function () {
  5898. this._gl.flush();
  5899. };
  5900. Engine.prototype.restoreDefaultFramebuffer = function () {
  5901. this._currentRenderTarget = null;
  5902. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5903. this.setViewport(this._cachedViewport);
  5904. this.wipeCaches();
  5905. };
  5906. // VBOs
  5907. Engine.prototype._resetVertexBufferBinding = function () {
  5908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5909. this._cachedVertexBuffers = null;
  5910. };
  5911. Engine.prototype.createVertexBuffer = function (vertices) {
  5912. var vbo = this._gl.createBuffer();
  5913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5914. if (vertices instanceof Float32Array) {
  5915. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5916. }
  5917. else {
  5918. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5919. }
  5920. this._resetVertexBufferBinding();
  5921. vbo.references = 1;
  5922. return vbo;
  5923. };
  5924. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5925. var vbo = this._gl.createBuffer();
  5926. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5927. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5928. this._resetVertexBufferBinding();
  5929. vbo.references = 1;
  5930. return vbo;
  5931. };
  5932. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5933. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5934. if (offset === undefined) {
  5935. offset = 0;
  5936. }
  5937. if (vertices instanceof Float32Array) {
  5938. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5939. }
  5940. else {
  5941. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5942. }
  5943. this._resetVertexBufferBinding();
  5944. };
  5945. Engine.prototype._resetIndexBufferBinding = function () {
  5946. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5947. this._cachedIndexBuffer = null;
  5948. };
  5949. Engine.prototype.createIndexBuffer = function (indices) {
  5950. var vbo = this._gl.createBuffer();
  5951. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5952. // Check for 32 bits indices
  5953. var arrayBuffer;
  5954. var need32Bits = false;
  5955. if (this._caps.uintIndices) {
  5956. for (var index = 0; index < indices.length; index++) {
  5957. if (indices[index] > 65535) {
  5958. need32Bits = true;
  5959. break;
  5960. }
  5961. }
  5962. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5963. }
  5964. else {
  5965. arrayBuffer = new Uint16Array(indices);
  5966. }
  5967. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5968. this._resetIndexBufferBinding();
  5969. vbo.references = 1;
  5970. vbo.is32Bits = need32Bits;
  5971. return vbo;
  5972. };
  5973. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5974. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5975. this._cachedVertexBuffers = vertexBuffer;
  5976. this._cachedEffectForVertexBuffers = effect;
  5977. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5978. var offset = 0;
  5979. for (var index = 0; index < vertexDeclaration.length; index++) {
  5980. var order = effect.getAttributeLocation(index);
  5981. if (order >= 0) {
  5982. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5983. }
  5984. offset += vertexDeclaration[index] * 4;
  5985. }
  5986. }
  5987. if (this._cachedIndexBuffer !== indexBuffer) {
  5988. this._cachedIndexBuffer = indexBuffer;
  5989. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5990. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5991. }
  5992. };
  5993. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5994. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5995. this._cachedVertexBuffers = vertexBuffers;
  5996. this._cachedEffectForVertexBuffers = effect;
  5997. var attributes = effect.getAttributesNames();
  5998. for (var index = 0; index < attributes.length; index++) {
  5999. var order = effect.getAttributeLocation(index);
  6000. if (order >= 0) {
  6001. var vertexBuffer = vertexBuffers[attributes[index]];
  6002. if (!vertexBuffer) {
  6003. continue;
  6004. }
  6005. var stride = vertexBuffer.getStrideSize();
  6006. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6007. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6008. }
  6009. }
  6010. }
  6011. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6012. this._cachedIndexBuffer = indexBuffer;
  6013. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6014. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6015. }
  6016. };
  6017. Engine.prototype._releaseBuffer = function (buffer) {
  6018. buffer.references--;
  6019. if (buffer.references === 0) {
  6020. this._gl.deleteBuffer(buffer);
  6021. return true;
  6022. }
  6023. return false;
  6024. };
  6025. Engine.prototype.createInstancesBuffer = function (capacity) {
  6026. var buffer = this._gl.createBuffer();
  6027. buffer.capacity = capacity;
  6028. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6029. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6030. return buffer;
  6031. };
  6032. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6033. this._gl.deleteBuffer(buffer);
  6034. };
  6035. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6036. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6037. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6038. for (var index = 0; index < 4; index++) {
  6039. var offsetLocation = offsetLocations[index];
  6040. this._gl.enableVertexAttribArray(offsetLocation);
  6041. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6042. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6043. }
  6044. };
  6045. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6046. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6047. for (var index = 0; index < 4; index++) {
  6048. var offsetLocation = offsetLocations[index];
  6049. this._gl.disableVertexAttribArray(offsetLocation);
  6050. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6051. }
  6052. };
  6053. Engine.prototype.applyStates = function () {
  6054. this._depthCullingState.apply(this._gl);
  6055. this._alphaState.apply(this._gl);
  6056. };
  6057. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6058. // Apply states
  6059. this.applyStates();
  6060. this._drawCalls++;
  6061. // Render
  6062. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6063. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6064. if (instancesCount) {
  6065. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6066. return;
  6067. }
  6068. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6069. };
  6070. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6071. // Apply states
  6072. this.applyStates();
  6073. this._drawCalls++;
  6074. if (instancesCount) {
  6075. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6076. return;
  6077. }
  6078. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6079. };
  6080. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6081. // Apply states
  6082. this.applyStates();
  6083. this._drawCalls++;
  6084. if (instancesCount) {
  6085. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6086. return;
  6087. }
  6088. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6089. };
  6090. // Shaders
  6091. Engine.prototype._releaseEffect = function (effect) {
  6092. if (this._compiledEffects[effect._key]) {
  6093. delete this._compiledEffects[effect._key];
  6094. if (effect.getProgram()) {
  6095. this._gl.deleteProgram(effect.getProgram());
  6096. }
  6097. }
  6098. };
  6099. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6100. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6101. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6102. var name = vertex + "+" + fragment + "@" + defines;
  6103. if (this._compiledEffects[name]) {
  6104. return this._compiledEffects[name];
  6105. }
  6106. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6107. effect._key = name;
  6108. this._compiledEffects[name] = effect;
  6109. return effect;
  6110. };
  6111. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6112. if (uniformsNames === void 0) { uniformsNames = []; }
  6113. if (samplers === void 0) { samplers = []; }
  6114. if (defines === void 0) { defines = ""; }
  6115. return this.createEffect({
  6116. vertex: "particles",
  6117. fragmentElement: fragmentName
  6118. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6119. };
  6120. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6121. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6122. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6123. var shaderProgram = this._gl.createProgram();
  6124. this._gl.attachShader(shaderProgram, vertexShader);
  6125. this._gl.attachShader(shaderProgram, fragmentShader);
  6126. this._gl.linkProgram(shaderProgram);
  6127. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6128. if (!linked) {
  6129. var error = this._gl.getProgramInfoLog(shaderProgram);
  6130. if (error) {
  6131. throw new Error(error);
  6132. }
  6133. }
  6134. this._gl.deleteShader(vertexShader);
  6135. this._gl.deleteShader(fragmentShader);
  6136. return shaderProgram;
  6137. };
  6138. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6139. var results = [];
  6140. for (var index = 0; index < uniformsNames.length; index++) {
  6141. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6142. }
  6143. return results;
  6144. };
  6145. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6146. var results = [];
  6147. for (var index = 0; index < attributesNames.length; index++) {
  6148. try {
  6149. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6150. }
  6151. catch (e) {
  6152. results.push(-1);
  6153. }
  6154. }
  6155. return results;
  6156. };
  6157. Engine.prototype.enableEffect = function (effect) {
  6158. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6159. if (effect && effect.onBind) {
  6160. effect.onBind(effect);
  6161. }
  6162. return;
  6163. }
  6164. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6165. // Use program
  6166. this._gl.useProgram(effect.getProgram());
  6167. for (var i in this._vertexAttribArrays) {
  6168. //make sure this is a number)
  6169. var iAsNumber = +i;
  6170. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6171. continue;
  6172. }
  6173. this._vertexAttribArrays[iAsNumber] = false;
  6174. this._gl.disableVertexAttribArray(iAsNumber);
  6175. }
  6176. var attributesCount = effect.getAttributesCount();
  6177. for (var index = 0; index < attributesCount; index++) {
  6178. // Attributes
  6179. var order = effect.getAttributeLocation(index);
  6180. if (order >= 0) {
  6181. this._vertexAttribArrays[order] = true;
  6182. this._gl.enableVertexAttribArray(order);
  6183. }
  6184. }
  6185. this._currentEffect = effect;
  6186. if (effect.onBind) {
  6187. effect.onBind(effect);
  6188. }
  6189. };
  6190. Engine.prototype.setArray = function (uniform, array) {
  6191. if (!uniform)
  6192. return;
  6193. this._gl.uniform1fv(uniform, array);
  6194. };
  6195. Engine.prototype.setArray2 = function (uniform, array) {
  6196. if (!uniform || array.length % 2 !== 0)
  6197. return;
  6198. this._gl.uniform2fv(uniform, array);
  6199. };
  6200. Engine.prototype.setArray3 = function (uniform, array) {
  6201. if (!uniform || array.length % 3 !== 0)
  6202. return;
  6203. this._gl.uniform3fv(uniform, array);
  6204. };
  6205. Engine.prototype.setArray4 = function (uniform, array) {
  6206. if (!uniform || array.length % 4 !== 0)
  6207. return;
  6208. this._gl.uniform4fv(uniform, array);
  6209. };
  6210. Engine.prototype.setMatrices = function (uniform, matrices) {
  6211. if (!uniform)
  6212. return;
  6213. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6214. };
  6215. Engine.prototype.setMatrix = function (uniform, matrix) {
  6216. if (!uniform)
  6217. return;
  6218. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6219. };
  6220. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6221. if (!uniform)
  6222. return;
  6223. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6224. };
  6225. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6226. if (!uniform)
  6227. return;
  6228. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6229. };
  6230. Engine.prototype.setFloat = function (uniform, value) {
  6231. if (!uniform)
  6232. return;
  6233. this._gl.uniform1f(uniform, value);
  6234. };
  6235. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6236. if (!uniform)
  6237. return;
  6238. this._gl.uniform2f(uniform, x, y);
  6239. };
  6240. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6241. if (!uniform)
  6242. return;
  6243. this._gl.uniform3f(uniform, x, y, z);
  6244. };
  6245. Engine.prototype.setBool = function (uniform, bool) {
  6246. if (!uniform)
  6247. return;
  6248. this._gl.uniform1i(uniform, bool);
  6249. };
  6250. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6251. if (!uniform)
  6252. return;
  6253. this._gl.uniform4f(uniform, x, y, z, w);
  6254. };
  6255. Engine.prototype.setColor3 = function (uniform, color3) {
  6256. if (!uniform)
  6257. return;
  6258. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6259. };
  6260. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6261. if (!uniform)
  6262. return;
  6263. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6264. };
  6265. // States
  6266. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6267. if (zOffset === void 0) { zOffset = 0; }
  6268. if (reverseSide === void 0) { reverseSide = false; }
  6269. // Culling
  6270. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6271. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6272. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6273. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6274. if (culling) {
  6275. this._depthCullingState.cullFace = cullFace;
  6276. this._depthCullingState.cull = true;
  6277. }
  6278. else {
  6279. this._depthCullingState.cull = false;
  6280. }
  6281. }
  6282. // Z offset
  6283. this._depthCullingState.zOffset = zOffset;
  6284. };
  6285. Engine.prototype.setDepthBuffer = function (enable) {
  6286. this._depthCullingState.depthTest = enable;
  6287. };
  6288. Engine.prototype.getDepthWrite = function () {
  6289. return this._depthCullingState.depthMask;
  6290. };
  6291. Engine.prototype.setDepthWrite = function (enable) {
  6292. this._depthCullingState.depthMask = enable;
  6293. };
  6294. Engine.prototype.setColorWrite = function (enable) {
  6295. this._gl.colorMask(enable, enable, enable, enable);
  6296. };
  6297. Engine.prototype.setAlphaMode = function (mode) {
  6298. if (this._alphaMode === mode) {
  6299. return;
  6300. }
  6301. switch (mode) {
  6302. case Engine.ALPHA_DISABLE:
  6303. this.setDepthWrite(true);
  6304. this._alphaState.alphaBlend = false;
  6305. break;
  6306. case Engine.ALPHA_COMBINE:
  6307. this.setDepthWrite(false);
  6308. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6309. this._alphaState.alphaBlend = true;
  6310. break;
  6311. case Engine.ALPHA_ONEONE:
  6312. this.setDepthWrite(false);
  6313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6314. this._alphaState.alphaBlend = true;
  6315. break;
  6316. case Engine.ALPHA_ADD:
  6317. this.setDepthWrite(false);
  6318. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6319. this._alphaState.alphaBlend = true;
  6320. break;
  6321. case Engine.ALPHA_SUBTRACT:
  6322. this.setDepthWrite(false);
  6323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6324. this._alphaState.alphaBlend = true;
  6325. break;
  6326. case Engine.ALPHA_MULTIPLY:
  6327. this.setDepthWrite(false);
  6328. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6329. this._alphaState.alphaBlend = true;
  6330. break;
  6331. case Engine.ALPHA_MAXIMIZED:
  6332. this.setDepthWrite(false);
  6333. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6334. this._alphaState.alphaBlend = true;
  6335. break;
  6336. }
  6337. this._alphaMode = mode;
  6338. };
  6339. Engine.prototype.getAlphaMode = function () {
  6340. return this._alphaMode;
  6341. };
  6342. Engine.prototype.setAlphaTesting = function (enable) {
  6343. this._alphaTest = enable;
  6344. };
  6345. Engine.prototype.getAlphaTesting = function () {
  6346. return this._alphaTest;
  6347. };
  6348. // Textures
  6349. Engine.prototype.wipeCaches = function () {
  6350. this.resetTextureCache();
  6351. this._currentEffect = null;
  6352. this._depthCullingState.reset();
  6353. this._alphaState.reset();
  6354. this._cachedVertexBuffers = null;
  6355. this._cachedIndexBuffer = null;
  6356. this._cachedEffectForVertexBuffers = null;
  6357. };
  6358. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6359. var gl = this._gl;
  6360. gl.bindTexture(gl.TEXTURE_2D, texture);
  6361. var magFilter = gl.NEAREST;
  6362. var minFilter = gl.NEAREST;
  6363. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6364. magFilter = gl.LINEAR;
  6365. minFilter = gl.LINEAR;
  6366. }
  6367. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6368. magFilter = gl.LINEAR;
  6369. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6370. }
  6371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6373. gl.bindTexture(gl.TEXTURE_2D, null);
  6374. texture.samplingMode = samplingMode;
  6375. };
  6376. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6377. var _this = this;
  6378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6379. if (onLoad === void 0) { onLoad = null; }
  6380. if (onError === void 0) { onError = null; }
  6381. if (buffer === void 0) { buffer = null; }
  6382. var texture = this._gl.createTexture();
  6383. var extension;
  6384. var fromData = false;
  6385. if (url.substr(0, 5) === "data:") {
  6386. fromData = true;
  6387. }
  6388. if (!fromData)
  6389. extension = url.substr(url.length - 4, 4).toLowerCase();
  6390. else {
  6391. var oldUrl = url;
  6392. fromData = oldUrl.split(':');
  6393. url = oldUrl;
  6394. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6395. }
  6396. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6397. var isTGA = (extension === ".tga");
  6398. scene._addPendingData(texture);
  6399. texture.url = url;
  6400. texture.noMipmap = noMipmap;
  6401. texture.references = 1;
  6402. texture.samplingMode = samplingMode;
  6403. this._loadedTexturesCache.push(texture);
  6404. var onerror = function () {
  6405. scene._removePendingData(texture);
  6406. if (onError) {
  6407. onError();
  6408. }
  6409. };
  6410. var callback;
  6411. if (isTGA) {
  6412. callback = function (arrayBuffer) {
  6413. var data = new Uint8Array(arrayBuffer);
  6414. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6415. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6416. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6417. }, onLoad, samplingMode);
  6418. };
  6419. if (!(fromData instanceof Array))
  6420. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6421. callback(arrayBuffer);
  6422. }, onerror, scene.database, true);
  6423. else
  6424. callback(buffer);
  6425. }
  6426. else if (isDDS) {
  6427. callback = function (data) {
  6428. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6429. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6430. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6431. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6432. }, onLoad, samplingMode);
  6433. };
  6434. if (!(fromData instanceof Array))
  6435. BABYLON.Tools.LoadFile(url, function (data) {
  6436. callback(data);
  6437. }, onerror, scene.database, true);
  6438. else
  6439. callback(buffer);
  6440. }
  6441. else {
  6442. var onload = function (img) {
  6443. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6444. var isPot = (img.width === potWidth && img.height === potHeight);
  6445. if (!isPot) {
  6446. _this._prepareWorkingCanvas();
  6447. _this._workingCanvas.width = potWidth;
  6448. _this._workingCanvas.height = potHeight;
  6449. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6450. _this._workingContext.imageSmoothingEnabled = false;
  6451. _this._workingContext.mozImageSmoothingEnabled = false;
  6452. _this._workingContext.oImageSmoothingEnabled = false;
  6453. _this._workingContext.webkitImageSmoothingEnabled = false;
  6454. _this._workingContext.msImageSmoothingEnabled = false;
  6455. }
  6456. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6457. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6458. _this._workingContext.imageSmoothingEnabled = true;
  6459. _this._workingContext.mozImageSmoothingEnabled = true;
  6460. _this._workingContext.oImageSmoothingEnabled = true;
  6461. _this._workingContext.webkitImageSmoothingEnabled = true;
  6462. _this._workingContext.msImageSmoothingEnabled = true;
  6463. }
  6464. }
  6465. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6466. }, onLoad, samplingMode);
  6467. };
  6468. if (!(fromData instanceof Array))
  6469. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6470. else
  6471. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6472. }
  6473. return texture;
  6474. };
  6475. Engine.prototype._getInternalFormat = function (format) {
  6476. var internalFormat = this._gl.RGBA;
  6477. switch (format) {
  6478. case Engine.TEXTUREFORMAT_ALPHA:
  6479. internalFormat = this._gl.ALPHA;
  6480. break;
  6481. case Engine.TEXTUREFORMAT_LUMINANCE:
  6482. internalFormat = this._gl.LUMINANCE;
  6483. break;
  6484. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6485. internalFormat = this._gl.LUMINANCE_ALPHA;
  6486. break;
  6487. case Engine.TEXTUREFORMAT_RGB:
  6488. internalFormat = this._gl.RGB;
  6489. break;
  6490. case Engine.TEXTUREFORMAT_RGBA:
  6491. internalFormat = this._gl.RGBA;
  6492. break;
  6493. }
  6494. return internalFormat;
  6495. };
  6496. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6497. if (compression === void 0) { compression = null; }
  6498. var internalFormat = this._getInternalFormat(format);
  6499. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6500. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6501. if (compression) {
  6502. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6503. }
  6504. else {
  6505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6506. }
  6507. if (texture.generateMipMaps) {
  6508. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6509. }
  6510. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6511. this.resetTextureCache();
  6512. texture.isReady = true;
  6513. };
  6514. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6515. if (compression === void 0) { compression = null; }
  6516. var texture = this._gl.createTexture();
  6517. texture._baseWidth = width;
  6518. texture._baseHeight = height;
  6519. texture._width = width;
  6520. texture._height = height;
  6521. texture.references = 1;
  6522. this.updateRawTexture(texture, data, format, invertY, compression);
  6523. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6524. // Filters
  6525. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6528. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6529. texture.samplingMode = samplingMode;
  6530. this._loadedTexturesCache.push(texture);
  6531. return texture;
  6532. };
  6533. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6534. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6535. var texture = this._gl.createTexture();
  6536. texture._baseWidth = width;
  6537. texture._baseHeight = height;
  6538. if (forceExponantOfTwo) {
  6539. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6540. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6541. }
  6542. this.resetTextureCache();
  6543. texture._width = width;
  6544. texture._height = height;
  6545. texture.isReady = false;
  6546. texture.generateMipMaps = generateMipMaps;
  6547. texture.references = 1;
  6548. texture.samplingMode = samplingMode;
  6549. this.updateTextureSamplingMode(samplingMode, texture);
  6550. this._loadedTexturesCache.push(texture);
  6551. return texture;
  6552. };
  6553. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6554. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6555. if (texture.isCube) {
  6556. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6557. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6558. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6559. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6560. }
  6561. else {
  6562. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6563. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6564. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6566. }
  6567. };
  6568. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6569. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6570. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6571. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6572. if (texture.generateMipMaps) {
  6573. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6574. }
  6575. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6576. this.resetTextureCache();
  6577. texture.isReady = true;
  6578. };
  6579. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6580. if (texture._isDisabled) {
  6581. return;
  6582. }
  6583. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6584. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6585. try {
  6586. // Testing video texture support
  6587. if (this._videoTextureSupported === undefined) {
  6588. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6589. if (this._gl.getError() !== 0) {
  6590. this._videoTextureSupported = false;
  6591. }
  6592. else {
  6593. this._videoTextureSupported = true;
  6594. }
  6595. }
  6596. // Copy video through the current working canvas if video texture is not supported
  6597. if (!this._videoTextureSupported) {
  6598. if (!texture._workingCanvas) {
  6599. texture._workingCanvas = document.createElement("canvas");
  6600. texture._workingContext = texture._workingCanvas.getContext("2d");
  6601. texture._workingCanvas.width = texture._width;
  6602. texture._workingCanvas.height = texture._height;
  6603. }
  6604. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6605. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6606. }
  6607. else {
  6608. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6609. }
  6610. if (texture.generateMipMaps) {
  6611. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6612. }
  6613. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6614. this.resetTextureCache();
  6615. texture.isReady = true;
  6616. }
  6617. catch (ex) {
  6618. // Something unexpected
  6619. // Let's disable the texture
  6620. texture._isDisabled = true;
  6621. }
  6622. };
  6623. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6624. // old version had a "generateMipMaps" arg instead of options.
  6625. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6626. // in the same way, generateDepthBuffer is defaulted to true
  6627. var generateMipMaps = false;
  6628. var generateDepthBuffer = true;
  6629. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6630. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6631. if (options !== undefined) {
  6632. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6633. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6634. type = options.type === undefined ? type : options.type;
  6635. if (options.samplingMode !== undefined) {
  6636. samplingMode = options.samplingMode;
  6637. }
  6638. if (type === Engine.TEXTURETYPE_FLOAT) {
  6639. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6640. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6641. }
  6642. }
  6643. var gl = this._gl;
  6644. var texture = gl.createTexture();
  6645. gl.bindTexture(gl.TEXTURE_2D, texture);
  6646. var width = size.width || size;
  6647. var height = size.height || size;
  6648. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6649. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6650. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6651. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6652. }
  6653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6657. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6658. var depthBuffer;
  6659. // Create the depth buffer
  6660. if (generateDepthBuffer) {
  6661. depthBuffer = gl.createRenderbuffer();
  6662. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6663. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6664. }
  6665. // Create the framebuffer
  6666. var framebuffer = gl.createFramebuffer();
  6667. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6668. if (generateDepthBuffer) {
  6669. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6670. }
  6671. if (generateMipMaps) {
  6672. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6673. }
  6674. // Unbind
  6675. gl.bindTexture(gl.TEXTURE_2D, null);
  6676. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6677. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6678. texture._framebuffer = framebuffer;
  6679. if (generateDepthBuffer) {
  6680. texture._depthBuffer = depthBuffer;
  6681. }
  6682. texture._width = width;
  6683. texture._height = height;
  6684. texture.isReady = true;
  6685. texture.generateMipMaps = generateMipMaps;
  6686. texture.references = 1;
  6687. texture.samplingMode = samplingMode;
  6688. this.resetTextureCache();
  6689. this._loadedTexturesCache.push(texture);
  6690. return texture;
  6691. };
  6692. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6693. var gl = this._gl;
  6694. var texture = gl.createTexture();
  6695. var generateMipMaps = true;
  6696. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6697. if (options !== undefined) {
  6698. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6699. if (options.samplingMode !== undefined) {
  6700. samplingMode = options.samplingMode;
  6701. }
  6702. }
  6703. texture.isCube = true;
  6704. texture.references = 1;
  6705. texture.generateMipMaps = generateMipMaps;
  6706. texture.references = 1;
  6707. texture.samplingMode = samplingMode;
  6708. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6709. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6710. for (var face = 0; face < 6; face++) {
  6711. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6712. }
  6713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6717. // Create the depth buffer
  6718. var depthBuffer = gl.createRenderbuffer();
  6719. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6720. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6721. // Create the framebuffer
  6722. var framebuffer = gl.createFramebuffer();
  6723. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6724. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6725. // Mipmaps
  6726. if (texture.generateMipMaps) {
  6727. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6728. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6729. }
  6730. // Unbind
  6731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6732. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6733. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6734. texture._framebuffer = framebuffer;
  6735. texture._depthBuffer = depthBuffer;
  6736. this.resetTextureCache();
  6737. texture._width = size;
  6738. texture._height = size;
  6739. texture.isReady = true;
  6740. return texture;
  6741. };
  6742. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6743. var _this = this;
  6744. var gl = this._gl;
  6745. var texture = gl.createTexture();
  6746. texture.isCube = true;
  6747. texture.url = rootUrl;
  6748. texture.references = 1;
  6749. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6750. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6751. if (isDDS) {
  6752. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6753. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6754. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6755. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6756. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6757. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6758. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6759. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6760. }
  6761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6765. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6766. _this.resetTextureCache();
  6767. texture._width = info.width;
  6768. texture._height = info.height;
  6769. texture.isReady = true;
  6770. }, null, null, true);
  6771. }
  6772. else {
  6773. cascadeLoad(rootUrl, scene, function (imgs) {
  6774. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6775. var height = width;
  6776. _this._prepareWorkingCanvas();
  6777. _this._workingCanvas.width = width;
  6778. _this._workingCanvas.height = height;
  6779. var faces = [
  6780. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6781. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6782. ];
  6783. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6784. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6785. for (var index = 0; index < faces.length; index++) {
  6786. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6787. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6788. }
  6789. if (!noMipmap) {
  6790. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6791. }
  6792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6796. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6797. _this.resetTextureCache();
  6798. texture._width = width;
  6799. texture._height = height;
  6800. texture.isReady = true;
  6801. }, files);
  6802. }
  6803. return texture;
  6804. };
  6805. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6806. var _this = this;
  6807. var gl = this._gl;
  6808. var texture = gl.createTexture();
  6809. scene._addPendingData(texture);
  6810. texture.isCube = true;
  6811. texture.references = 1;
  6812. texture.url = url;
  6813. var internalFormat = this._getInternalFormat(format);
  6814. var textureType = gl.UNSIGNED_BYTE;
  6815. if (type === Engine.TEXTURETYPE_FLOAT) {
  6816. textureType = gl.FLOAT;
  6817. }
  6818. var width = size;
  6819. var height = width;
  6820. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6821. texture._width = width;
  6822. texture._height = height;
  6823. var onerror = function () {
  6824. scene._removePendingData(texture);
  6825. };
  6826. var internalCallback = function (data) {
  6827. var rgbeDataArrays = callback(data);
  6828. var facesIndex = [
  6829. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6830. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6831. ];
  6832. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6833. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6834. if (!noMipmap && isPot) {
  6835. if (mipmmapGenerator) {
  6836. var arrayTemp = [];
  6837. // Data are known to be in +X +Y +Z -X -Y -Z
  6838. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6839. arrayTemp.push(rgbeDataArrays[0]); // +X
  6840. arrayTemp.push(rgbeDataArrays[3]); // -X
  6841. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6842. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6843. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6844. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6845. var mipData = mipmmapGenerator(arrayTemp);
  6846. for (var level = 0; level < mipData.length; level++) {
  6847. var mipSize = width >> level;
  6848. // mipData is order in +X -X +Y -Y +Z -Z
  6849. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6850. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6851. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6852. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6853. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6854. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6855. }
  6856. }
  6857. else {
  6858. // Data are known to be in +X +Y +Z -X -Y -Z
  6859. for (var index = 0; index < facesIndex.length; index++) {
  6860. var faceData = rgbeDataArrays[index];
  6861. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6862. }
  6863. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6864. }
  6865. }
  6866. else {
  6867. noMipmap = true;
  6868. }
  6869. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6872. }
  6873. else {
  6874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6876. }
  6877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6879. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6880. texture.isReady = true;
  6881. _this.resetTextureCache();
  6882. scene._removePendingData(texture);
  6883. };
  6884. BABYLON.Tools.LoadFile(url, function (data) {
  6885. internalCallback(data);
  6886. }, onerror, scene.database, true);
  6887. return texture;
  6888. };
  6889. ;
  6890. Engine.prototype._releaseTexture = function (texture) {
  6891. var gl = this._gl;
  6892. if (texture._framebuffer) {
  6893. gl.deleteFramebuffer(texture._framebuffer);
  6894. }
  6895. if (texture._depthBuffer) {
  6896. gl.deleteRenderbuffer(texture._depthBuffer);
  6897. }
  6898. gl.deleteTexture(texture);
  6899. // Unbind channels
  6900. this.unbindAllTextures();
  6901. var index = this._loadedTexturesCache.indexOf(texture);
  6902. if (index !== -1) {
  6903. this._loadedTexturesCache.splice(index, 1);
  6904. }
  6905. };
  6906. Engine.prototype.bindSamplers = function (effect) {
  6907. this._gl.useProgram(effect.getProgram());
  6908. var samplers = effect.getSamplers();
  6909. for (var index = 0; index < samplers.length; index++) {
  6910. var uniform = effect.getUniform(samplers[index]);
  6911. this._gl.uniform1i(uniform, index);
  6912. }
  6913. this._currentEffect = null;
  6914. };
  6915. Engine.prototype._bindTexture = function (channel, texture) {
  6916. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6917. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6918. this._activeTexturesCache[channel] = null;
  6919. };
  6920. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6921. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6922. };
  6923. Engine.prototype.unbindAllTextures = function () {
  6924. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6925. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6926. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6927. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6928. this._activeTexturesCache[channel] = null;
  6929. }
  6930. };
  6931. Engine.prototype.setTexture = function (channel, texture) {
  6932. if (channel < 0) {
  6933. return;
  6934. }
  6935. // Not ready?
  6936. if (!texture || !texture.isReady()) {
  6937. if (this._activeTexturesCache[channel] != null) {
  6938. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6939. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6940. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6941. this._activeTexturesCache[channel] = null;
  6942. }
  6943. return;
  6944. }
  6945. // Video
  6946. var alreadyActivated = false;
  6947. if (texture instanceof BABYLON.VideoTexture) {
  6948. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6949. alreadyActivated = true;
  6950. texture.update();
  6951. }
  6952. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6953. texture.delayLoad();
  6954. return;
  6955. }
  6956. if (this._activeTexturesCache[channel] === texture) {
  6957. return;
  6958. }
  6959. this._activeTexturesCache[channel] = texture;
  6960. var internalTexture = texture.getInternalTexture();
  6961. if (!alreadyActivated) {
  6962. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6963. }
  6964. if (internalTexture.isCube) {
  6965. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6966. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6967. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6968. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6969. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6970. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6971. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6972. }
  6973. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6974. }
  6975. else {
  6976. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6977. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6978. internalTexture._cachedWrapU = texture.wrapU;
  6979. switch (texture.wrapU) {
  6980. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6981. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6982. break;
  6983. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6984. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6985. break;
  6986. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6987. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6988. break;
  6989. }
  6990. }
  6991. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6992. internalTexture._cachedWrapV = texture.wrapV;
  6993. switch (texture.wrapV) {
  6994. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6996. break;
  6997. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6998. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6999. break;
  7000. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7001. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7002. break;
  7003. }
  7004. }
  7005. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7006. }
  7007. };
  7008. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7009. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7010. var value = texture.anisotropicFilteringLevel;
  7011. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7012. value = 1;
  7013. }
  7014. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7015. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7016. texture._cachedAnisotropicFilteringLevel = value;
  7017. }
  7018. };
  7019. Engine.prototype.readPixels = function (x, y, width, height) {
  7020. var data = new Uint8Array(height * width * 4);
  7021. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7022. return data;
  7023. };
  7024. Engine.prototype.releaseInternalTexture = function (texture) {
  7025. if (!texture) {
  7026. return;
  7027. }
  7028. texture.references--;
  7029. // Final reference ?
  7030. if (texture.references === 0) {
  7031. var texturesCache = this.getLoadedTexturesCache();
  7032. var index = texturesCache.indexOf(texture);
  7033. if (index > -1) {
  7034. texturesCache.splice(index, 1);
  7035. }
  7036. this._releaseTexture(texture);
  7037. }
  7038. };
  7039. // Dispose
  7040. Engine.prototype.dispose = function () {
  7041. this.hideLoadingUI();
  7042. this.stopRenderLoop();
  7043. // Release scenes
  7044. while (this.scenes.length) {
  7045. this.scenes[0].dispose();
  7046. }
  7047. // Release audio engine
  7048. Engine.audioEngine.dispose();
  7049. // Release effects
  7050. for (var name in this._compiledEffects) {
  7051. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7052. }
  7053. // Unbind
  7054. for (var i in this._vertexAttribArrays) {
  7055. //making sure this is a string
  7056. var iAsNumber = +i;
  7057. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7058. continue;
  7059. }
  7060. this._gl.disableVertexAttribArray(iAsNumber);
  7061. }
  7062. this._gl = null;
  7063. // Events
  7064. window.removeEventListener("blur", this._onBlur);
  7065. window.removeEventListener("focus", this._onFocus);
  7066. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7067. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7068. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7069. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7070. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7071. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7072. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7073. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7074. };
  7075. // Loading screen
  7076. Engine.prototype.displayLoadingUI = function () {
  7077. this._loadingScreen.displayLoadingUI();
  7078. };
  7079. Engine.prototype.hideLoadingUI = function () {
  7080. this._loadingScreen.hideLoadingUI();
  7081. };
  7082. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7083. get: function () {
  7084. return this._loadingScreen;
  7085. },
  7086. set: function (loadingScreen) {
  7087. this._loadingScreen = loadingScreen;
  7088. },
  7089. enumerable: true,
  7090. configurable: true
  7091. });
  7092. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7093. set: function (text) {
  7094. this._loadingScreen.loadingUIText = text;
  7095. },
  7096. enumerable: true,
  7097. configurable: true
  7098. });
  7099. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7100. set: function (color) {
  7101. this._loadingScreen.loadingUIBackgroundColor = color;
  7102. },
  7103. enumerable: true,
  7104. configurable: true
  7105. });
  7106. // FPS
  7107. Engine.prototype.getFps = function () {
  7108. return this.fps;
  7109. };
  7110. Engine.prototype.getDeltaTime = function () {
  7111. return this.deltaTime;
  7112. };
  7113. Engine.prototype._measureFps = function () {
  7114. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7115. var length = this.previousFramesDuration.length;
  7116. if (length >= 2) {
  7117. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7118. }
  7119. if (length >= this.fpsRange) {
  7120. if (length > this.fpsRange) {
  7121. this.previousFramesDuration.splice(0, 1);
  7122. length = this.previousFramesDuration.length;
  7123. }
  7124. var sum = 0;
  7125. for (var id = 0; id < length - 1; id++) {
  7126. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7127. }
  7128. this.fps = 1000.0 / (sum / (length - 1));
  7129. }
  7130. };
  7131. // Statics
  7132. Engine.isSupported = function () {
  7133. try {
  7134. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7135. if (navigator.isCocoonJS) {
  7136. return true;
  7137. }
  7138. var tempcanvas = document.createElement("canvas");
  7139. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7140. return gl != null && !!window.WebGLRenderingContext;
  7141. }
  7142. catch (e) {
  7143. return false;
  7144. }
  7145. };
  7146. // Const statics
  7147. Engine._ALPHA_DISABLE = 0;
  7148. Engine._ALPHA_ADD = 1;
  7149. Engine._ALPHA_COMBINE = 2;
  7150. Engine._ALPHA_SUBTRACT = 3;
  7151. Engine._ALPHA_MULTIPLY = 4;
  7152. Engine._ALPHA_MAXIMIZED = 5;
  7153. Engine._ALPHA_ONEONE = 6;
  7154. Engine._DELAYLOADSTATE_NONE = 0;
  7155. Engine._DELAYLOADSTATE_LOADED = 1;
  7156. Engine._DELAYLOADSTATE_LOADING = 2;
  7157. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7158. Engine._TEXTUREFORMAT_ALPHA = 0;
  7159. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7160. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7161. Engine._TEXTUREFORMAT_RGB = 4;
  7162. Engine._TEXTUREFORMAT_RGBA = 5;
  7163. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7164. Engine._TEXTURETYPE_FLOAT = 1;
  7165. // Updatable statics so stick with vars here
  7166. Engine.CollisionsEpsilon = 0.001;
  7167. Engine.CodeRepository = "src/";
  7168. Engine.ShadersRepository = "src/Shaders/";
  7169. return Engine;
  7170. })();
  7171. BABYLON.Engine = Engine;
  7172. })(BABYLON || (BABYLON = {}));
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. /**
  7176. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7177. */
  7178. var Node = (function () {
  7179. /**
  7180. * @constructor
  7181. * @param {string} name - the name and id to be given to this node
  7182. * @param {BABYLON.Scene} the scene this node will be added to
  7183. */
  7184. function Node(name, scene) {
  7185. this.state = "";
  7186. this.animations = new Array();
  7187. this._ranges = {};
  7188. this._childrenFlag = -1;
  7189. this._isEnabled = true;
  7190. this._isReady = true;
  7191. this._currentRenderId = -1;
  7192. this._parentRenderId = -1;
  7193. this.name = name;
  7194. this.id = name;
  7195. this._scene = scene;
  7196. this._initCache();
  7197. }
  7198. Object.defineProperty(Node.prototype, "parent", {
  7199. get: function () {
  7200. return this._parentNode;
  7201. },
  7202. set: function (parent) {
  7203. if (this._parentNode === parent) {
  7204. return;
  7205. }
  7206. if (this._parentNode) {
  7207. var index = this._parentNode._children.indexOf(this);
  7208. if (index !== -1) {
  7209. this._parentNode._children.splice(index, 1);
  7210. }
  7211. }
  7212. this._parentNode = parent;
  7213. if (this._parentNode) {
  7214. if (!this._parentNode._children) {
  7215. this._parentNode._children = new Array();
  7216. }
  7217. this._parentNode._children.push(this);
  7218. }
  7219. },
  7220. enumerable: true,
  7221. configurable: true
  7222. });
  7223. Node.prototype.getScene = function () {
  7224. return this._scene;
  7225. };
  7226. Node.prototype.getEngine = function () {
  7227. return this._scene.getEngine();
  7228. };
  7229. // override it in derived class
  7230. Node.prototype.getWorldMatrix = function () {
  7231. return BABYLON.Matrix.Identity();
  7232. };
  7233. // override it in derived class if you add new variables to the cache
  7234. // and call the parent class method
  7235. Node.prototype._initCache = function () {
  7236. this._cache = {};
  7237. this._cache.parent = undefined;
  7238. };
  7239. Node.prototype.updateCache = function (force) {
  7240. if (!force && this.isSynchronized())
  7241. return;
  7242. this._cache.parent = this.parent;
  7243. this._updateCache();
  7244. };
  7245. // override it in derived class if you add new variables to the cache
  7246. // and call the parent class method if !ignoreParentClass
  7247. Node.prototype._updateCache = function (ignoreParentClass) {
  7248. };
  7249. // override it in derived class if you add new variables to the cache
  7250. Node.prototype._isSynchronized = function () {
  7251. return true;
  7252. };
  7253. Node.prototype._markSyncedWithParent = function () {
  7254. this._parentRenderId = this.parent._currentRenderId;
  7255. };
  7256. Node.prototype.isSynchronizedWithParent = function () {
  7257. if (!this.parent) {
  7258. return true;
  7259. }
  7260. if (this._parentRenderId !== this.parent._currentRenderId) {
  7261. return false;
  7262. }
  7263. return this.parent.isSynchronized();
  7264. };
  7265. Node.prototype.isSynchronized = function (updateCache) {
  7266. var check = this.hasNewParent();
  7267. check = check || !this.isSynchronizedWithParent();
  7268. check = check || !this._isSynchronized();
  7269. if (updateCache)
  7270. this.updateCache(true);
  7271. return !check;
  7272. };
  7273. Node.prototype.hasNewParent = function (update) {
  7274. if (this._cache.parent === this.parent)
  7275. return false;
  7276. if (update)
  7277. this._cache.parent = this.parent;
  7278. return true;
  7279. };
  7280. /**
  7281. * Is this node ready to be used/rendered
  7282. * @return {boolean} is it ready
  7283. */
  7284. Node.prototype.isReady = function () {
  7285. return this._isReady;
  7286. };
  7287. /**
  7288. * Is this node enabled.
  7289. * If the node has a parent and is enabled, the parent will be inspected as well.
  7290. * @return {boolean} whether this node (and its parent) is enabled.
  7291. * @see setEnabled
  7292. */
  7293. Node.prototype.isEnabled = function () {
  7294. if (!this._isEnabled) {
  7295. return false;
  7296. }
  7297. if (this.parent) {
  7298. return this.parent.isEnabled();
  7299. }
  7300. return true;
  7301. };
  7302. /**
  7303. * Set the enabled state of this node.
  7304. * @param {boolean} value - the new enabled state
  7305. * @see isEnabled
  7306. */
  7307. Node.prototype.setEnabled = function (value) {
  7308. this._isEnabled = value;
  7309. };
  7310. /**
  7311. * Is this node a descendant of the given node.
  7312. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7313. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7314. * @see parent
  7315. */
  7316. Node.prototype.isDescendantOf = function (ancestor) {
  7317. if (this.parent) {
  7318. if (this.parent === ancestor) {
  7319. return true;
  7320. }
  7321. return this.parent.isDescendantOf(ancestor);
  7322. }
  7323. return false;
  7324. };
  7325. /**
  7326. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7327. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7328. * @param {boolean} directDescendantsOnly 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.
  7329. * @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.
  7330. */
  7331. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7332. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7333. if (!this._children) {
  7334. return;
  7335. }
  7336. for (var index = 0; index < this._children.length; index++) {
  7337. var item = this._children[index];
  7338. if (!predicate || predicate(item)) {
  7339. results.push(item);
  7340. }
  7341. if (!directDescendantsOnly) {
  7342. item._getDescendants(results, false, predicate);
  7343. }
  7344. }
  7345. };
  7346. /**
  7347. * Will return all nodes that have this node as ascendant.
  7348. * @param {boolean} directDescendantsOnly 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.
  7349. * @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.
  7350. * @return {BABYLON.Node[]} all children nodes of all types.
  7351. */
  7352. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7353. var results = [];
  7354. this._getDescendants(results, directDescendantsOnly, predicate);
  7355. return results;
  7356. };
  7357. /**
  7358. * @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.
  7359. * @Deprecated, legacy support.
  7360. * use getDecendants instead.
  7361. */
  7362. Node.prototype.getChildren = function (predicate) {
  7363. return this.getDescendants(true, predicate);
  7364. };
  7365. /**
  7366. * Get all child-meshes of this node.
  7367. */
  7368. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7369. var results = [];
  7370. this._getDescendants(results, directDecendantsOnly, function (node) {
  7371. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7372. });
  7373. return results;
  7374. };
  7375. Node.prototype._setReady = function (state) {
  7376. if (state === this._isReady) {
  7377. return;
  7378. }
  7379. if (!state) {
  7380. this._isReady = false;
  7381. return;
  7382. }
  7383. this._isReady = true;
  7384. if (this.onReady) {
  7385. this.onReady(this);
  7386. }
  7387. };
  7388. Node.prototype.getAnimationByName = function (name) {
  7389. for (var i = 0; i < this.animations.length; i++) {
  7390. var animation = this.animations[i];
  7391. if (animation.name === name) {
  7392. return animation;
  7393. }
  7394. }
  7395. return null;
  7396. };
  7397. Node.prototype.createAnimationRange = function (name, from, to) {
  7398. // check name not already in use
  7399. if (!this._ranges[name]) {
  7400. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7401. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7402. if (this.animations[i]) {
  7403. this.animations[i].createRange(name, from, to);
  7404. }
  7405. }
  7406. }
  7407. };
  7408. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7409. if (deleteFrames === void 0) { deleteFrames = true; }
  7410. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7411. if (this.animations[i]) {
  7412. this.animations[i].deleteRange(name, deleteFrames);
  7413. }
  7414. }
  7415. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7416. };
  7417. Node.prototype.getAnimationRange = function (name) {
  7418. return this._ranges[name];
  7419. };
  7420. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7421. var range = this.getAnimationRange(name);
  7422. if (!range) {
  7423. return null;
  7424. }
  7425. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7426. };
  7427. Node.prototype.serializeAnimationRanges = function () {
  7428. var serializationRanges = [];
  7429. for (var name in this._ranges) {
  7430. var range = {};
  7431. range.name = name;
  7432. range.from = this._ranges[name].from;
  7433. range.to = this._ranges[name].to;
  7434. serializationRanges.push(range);
  7435. }
  7436. return serializationRanges;
  7437. };
  7438. Node.prototype.dispose = function () {
  7439. this.parent = null;
  7440. };
  7441. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7442. if (parsedNode.ranges) {
  7443. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7444. var data = parsedNode.ranges[index];
  7445. node.createAnimationRange(data.name, data.from, data.to);
  7446. }
  7447. }
  7448. };
  7449. __decorate([
  7450. BABYLON.serialize()
  7451. ], Node.prototype, "name", void 0);
  7452. __decorate([
  7453. BABYLON.serialize()
  7454. ], Node.prototype, "id", void 0);
  7455. __decorate([
  7456. BABYLON.serialize()
  7457. ], Node.prototype, "uniqueId", void 0);
  7458. __decorate([
  7459. BABYLON.serialize()
  7460. ], Node.prototype, "state", void 0);
  7461. return Node;
  7462. })();
  7463. BABYLON.Node = Node;
  7464. })(BABYLON || (BABYLON = {}));
  7465. var BABYLON;
  7466. (function (BABYLON) {
  7467. var FilesInput = (function () {
  7468. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7469. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7470. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7471. this._engine = p_engine;
  7472. this._canvas = p_canvas;
  7473. this._currentScene = p_scene;
  7474. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7475. this._progressCallback = p_progressCallback;
  7476. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7477. this._textureLoadingCallback = p_textureLoadingCallback;
  7478. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7479. }
  7480. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7481. var _this = this;
  7482. if (p_elementToMonitor) {
  7483. this._elementToMonitor = p_elementToMonitor;
  7484. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7485. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7486. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7487. }
  7488. };
  7489. FilesInput.prototype.renderFunction = function () {
  7490. if (this._additionnalRenderLoopLogicCallback) {
  7491. this._additionnalRenderLoopLogicCallback();
  7492. }
  7493. if (this._currentScene) {
  7494. if (this._textureLoadingCallback) {
  7495. var remaining = this._currentScene.getWaitingItemsCount();
  7496. if (remaining > 0) {
  7497. this._textureLoadingCallback(remaining);
  7498. }
  7499. }
  7500. this._currentScene.render();
  7501. }
  7502. };
  7503. FilesInput.prototype.drag = function (e) {
  7504. e.stopPropagation();
  7505. e.preventDefault();
  7506. };
  7507. FilesInput.prototype.drop = function (eventDrop) {
  7508. eventDrop.stopPropagation();
  7509. eventDrop.preventDefault();
  7510. this.loadFiles(eventDrop);
  7511. };
  7512. FilesInput.prototype.loadFiles = function (event) {
  7513. if (this._startingProcessingFilesCallback)
  7514. this._startingProcessingFilesCallback();
  7515. // Handling data transfer via drag'n'drop
  7516. if (event && event.dataTransfer && event.dataTransfer.files) {
  7517. this._filesToLoad = event.dataTransfer.files;
  7518. }
  7519. // Handling files from input files
  7520. if (event && event.target && event.target.files) {
  7521. this._filesToLoad = event.target.files;
  7522. }
  7523. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7524. for (var i = 0; i < this._filesToLoad.length; i++) {
  7525. switch (this._filesToLoad[i].type) {
  7526. case "image/jpeg":
  7527. case "image/png":
  7528. case "image/bmp":
  7529. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7530. break;
  7531. case "image/targa":
  7532. case "image/vnd.ms-dds":
  7533. case "audio/wav":
  7534. case "audio/x-wav":
  7535. case "audio/mp3":
  7536. case "audio/mpeg":
  7537. case "audio/mpeg3":
  7538. case "audio/x-mpeg-3":
  7539. case "audio/ogg":
  7540. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7541. break;
  7542. default:
  7543. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7544. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7545. }
  7546. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7547. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7548. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7549. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7550. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7551. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7552. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7553. this._sceneFileToLoad = this._filesToLoad[i];
  7554. }
  7555. break;
  7556. }
  7557. }
  7558. this.reload();
  7559. }
  7560. };
  7561. FilesInput.prototype.reload = function () {
  7562. var _this = this;
  7563. var that = this;
  7564. // If a ".babylon" file has been provided
  7565. if (this._sceneFileToLoad) {
  7566. if (this._currentScene) {
  7567. if (BABYLON.Tools.errorsCount > 0) {
  7568. BABYLON.Tools.ClearLogCache();
  7569. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7570. }
  7571. this._engine.stopRenderLoop();
  7572. this._currentScene.dispose();
  7573. }
  7574. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7575. that._currentScene = newScene;
  7576. // Wait for textures and shaders to be ready
  7577. that._currentScene.executeWhenReady(function () {
  7578. // Attach camera to canvas inputs
  7579. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7580. that._currentScene.createDefaultCameraOrLight();
  7581. }
  7582. that._currentScene.activeCamera.attachControl(that._canvas);
  7583. if (that._sceneLoadedCallback) {
  7584. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7585. }
  7586. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7587. });
  7588. }, function (progress) {
  7589. if (_this._progressCallback) {
  7590. _this._progressCallback(progress);
  7591. }
  7592. });
  7593. }
  7594. else {
  7595. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7596. }
  7597. };
  7598. FilesInput.FilesTextures = new Array();
  7599. FilesInput.FilesToLoad = new Array();
  7600. return FilesInput;
  7601. })();
  7602. BABYLON.FilesInput = FilesInput;
  7603. })(BABYLON || (BABYLON = {}));
  7604. var BABYLON;
  7605. (function (BABYLON) {
  7606. var IntersectionInfo = (function () {
  7607. function IntersectionInfo(bu, bv, distance) {
  7608. this.bu = bu;
  7609. this.bv = bv;
  7610. this.distance = distance;
  7611. this.faceId = 0;
  7612. this.subMeshId = 0;
  7613. }
  7614. return IntersectionInfo;
  7615. })();
  7616. BABYLON.IntersectionInfo = IntersectionInfo;
  7617. var PickingInfo = (function () {
  7618. function PickingInfo() {
  7619. this.hit = false;
  7620. this.distance = 0;
  7621. this.pickedPoint = null;
  7622. this.pickedMesh = null;
  7623. this.bu = 0;
  7624. this.bv = 0;
  7625. this.faceId = -1;
  7626. this.subMeshId = 0;
  7627. this.pickedSprite = null;
  7628. }
  7629. // Methods
  7630. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7631. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7632. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7633. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7634. return null;
  7635. }
  7636. var indices = this.pickedMesh.getIndices();
  7637. var result;
  7638. if (useVerticesNormals) {
  7639. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7640. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7641. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7642. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7643. normal0 = normal0.scale(this.bu);
  7644. normal1 = normal1.scale(this.bv);
  7645. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7646. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7647. }
  7648. else {
  7649. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7650. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7651. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7652. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7653. var p1p2 = vertex1.subtract(vertex2);
  7654. var p3p2 = vertex3.subtract(vertex2);
  7655. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7656. }
  7657. if (useWorldCoordinates) {
  7658. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7659. }
  7660. return BABYLON.Vector3.Normalize(result);
  7661. };
  7662. PickingInfo.prototype.getTextureCoordinates = function () {
  7663. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7664. return null;
  7665. }
  7666. var indices = this.pickedMesh.getIndices();
  7667. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7668. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7669. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7670. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7671. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7672. uv1 = uv1.scale(this.bu);
  7673. uv2 = uv2.scale(this.bv);
  7674. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7675. };
  7676. return PickingInfo;
  7677. })();
  7678. BABYLON.PickingInfo = PickingInfo;
  7679. })(BABYLON || (BABYLON = {}));
  7680. var BABYLON;
  7681. (function (BABYLON) {
  7682. var BoundingSphere = (function () {
  7683. function BoundingSphere(minimum, maximum) {
  7684. this.minimum = minimum;
  7685. this.maximum = maximum;
  7686. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7687. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7688. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7689. this.radius = distance * 0.5;
  7690. this.centerWorld = BABYLON.Vector3.Zero();
  7691. this._update(BABYLON.Matrix.Identity());
  7692. }
  7693. // Methods
  7694. BoundingSphere.prototype._update = function (world) {
  7695. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7696. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7697. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7698. };
  7699. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7700. for (var i = 0; i < 6; i++) {
  7701. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7702. return false;
  7703. }
  7704. return true;
  7705. };
  7706. BoundingSphere.prototype.intersectsPoint = function (point) {
  7707. var x = this.centerWorld.x - point.x;
  7708. var y = this.centerWorld.y - point.y;
  7709. var z = this.centerWorld.z - point.z;
  7710. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7711. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7712. return false;
  7713. return true;
  7714. };
  7715. // Statics
  7716. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7717. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7718. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7719. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7720. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7721. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7722. return false;
  7723. return true;
  7724. };
  7725. return BoundingSphere;
  7726. })();
  7727. BABYLON.BoundingSphere = BoundingSphere;
  7728. })(BABYLON || (BABYLON = {}));
  7729. var BABYLON;
  7730. (function (BABYLON) {
  7731. var BoundingBox = (function () {
  7732. function BoundingBox(minimum, maximum) {
  7733. this.minimum = minimum;
  7734. this.maximum = maximum;
  7735. this.vectors = new Array();
  7736. this.vectorsWorld = new Array();
  7737. // Bounding vectors
  7738. this.vectors.push(this.minimum.clone());
  7739. this.vectors.push(this.maximum.clone());
  7740. this.vectors.push(this.minimum.clone());
  7741. this.vectors[2].x = this.maximum.x;
  7742. this.vectors.push(this.minimum.clone());
  7743. this.vectors[3].y = this.maximum.y;
  7744. this.vectors.push(this.minimum.clone());
  7745. this.vectors[4].z = this.maximum.z;
  7746. this.vectors.push(this.maximum.clone());
  7747. this.vectors[5].z = this.minimum.z;
  7748. this.vectors.push(this.maximum.clone());
  7749. this.vectors[6].x = this.minimum.x;
  7750. this.vectors.push(this.maximum.clone());
  7751. this.vectors[7].y = this.minimum.y;
  7752. // OBB
  7753. this.center = this.maximum.add(this.minimum).scale(0.5);
  7754. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7755. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7756. // World
  7757. for (var index = 0; index < this.vectors.length; index++) {
  7758. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7759. }
  7760. this.minimumWorld = BABYLON.Vector3.Zero();
  7761. this.maximumWorld = BABYLON.Vector3.Zero();
  7762. this._update(BABYLON.Matrix.Identity());
  7763. }
  7764. // Methods
  7765. BoundingBox.prototype.getWorldMatrix = function () {
  7766. return this._worldMatrix;
  7767. };
  7768. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7769. this._worldMatrix.copyFrom(matrix);
  7770. return this;
  7771. };
  7772. BoundingBox.prototype._update = function (world) {
  7773. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7774. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7775. for (var index = 0; index < this.vectors.length; index++) {
  7776. var v = this.vectorsWorld[index];
  7777. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7778. if (v.x < this.minimumWorld.x)
  7779. this.minimumWorld.x = v.x;
  7780. if (v.y < this.minimumWorld.y)
  7781. this.minimumWorld.y = v.y;
  7782. if (v.z < this.minimumWorld.z)
  7783. this.minimumWorld.z = v.z;
  7784. if (v.x > this.maximumWorld.x)
  7785. this.maximumWorld.x = v.x;
  7786. if (v.y > this.maximumWorld.y)
  7787. this.maximumWorld.y = v.y;
  7788. if (v.z > this.maximumWorld.z)
  7789. this.maximumWorld.z = v.z;
  7790. }
  7791. // OBB
  7792. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7793. this.center.scaleInPlace(0.5);
  7794. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7795. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7796. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7797. this._worldMatrix = world;
  7798. };
  7799. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7800. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7801. };
  7802. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7803. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7804. };
  7805. BoundingBox.prototype.intersectsPoint = function (point) {
  7806. var delta = -BABYLON.Epsilon;
  7807. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7808. return false;
  7809. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7810. return false;
  7811. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7812. return false;
  7813. return true;
  7814. };
  7815. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7816. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7817. };
  7818. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7819. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7820. return false;
  7821. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7822. return false;
  7823. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7824. return false;
  7825. return true;
  7826. };
  7827. // Statics
  7828. BoundingBox.Intersects = function (box0, box1) {
  7829. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7830. return false;
  7831. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7832. return false;
  7833. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7834. return false;
  7835. return true;
  7836. };
  7837. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7838. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7839. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7840. return (num <= (sphereRadius * sphereRadius));
  7841. };
  7842. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7843. for (var p = 0; p < 6; p++) {
  7844. for (var i = 0; i < 8; i++) {
  7845. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7846. return false;
  7847. }
  7848. }
  7849. }
  7850. return true;
  7851. };
  7852. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7853. for (var p = 0; p < 6; p++) {
  7854. var inCount = 8;
  7855. for (var i = 0; i < 8; i++) {
  7856. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7857. --inCount;
  7858. }
  7859. else {
  7860. break;
  7861. }
  7862. }
  7863. if (inCount === 0)
  7864. return false;
  7865. }
  7866. return true;
  7867. };
  7868. return BoundingBox;
  7869. })();
  7870. BABYLON.BoundingBox = BoundingBox;
  7871. })(BABYLON || (BABYLON = {}));
  7872. var BABYLON;
  7873. (function (BABYLON) {
  7874. var computeBoxExtents = function (axis, box) {
  7875. var p = BABYLON.Vector3.Dot(box.center, axis);
  7876. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7877. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7878. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7879. var r = r0 + r1 + r2;
  7880. return {
  7881. min: p - r,
  7882. max: p + r
  7883. };
  7884. };
  7885. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7886. var axisOverlap = function (axis, box0, box1) {
  7887. var result0 = computeBoxExtents(axis, box0);
  7888. var result1 = computeBoxExtents(axis, box1);
  7889. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7890. };
  7891. var BoundingInfo = (function () {
  7892. function BoundingInfo(minimum, maximum) {
  7893. this.minimum = minimum;
  7894. this.maximum = maximum;
  7895. this._isLocked = false;
  7896. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7897. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7898. }
  7899. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7900. get: function () {
  7901. return this._isLocked;
  7902. },
  7903. set: function (value) {
  7904. this._isLocked = value;
  7905. },
  7906. enumerable: true,
  7907. configurable: true
  7908. });
  7909. // Methods
  7910. BoundingInfo.prototype.update = function (world) {
  7911. if (this._isLocked) {
  7912. return;
  7913. }
  7914. this.boundingBox._update(world);
  7915. this.boundingSphere._update(world);
  7916. };
  7917. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7918. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7919. return false;
  7920. return this.boundingBox.isInFrustum(frustumPlanes);
  7921. };
  7922. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7923. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7924. };
  7925. BoundingInfo.prototype._checkCollision = function (collider) {
  7926. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7927. };
  7928. BoundingInfo.prototype.intersectsPoint = function (point) {
  7929. if (!this.boundingSphere.centerWorld) {
  7930. return false;
  7931. }
  7932. if (!this.boundingSphere.intersectsPoint(point)) {
  7933. return false;
  7934. }
  7935. if (!this.boundingBox.intersectsPoint(point)) {
  7936. return false;
  7937. }
  7938. return true;
  7939. };
  7940. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7941. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7942. return false;
  7943. }
  7944. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7945. return false;
  7946. }
  7947. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7948. return false;
  7949. }
  7950. if (!precise) {
  7951. return true;
  7952. }
  7953. var box0 = this.boundingBox;
  7954. var box1 = boundingInfo.boundingBox;
  7955. if (!axisOverlap(box0.directions[0], box0, box1))
  7956. return false;
  7957. if (!axisOverlap(box0.directions[1], box0, box1))
  7958. return false;
  7959. if (!axisOverlap(box0.directions[2], box0, box1))
  7960. return false;
  7961. if (!axisOverlap(box1.directions[0], box0, box1))
  7962. return false;
  7963. if (!axisOverlap(box1.directions[1], box0, box1))
  7964. return false;
  7965. if (!axisOverlap(box1.directions[2], box0, box1))
  7966. return false;
  7967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7968. return false;
  7969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7970. return false;
  7971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7972. return false;
  7973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7974. return false;
  7975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7976. return false;
  7977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7978. return false;
  7979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7980. return false;
  7981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7982. return false;
  7983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7984. return false;
  7985. return true;
  7986. };
  7987. return BoundingInfo;
  7988. })();
  7989. BABYLON.BoundingInfo = BoundingInfo;
  7990. })(BABYLON || (BABYLON = {}));
  7991. var BABYLON;
  7992. (function (BABYLON) {
  7993. var Ray = (function () {
  7994. function Ray(origin, direction, length) {
  7995. if (length === void 0) { length = Number.MAX_VALUE; }
  7996. this.origin = origin;
  7997. this.direction = direction;
  7998. this.length = length;
  7999. }
  8000. // Methods
  8001. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8002. var d = 0.0;
  8003. var maxValue = Number.MAX_VALUE;
  8004. var inv;
  8005. var min;
  8006. var max;
  8007. var temp;
  8008. if (Math.abs(this.direction.x) < 0.0000001) {
  8009. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8010. return false;
  8011. }
  8012. }
  8013. else {
  8014. inv = 1.0 / this.direction.x;
  8015. min = (minimum.x - this.origin.x) * inv;
  8016. max = (maximum.x - this.origin.x) * inv;
  8017. if (max === -Infinity) {
  8018. max = Infinity;
  8019. }
  8020. if (min > max) {
  8021. temp = min;
  8022. min = max;
  8023. max = temp;
  8024. }
  8025. d = Math.max(min, d);
  8026. maxValue = Math.min(max, maxValue);
  8027. if (d > maxValue) {
  8028. return false;
  8029. }
  8030. }
  8031. if (Math.abs(this.direction.y) < 0.0000001) {
  8032. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8033. return false;
  8034. }
  8035. }
  8036. else {
  8037. inv = 1.0 / this.direction.y;
  8038. min = (minimum.y - this.origin.y) * inv;
  8039. max = (maximum.y - this.origin.y) * inv;
  8040. if (max === -Infinity) {
  8041. max = Infinity;
  8042. }
  8043. if (min > max) {
  8044. temp = min;
  8045. min = max;
  8046. max = temp;
  8047. }
  8048. d = Math.max(min, d);
  8049. maxValue = Math.min(max, maxValue);
  8050. if (d > maxValue) {
  8051. return false;
  8052. }
  8053. }
  8054. if (Math.abs(this.direction.z) < 0.0000001) {
  8055. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8056. return false;
  8057. }
  8058. }
  8059. else {
  8060. inv = 1.0 / this.direction.z;
  8061. min = (minimum.z - this.origin.z) * inv;
  8062. max = (maximum.z - this.origin.z) * inv;
  8063. if (max === -Infinity) {
  8064. max = Infinity;
  8065. }
  8066. if (min > max) {
  8067. temp = min;
  8068. min = max;
  8069. max = temp;
  8070. }
  8071. d = Math.max(min, d);
  8072. maxValue = Math.min(max, maxValue);
  8073. if (d > maxValue) {
  8074. return false;
  8075. }
  8076. }
  8077. return true;
  8078. };
  8079. Ray.prototype.intersectsBox = function (box) {
  8080. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8081. };
  8082. Ray.prototype.intersectsSphere = function (sphere) {
  8083. var x = sphere.center.x - this.origin.x;
  8084. var y = sphere.center.y - this.origin.y;
  8085. var z = sphere.center.z - this.origin.z;
  8086. var pyth = (x * x) + (y * y) + (z * z);
  8087. var rr = sphere.radius * sphere.radius;
  8088. if (pyth <= rr) {
  8089. return true;
  8090. }
  8091. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8092. if (dot < 0.0) {
  8093. return false;
  8094. }
  8095. var temp = pyth - (dot * dot);
  8096. return temp <= rr;
  8097. };
  8098. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8099. if (!this._edge1) {
  8100. this._edge1 = BABYLON.Vector3.Zero();
  8101. this._edge2 = BABYLON.Vector3.Zero();
  8102. this._pvec = BABYLON.Vector3.Zero();
  8103. this._tvec = BABYLON.Vector3.Zero();
  8104. this._qvec = BABYLON.Vector3.Zero();
  8105. }
  8106. vertex1.subtractToRef(vertex0, this._edge1);
  8107. vertex2.subtractToRef(vertex0, this._edge2);
  8108. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8109. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8110. if (det === 0) {
  8111. return null;
  8112. }
  8113. var invdet = 1 / det;
  8114. this.origin.subtractToRef(vertex0, this._tvec);
  8115. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8116. if (bu < 0 || bu > 1.0) {
  8117. return null;
  8118. }
  8119. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8120. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8121. if (bv < 0 || bu + bv > 1.0) {
  8122. return null;
  8123. }
  8124. //check if the distance is longer than the predefined length.
  8125. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8126. if (distance > this.length) {
  8127. return null;
  8128. }
  8129. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8130. };
  8131. // Statics
  8132. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8133. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8134. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8135. var direction = end.subtract(start);
  8136. direction.normalize();
  8137. return new Ray(start, direction);
  8138. };
  8139. /**
  8140. * 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
  8141. * transformed to the given world matrix.
  8142. * @param origin The origin point
  8143. * @param end The end point
  8144. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8145. */
  8146. Ray.CreateNewFromTo = function (origin, end, world) {
  8147. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8148. var direction = end.subtract(origin);
  8149. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8150. direction.normalize();
  8151. return Ray.Transform(new Ray(origin, direction, length), world);
  8152. };
  8153. Ray.Transform = function (ray, matrix) {
  8154. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8155. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8156. return new Ray(newOrigin, newDirection, ray.length);
  8157. };
  8158. return Ray;
  8159. })();
  8160. BABYLON.Ray = Ray;
  8161. })(BABYLON || (BABYLON = {}));
  8162. var BABYLON;
  8163. (function (BABYLON) {
  8164. var AbstractMesh = (function (_super) {
  8165. __extends(AbstractMesh, _super);
  8166. // Constructor
  8167. function AbstractMesh(name, scene) {
  8168. var _this = this;
  8169. _super.call(this, name, scene);
  8170. // Events
  8171. /**
  8172. * An event triggered when this mesh collides with another one
  8173. * @type {BABYLON.Observable}
  8174. */
  8175. this.onCollideObservable = new BABYLON.Observable();
  8176. /**
  8177. * An event triggered when the collision's position changes
  8178. * @type {BABYLON.Observable}
  8179. */
  8180. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8181. /**
  8182. * An event triggered after the world matrix is updated
  8183. * @type {BABYLON.Observable}
  8184. */
  8185. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8186. // Properties
  8187. this.definedFacingForward = true; // orientation for POV movement & rotation
  8188. this.position = new BABYLON.Vector3(0, 0, 0);
  8189. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8190. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8191. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8192. this.visibility = 1.0;
  8193. this.alphaIndex = Number.MAX_VALUE;
  8194. this.infiniteDistance = false;
  8195. this.isVisible = true;
  8196. this.isPickable = true;
  8197. this.showBoundingBox = false;
  8198. this.showSubMeshesBoundingBox = false;
  8199. this.onDispose = null;
  8200. this.isBlocker = false;
  8201. this.renderingGroupId = 0;
  8202. this.receiveShadows = false;
  8203. this.renderOutline = false;
  8204. this.outlineColor = BABYLON.Color3.Red();
  8205. this.outlineWidth = 0.02;
  8206. this.renderOverlay = false;
  8207. this.overlayColor = BABYLON.Color3.Red();
  8208. this.overlayAlpha = 0.5;
  8209. this.hasVertexAlpha = false;
  8210. this.useVertexColors = true;
  8211. this.applyFog = true;
  8212. this.computeBonesUsingShaders = true;
  8213. this.scalingDeterminant = 1;
  8214. this.numBoneInfluencers = 4;
  8215. this.useOctreeForRenderingSelection = true;
  8216. this.useOctreeForPicking = true;
  8217. this.useOctreeForCollisions = true;
  8218. this.layerMask = 0x0FFFFFFF;
  8219. this.alwaysSelectAsActiveMesh = false;
  8220. // Collisions
  8221. this._checkCollisions = false;
  8222. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8223. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8224. this._collider = new BABYLON.Collider();
  8225. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8226. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8227. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8228. // Edges
  8229. this.edgesWidth = 1;
  8230. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8231. // Cache
  8232. this._localWorld = BABYLON.Matrix.Zero();
  8233. this._worldMatrix = BABYLON.Matrix.Zero();
  8234. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8235. this._absolutePosition = BABYLON.Vector3.Zero();
  8236. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8237. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8238. this._isDirty = false;
  8239. this._pivotMatrix = BABYLON.Matrix.Identity();
  8240. this._isDisposed = false;
  8241. this._renderId = 0;
  8242. this._intersectionsInProgress = new Array();
  8243. this._isWorldMatrixFrozen = false;
  8244. this._unIndexed = false;
  8245. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8246. if (collidedMesh === void 0) { collidedMesh = null; }
  8247. //TODO move this to the collision coordinator!
  8248. if (_this.getScene().workerCollisions)
  8249. newPosition.multiplyInPlace(_this._collider.radius);
  8250. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8251. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8252. _this.position.addInPlace(_this._diffPositionForCollisions);
  8253. }
  8254. if (collidedMesh) {
  8255. _this.onCollideObservable.notifyObservers(collidedMesh);
  8256. }
  8257. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8258. };
  8259. scene.addMesh(this);
  8260. }
  8261. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8262. get: function () {
  8263. return AbstractMesh._BILLBOARDMODE_NONE;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8269. get: function () {
  8270. return AbstractMesh._BILLBOARDMODE_X;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8276. get: function () {
  8277. return AbstractMesh._BILLBOARDMODE_Y;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8283. get: function () {
  8284. return AbstractMesh._BILLBOARDMODE_Z;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8290. get: function () {
  8291. return AbstractMesh._BILLBOARDMODE_ALL;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8297. set: function (callback) {
  8298. if (this._onCollideObserver) {
  8299. this.onCollideObservable.remove(this._onCollideObserver);
  8300. }
  8301. this._onCollideObserver = this.onCollideObservable.add(callback);
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8307. set: function (callback) {
  8308. if (this._onCollisionPositionChangeObserver) {
  8309. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8310. }
  8311. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8317. get: function () {
  8318. return this._skeleton;
  8319. },
  8320. set: function (value) {
  8321. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8322. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8323. }
  8324. if (value && value.needInitialSkinMatrix) {
  8325. value._registerMeshWithPoseMatrix(this);
  8326. }
  8327. this._skeleton = value;
  8328. if (!this._skeleton) {
  8329. this._bonesTransformMatrices = null;
  8330. }
  8331. },
  8332. enumerable: true,
  8333. configurable: true
  8334. });
  8335. /**
  8336. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8337. */
  8338. AbstractMesh.prototype.toString = function (fullDetails) {
  8339. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8340. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8341. if (this._skeleton) {
  8342. ret += ", skeleton: " + this._skeleton.name;
  8343. }
  8344. if (fullDetails) {
  8345. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8346. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8347. }
  8348. return ret;
  8349. };
  8350. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8351. /**
  8352. * Getting the rotation object.
  8353. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8354. */
  8355. get: function () {
  8356. return this._rotation;
  8357. },
  8358. set: function (newRotation) {
  8359. this._rotation = newRotation;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8365. get: function () {
  8366. return this._scaling;
  8367. },
  8368. set: function (newScaling) {
  8369. this._scaling = newScaling;
  8370. if (this.physicsImpostor) {
  8371. this.physicsImpostor.forceUpdate();
  8372. }
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8378. get: function () {
  8379. return this._rotationQuaternion;
  8380. },
  8381. set: function (quaternion) {
  8382. this._rotationQuaternion = quaternion;
  8383. //reset the rotation vector.
  8384. if (quaternion && this.rotation.length()) {
  8385. this.rotation.copyFromFloats(0, 0, 0);
  8386. }
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. // Methods
  8392. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8393. this._poseMatrix.copyFrom(matrix);
  8394. };
  8395. AbstractMesh.prototype.getPoseMatrix = function () {
  8396. return this._poseMatrix;
  8397. };
  8398. AbstractMesh.prototype.disableEdgesRendering = function () {
  8399. if (this._edgesRenderer !== undefined) {
  8400. this._edgesRenderer.dispose();
  8401. this._edgesRenderer = undefined;
  8402. }
  8403. };
  8404. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8405. if (epsilon === void 0) { epsilon = 0.95; }
  8406. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8407. this.disableEdgesRendering();
  8408. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8409. };
  8410. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8411. get: function () {
  8412. return false;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. AbstractMesh.prototype.getLOD = function (camera) {
  8418. return this;
  8419. };
  8420. AbstractMesh.prototype.getTotalVertices = function () {
  8421. return 0;
  8422. };
  8423. AbstractMesh.prototype.getIndices = function () {
  8424. return null;
  8425. };
  8426. AbstractMesh.prototype.getVerticesData = function (kind) {
  8427. return null;
  8428. };
  8429. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8430. return false;
  8431. };
  8432. AbstractMesh.prototype.getBoundingInfo = function () {
  8433. if (this._masterMesh) {
  8434. return this._masterMesh.getBoundingInfo();
  8435. }
  8436. if (!this._boundingInfo) {
  8437. this._updateBoundingInfo();
  8438. }
  8439. return this._boundingInfo;
  8440. };
  8441. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8442. get: function () {
  8443. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. AbstractMesh.prototype._preActivate = function () {
  8449. };
  8450. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8451. };
  8452. AbstractMesh.prototype._activate = function (renderId) {
  8453. this._renderId = renderId;
  8454. };
  8455. AbstractMesh.prototype.getWorldMatrix = function () {
  8456. if (this._masterMesh) {
  8457. return this._masterMesh.getWorldMatrix();
  8458. }
  8459. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8460. this.computeWorldMatrix();
  8461. }
  8462. return this._worldMatrix;
  8463. };
  8464. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8465. get: function () {
  8466. return this._worldMatrix;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8472. get: function () {
  8473. return this._absolutePosition;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8479. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8480. this.computeWorldMatrix(true);
  8481. this._isWorldMatrixFrozen = true;
  8482. };
  8483. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8484. this._isWorldMatrixFrozen = false;
  8485. this.computeWorldMatrix(true);
  8486. };
  8487. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8488. get: function () {
  8489. return this._isWorldMatrixFrozen;
  8490. },
  8491. enumerable: true,
  8492. configurable: true
  8493. });
  8494. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8495. axis.normalize();
  8496. if (!this.rotationQuaternion) {
  8497. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8498. this.rotation = BABYLON.Vector3.Zero();
  8499. }
  8500. var rotationQuaternion;
  8501. if (!space || space === BABYLON.Space.LOCAL) {
  8502. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8503. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8504. }
  8505. else {
  8506. if (this.parent) {
  8507. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8508. invertParentWorldMatrix.invert();
  8509. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8510. }
  8511. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8512. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8513. }
  8514. };
  8515. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8516. var displacementVector = axis.scale(distance);
  8517. if (!space || space === BABYLON.Space.LOCAL) {
  8518. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8519. this.setPositionWithLocalVector(tempV3);
  8520. }
  8521. else {
  8522. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8523. }
  8524. };
  8525. AbstractMesh.prototype.getAbsolutePosition = function () {
  8526. this.computeWorldMatrix();
  8527. return this._absolutePosition;
  8528. };
  8529. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8530. if (!absolutePosition) {
  8531. return;
  8532. }
  8533. var absolutePositionX;
  8534. var absolutePositionY;
  8535. var absolutePositionZ;
  8536. if (absolutePosition.x === undefined) {
  8537. if (arguments.length < 3) {
  8538. return;
  8539. }
  8540. absolutePositionX = arguments[0];
  8541. absolutePositionY = arguments[1];
  8542. absolutePositionZ = arguments[2];
  8543. }
  8544. else {
  8545. absolutePositionX = absolutePosition.x;
  8546. absolutePositionY = absolutePosition.y;
  8547. absolutePositionZ = absolutePosition.z;
  8548. }
  8549. if (this.parent) {
  8550. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8551. invertParentWorldMatrix.invert();
  8552. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8553. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8554. }
  8555. else {
  8556. this.position.x = absolutePositionX;
  8557. this.position.y = absolutePositionY;
  8558. this.position.z = absolutePositionZ;
  8559. }
  8560. };
  8561. // ================================== Point of View Movement =================================
  8562. /**
  8563. * Perform relative position change from the point of view of behind the front of the mesh.
  8564. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8565. * Supports definition of mesh facing forward or backward.
  8566. * @param {number} amountRight
  8567. * @param {number} amountUp
  8568. * @param {number} amountForward
  8569. */
  8570. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8571. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8572. };
  8573. /**
  8574. * Calculate relative position change from the point of view of behind the front of the mesh.
  8575. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8576. * Supports definition of mesh facing forward or backward.
  8577. * @param {number} amountRight
  8578. * @param {number} amountUp
  8579. * @param {number} amountForward
  8580. */
  8581. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8582. var rotMatrix = new BABYLON.Matrix();
  8583. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8584. rotQuaternion.toRotationMatrix(rotMatrix);
  8585. var translationDelta = BABYLON.Vector3.Zero();
  8586. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8588. return translationDelta;
  8589. };
  8590. // ================================== Point of View Rotation =================================
  8591. /**
  8592. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8593. * Supports definition of mesh facing forward or backward.
  8594. * @param {number} flipBack
  8595. * @param {number} twirlClockwise
  8596. * @param {number} tiltRight
  8597. */
  8598. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8599. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8600. };
  8601. /**
  8602. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8603. * Supports definition of mesh facing forward or backward.
  8604. * @param {number} flipBack
  8605. * @param {number} twirlClockwise
  8606. * @param {number} tiltRight
  8607. */
  8608. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8609. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8610. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8611. };
  8612. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8613. this._pivotMatrix = matrix;
  8614. this._cache.pivotMatrixUpdated = true;
  8615. };
  8616. AbstractMesh.prototype.getPivotMatrix = function () {
  8617. return this._pivotMatrix;
  8618. };
  8619. AbstractMesh.prototype._isSynchronized = function () {
  8620. if (this._isDirty) {
  8621. return false;
  8622. }
  8623. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8624. return false;
  8625. if (this._cache.pivotMatrixUpdated) {
  8626. return false;
  8627. }
  8628. if (this.infiniteDistance) {
  8629. return false;
  8630. }
  8631. if (!this._cache.position.equals(this.position))
  8632. return false;
  8633. if (this.rotationQuaternion) {
  8634. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8635. return false;
  8636. }
  8637. else {
  8638. if (!this._cache.rotation.equals(this.rotation))
  8639. return false;
  8640. }
  8641. if (!this._cache.scaling.equals(this.scaling))
  8642. return false;
  8643. return true;
  8644. };
  8645. AbstractMesh.prototype._initCache = function () {
  8646. _super.prototype._initCache.call(this);
  8647. this._cache.localMatrixUpdated = false;
  8648. this._cache.position = BABYLON.Vector3.Zero();
  8649. this._cache.scaling = BABYLON.Vector3.Zero();
  8650. this._cache.rotation = BABYLON.Vector3.Zero();
  8651. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8652. this._cache.billboardMode = -1;
  8653. };
  8654. AbstractMesh.prototype.markAsDirty = function (property) {
  8655. if (property === "rotation") {
  8656. this.rotationQuaternion = null;
  8657. }
  8658. this._currentRenderId = Number.MAX_VALUE;
  8659. this._isDirty = true;
  8660. };
  8661. AbstractMesh.prototype._updateBoundingInfo = function () {
  8662. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8663. this._boundingInfo.update(this.worldMatrixFromCache);
  8664. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8665. };
  8666. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8667. if (!this.subMeshes) {
  8668. return;
  8669. }
  8670. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8671. var subMesh = this.subMeshes[subIndex];
  8672. if (!subMesh.IsGlobal) {
  8673. subMesh.updateBoundingInfo(matrix);
  8674. }
  8675. }
  8676. };
  8677. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8678. if (this._isWorldMatrixFrozen) {
  8679. return this._worldMatrix;
  8680. }
  8681. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8682. this._currentRenderId = this.getScene().getRenderId();
  8683. return this._worldMatrix;
  8684. }
  8685. this._cache.position.copyFrom(this.position);
  8686. this._cache.scaling.copyFrom(this.scaling);
  8687. this._cache.pivotMatrixUpdated = false;
  8688. this._cache.billboardMode = this.billboardMode;
  8689. this._currentRenderId = this.getScene().getRenderId();
  8690. this._isDirty = false;
  8691. // Scaling
  8692. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8693. // Rotation
  8694. //rotate, if quaternion is set and rotation was used
  8695. if (this.rotationQuaternion) {
  8696. var len = this.rotation.length();
  8697. if (len) {
  8698. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8699. this.rotation.copyFromFloats(0, 0, 0);
  8700. }
  8701. }
  8702. if (this.rotationQuaternion) {
  8703. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8704. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8705. }
  8706. else {
  8707. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8708. this._cache.rotation.copyFrom(this.rotation);
  8709. }
  8710. // Translation
  8711. if (this.infiniteDistance && !this.parent) {
  8712. var camera = this.getScene().activeCamera;
  8713. if (camera) {
  8714. var cameraWorldMatrix = camera.getWorldMatrix();
  8715. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8716. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8717. }
  8718. }
  8719. else {
  8720. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8721. }
  8722. // Composing transformations
  8723. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8724. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8725. // Billboarding
  8726. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8727. var localPosition = this.position.clone();
  8728. var zero = this.getScene().activeCamera.globalPosition.clone();
  8729. if (this.parent && this.parent.position) {
  8730. localPosition.addInPlace(this.parent.position);
  8731. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8732. }
  8733. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8734. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8735. zero.x = localPosition.x + BABYLON.Epsilon;
  8736. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8737. zero.y = localPosition.y + BABYLON.Epsilon;
  8738. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8739. zero.z = localPosition.z + BABYLON.Epsilon;
  8740. }
  8741. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8742. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8743. BABYLON.Tmp.Matrix[3].invert();
  8744. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8745. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8746. }
  8747. // Local world
  8748. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8749. // Parent
  8750. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8751. this._markSyncedWithParent();
  8752. if (this._meshToBoneReferal) {
  8753. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8754. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8755. }
  8756. else {
  8757. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8758. }
  8759. }
  8760. else {
  8761. this._worldMatrix.copyFrom(this._localWorld);
  8762. }
  8763. // Bounding info
  8764. this._updateBoundingInfo();
  8765. // Absolute position
  8766. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8767. // Callbacks
  8768. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8769. if (!this._poseMatrix) {
  8770. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8771. }
  8772. return this._worldMatrix;
  8773. };
  8774. /**
  8775. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8776. * @param func: callback function to add
  8777. */
  8778. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8779. this.onAfterWorldMatrixUpdateObservable.add(func);
  8780. };
  8781. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8782. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8783. };
  8784. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8785. this.computeWorldMatrix();
  8786. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8787. };
  8788. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8789. this.computeWorldMatrix();
  8790. var invLocalWorldMatrix = this._localWorld.clone();
  8791. invLocalWorldMatrix.invert();
  8792. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8793. };
  8794. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8795. this.computeWorldMatrix(true);
  8796. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8797. };
  8798. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8799. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8800. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8801. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8802. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8803. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8804. /// <returns>Mesh oriented towards targetMesh</returns>
  8805. yawCor = yawCor || 0; // default to zero if undefined
  8806. pitchCor = pitchCor || 0;
  8807. rollCor = rollCor || 0;
  8808. var dv = targetPoint.subtract(this.position);
  8809. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8810. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8811. var pitch = Math.atan2(dv.y, len);
  8812. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8813. };
  8814. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8815. this._meshToBoneReferal = affectedMesh;
  8816. this.parent = bone;
  8817. if (bone.getWorldMatrix().determinant() < 0) {
  8818. this.scalingDeterminant *= -1;
  8819. }
  8820. };
  8821. AbstractMesh.prototype.detachFromBone = function () {
  8822. if (this.parent.getWorldMatrix().determinant() < 0) {
  8823. this.scalingDeterminant *= -1;
  8824. }
  8825. this._meshToBoneReferal = null;
  8826. this.parent = null;
  8827. };
  8828. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8829. return this._boundingInfo.isInFrustum(frustumPlanes);
  8830. };
  8831. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8832. if (!camera) {
  8833. camera = this.getScene().activeCamera;
  8834. }
  8835. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8836. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8837. return false;
  8838. }
  8839. return true;
  8840. };
  8841. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8842. if (!this._boundingInfo || !mesh._boundingInfo) {
  8843. return false;
  8844. }
  8845. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8846. };
  8847. AbstractMesh.prototype.intersectsPoint = function (point) {
  8848. if (!this._boundingInfo) {
  8849. return false;
  8850. }
  8851. return this._boundingInfo.intersectsPoint(point);
  8852. };
  8853. // Physics
  8854. /**
  8855. * @Deprecated. Use new PhysicsImpostor instead.
  8856. * */
  8857. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8858. //legacy support
  8859. if (impostor.impostor) {
  8860. options = impostor;
  8861. impostor = impostor.impostor;
  8862. }
  8863. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  8864. return this.physicsImpostor.physicsBody;
  8865. };
  8866. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8867. return this.physicsImpostor;
  8868. };
  8869. /**
  8870. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8871. */
  8872. AbstractMesh.prototype.getPhysicsMass = function () {
  8873. return this.physicsImpostor.getParam("mass");
  8874. };
  8875. /**
  8876. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8877. */
  8878. AbstractMesh.prototype.getPhysicsFriction = function () {
  8879. return this.physicsImpostor.getParam("friction");
  8880. };
  8881. /**
  8882. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8883. */
  8884. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8885. return this.physicsImpostor.getParam("resitution");
  8886. };
  8887. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8888. if (!camera) {
  8889. camera = this.getScene().activeCamera;
  8890. }
  8891. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8892. };
  8893. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8894. if (!camera) {
  8895. camera = this.getScene().activeCamera;
  8896. }
  8897. return this.absolutePosition.subtract(camera.position).length();
  8898. };
  8899. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8900. if (!this.physicsImpostor) {
  8901. return;
  8902. }
  8903. this.physicsImpostor.applyImpulse(force, contactPoint);
  8904. };
  8905. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8906. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8907. return;
  8908. }
  8909. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8910. mainPivot: pivot1,
  8911. connectedPivot: pivot2,
  8912. nativeParams: options
  8913. });
  8914. };
  8915. /**
  8916. * @Deprecated
  8917. */
  8918. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8919. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8920. this.updatePhysicsBody();
  8921. };
  8922. /**
  8923. * @Deprecated
  8924. * Calling this function is not needed anymore.
  8925. * The physics engine takes care of transofmration automatically.
  8926. */
  8927. AbstractMesh.prototype.updatePhysicsBody = function () {
  8928. //Unneeded
  8929. };
  8930. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8931. // Collisions
  8932. get: function () {
  8933. return this._checkCollisions;
  8934. },
  8935. set: function (collisionEnabled) {
  8936. this._checkCollisions = collisionEnabled;
  8937. if (this.getScene().workerCollisions) {
  8938. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8939. }
  8940. },
  8941. enumerable: true,
  8942. configurable: true
  8943. });
  8944. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8945. var globalPosition = this.getAbsolutePosition();
  8946. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8947. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8948. this._collider.radius = this.ellipsoid;
  8949. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8950. };
  8951. // Submeshes octree
  8952. /**
  8953. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8954. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8955. */
  8956. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8957. if (maxCapacity === void 0) { maxCapacity = 64; }
  8958. if (maxDepth === void 0) { maxDepth = 2; }
  8959. if (!this._submeshesOctree) {
  8960. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8961. }
  8962. this.computeWorldMatrix(true);
  8963. // Update octree
  8964. var bbox = this.getBoundingInfo().boundingBox;
  8965. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8966. return this._submeshesOctree;
  8967. };
  8968. // Collisions
  8969. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8970. this._generatePointsArray();
  8971. // Transformation
  8972. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8973. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8974. subMesh._lastColliderWorldVertices = [];
  8975. subMesh._trianglePlanes = [];
  8976. var start = subMesh.verticesStart;
  8977. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8978. for (var i = start; i < end; i++) {
  8979. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8980. }
  8981. }
  8982. // Collide
  8983. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8984. if (collider.collisionFound) {
  8985. collider.collidedMesh = this;
  8986. }
  8987. };
  8988. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8989. var subMeshes;
  8990. var len;
  8991. // Octrees
  8992. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8993. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8994. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8995. len = intersections.length;
  8996. subMeshes = intersections.data;
  8997. }
  8998. else {
  8999. subMeshes = this.subMeshes;
  9000. len = subMeshes.length;
  9001. }
  9002. for (var index = 0; index < len; index++) {
  9003. var subMesh = subMeshes[index];
  9004. // Bounding test
  9005. if (len > 1 && !subMesh._checkCollision(collider))
  9006. continue;
  9007. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9008. }
  9009. };
  9010. AbstractMesh.prototype._checkCollision = function (collider) {
  9011. // Bounding box test
  9012. if (!this._boundingInfo._checkCollision(collider))
  9013. return;
  9014. // Transformation matrix
  9015. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9016. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9017. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9018. };
  9019. // Picking
  9020. AbstractMesh.prototype._generatePointsArray = function () {
  9021. return false;
  9022. };
  9023. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9024. var pickingInfo = new BABYLON.PickingInfo();
  9025. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9026. return pickingInfo;
  9027. }
  9028. if (!this._generatePointsArray()) {
  9029. return pickingInfo;
  9030. }
  9031. var intersectInfo = null;
  9032. // Octrees
  9033. var subMeshes;
  9034. var len;
  9035. if (this._submeshesOctree && this.useOctreeForPicking) {
  9036. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9037. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9038. len = intersections.length;
  9039. subMeshes = intersections.data;
  9040. }
  9041. else {
  9042. subMeshes = this.subMeshes;
  9043. len = subMeshes.length;
  9044. }
  9045. for (var index = 0; index < len; index++) {
  9046. var subMesh = subMeshes[index];
  9047. // Bounding test
  9048. if (len > 1 && !subMesh.canIntersects(ray))
  9049. continue;
  9050. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9051. if (currentIntersectInfo) {
  9052. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9053. intersectInfo = currentIntersectInfo;
  9054. intersectInfo.subMeshId = index;
  9055. if (fastCheck) {
  9056. break;
  9057. }
  9058. }
  9059. }
  9060. }
  9061. if (intersectInfo) {
  9062. // Get picked point
  9063. var world = this.getWorldMatrix();
  9064. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9065. var direction = ray.direction.clone();
  9066. direction = direction.scale(intersectInfo.distance);
  9067. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9068. var pickedPoint = worldOrigin.add(worldDirection);
  9069. // Return result
  9070. pickingInfo.hit = true;
  9071. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9072. pickingInfo.pickedPoint = pickedPoint;
  9073. pickingInfo.pickedMesh = this;
  9074. pickingInfo.bu = intersectInfo.bu;
  9075. pickingInfo.bv = intersectInfo.bv;
  9076. pickingInfo.faceId = intersectInfo.faceId;
  9077. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9078. return pickingInfo;
  9079. }
  9080. return pickingInfo;
  9081. };
  9082. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9083. return null;
  9084. };
  9085. AbstractMesh.prototype.releaseSubMeshes = function () {
  9086. if (this.subMeshes) {
  9087. while (this.subMeshes.length) {
  9088. this.subMeshes[0].dispose();
  9089. }
  9090. }
  9091. else {
  9092. this.subMeshes = new Array();
  9093. }
  9094. };
  9095. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9096. var _this = this;
  9097. var index;
  9098. // Action manager
  9099. if (this.actionManager) {
  9100. this.actionManager.dispose();
  9101. this.actionManager = null;
  9102. }
  9103. // Skeleton
  9104. this.skeleton = null;
  9105. // Animations
  9106. this.getScene().stopAnimation(this);
  9107. // Physics
  9108. if (this.physicsImpostor) {
  9109. this.physicsImpostor.dispose();
  9110. }
  9111. // Intersections in progress
  9112. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9113. var other = this._intersectionsInProgress[index];
  9114. var pos = other._intersectionsInProgress.indexOf(this);
  9115. other._intersectionsInProgress.splice(pos, 1);
  9116. }
  9117. this._intersectionsInProgress = [];
  9118. // Lights
  9119. var lights = this.getScene().lights;
  9120. lights.forEach(function (light) {
  9121. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9122. if (meshIndex !== -1) {
  9123. light.includedOnlyMeshes.splice(meshIndex, 1);
  9124. }
  9125. meshIndex = light.excludedMeshes.indexOf(_this);
  9126. if (meshIndex !== -1) {
  9127. light.excludedMeshes.splice(meshIndex, 1);
  9128. }
  9129. });
  9130. // Edges
  9131. if (this._edgesRenderer) {
  9132. this._edgesRenderer.dispose();
  9133. this._edgesRenderer = null;
  9134. }
  9135. // SubMeshes
  9136. this.releaseSubMeshes();
  9137. // Remove from scene
  9138. this.getScene().removeMesh(this);
  9139. if (!doNotRecurse) {
  9140. // Particles
  9141. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9142. if (this.getScene().particleSystems[index].emitter === this) {
  9143. this.getScene().particleSystems[index].dispose();
  9144. index--;
  9145. }
  9146. }
  9147. // Children
  9148. var objects = this.getDescendants(true);
  9149. for (index = 0; index < objects.length; index++) {
  9150. objects[index].dispose();
  9151. }
  9152. }
  9153. else {
  9154. var childMeshes = this.getChildMeshes(true);
  9155. for (index = 0; childMeshes.length; index++) {
  9156. var child = childMeshes[index];
  9157. child.parent = null;
  9158. child.computeWorldMatrix(true);
  9159. }
  9160. }
  9161. _super.prototype.dispose.call(this);
  9162. this.onAfterWorldMatrixUpdateObservable.clear();
  9163. this._isDisposed = true;
  9164. // Callback
  9165. if (this.onDispose) {
  9166. this.onDispose();
  9167. }
  9168. };
  9169. // Statics
  9170. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9171. AbstractMesh._BILLBOARDMODE_X = 1;
  9172. AbstractMesh._BILLBOARDMODE_Y = 2;
  9173. AbstractMesh._BILLBOARDMODE_Z = 4;
  9174. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9175. return AbstractMesh;
  9176. })(BABYLON.Node);
  9177. BABYLON.AbstractMesh = AbstractMesh;
  9178. })(BABYLON || (BABYLON = {}));
  9179. var BABYLON;
  9180. (function (BABYLON) {
  9181. var Light = (function (_super) {
  9182. __extends(Light, _super);
  9183. function Light(name, scene) {
  9184. _super.call(this, name, scene);
  9185. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9186. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9187. this.intensity = 1.0;
  9188. this.range = Number.MAX_VALUE;
  9189. this.includeOnlyWithLayerMask = 0;
  9190. this.includedOnlyMeshes = new Array();
  9191. this.excludedMeshes = new Array();
  9192. this.excludeWithLayerMask = 0;
  9193. // PBR Properties.
  9194. this.radius = 0.00001;
  9195. this._excludedMeshesIds = new Array();
  9196. this._includedOnlyMeshesIds = new Array();
  9197. scene.addLight(this);
  9198. }
  9199. /**
  9200. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9201. */
  9202. Light.prototype.toString = function (fullDetails) {
  9203. var ret = "Name: " + this.name;
  9204. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9205. if (this.animations) {
  9206. for (var i = 0; i < this.animations.length; i++) {
  9207. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9208. }
  9209. }
  9210. if (fullDetails) {
  9211. }
  9212. return ret;
  9213. };
  9214. Light.prototype.getShadowGenerator = function () {
  9215. return this._shadowGenerator;
  9216. };
  9217. Light.prototype.getAbsolutePosition = function () {
  9218. return BABYLON.Vector3.Zero();
  9219. };
  9220. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9221. };
  9222. Light.prototype._getWorldMatrix = function () {
  9223. return BABYLON.Matrix.Identity();
  9224. };
  9225. Light.prototype.canAffectMesh = function (mesh) {
  9226. if (!mesh) {
  9227. return true;
  9228. }
  9229. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9230. return false;
  9231. }
  9232. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9233. return false;
  9234. }
  9235. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9236. return false;
  9237. }
  9238. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9239. return false;
  9240. }
  9241. return true;
  9242. };
  9243. Light.prototype.getWorldMatrix = function () {
  9244. this._currentRenderId = this.getScene().getRenderId();
  9245. var worldMatrix = this._getWorldMatrix();
  9246. if (this.parent && this.parent.getWorldMatrix) {
  9247. if (!this._parentedWorldMatrix) {
  9248. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9249. }
  9250. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9251. this._markSyncedWithParent();
  9252. return this._parentedWorldMatrix;
  9253. }
  9254. return worldMatrix;
  9255. };
  9256. Light.prototype.dispose = function () {
  9257. if (this._shadowGenerator) {
  9258. this._shadowGenerator.dispose();
  9259. this._shadowGenerator = null;
  9260. }
  9261. // Animations
  9262. this.getScene().stopAnimation(this);
  9263. // Remove from scene
  9264. this.getScene().removeLight(this);
  9265. _super.prototype.dispose.call(this);
  9266. };
  9267. Light.prototype.getTypeID = function () {
  9268. return 0;
  9269. };
  9270. Light.prototype.clone = function (name) {
  9271. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9272. };
  9273. Light.prototype.serialize = function () {
  9274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9275. // Type
  9276. serializationObject.type = this.getTypeID();
  9277. // Parent
  9278. if (this.parent) {
  9279. serializationObject.parentId = this.parent.id;
  9280. }
  9281. // Inclusion / exclusions
  9282. if (this.excludedMeshes.length > 0) {
  9283. serializationObject.excludedMeshesIds = [];
  9284. this.excludedMeshes.forEach(function (mesh) {
  9285. serializationObject.excludedMeshesIds.push(mesh.id);
  9286. });
  9287. }
  9288. if (this.includedOnlyMeshes.length > 0) {
  9289. serializationObject.includedOnlyMeshesIds = [];
  9290. this.includedOnlyMeshes.forEach(function (mesh) {
  9291. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9292. });
  9293. }
  9294. // Animations
  9295. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9296. serializationObject.ranges = this.serializeAnimationRanges();
  9297. return serializationObject;
  9298. };
  9299. Light.GetConstructorFromName = function (type, name, scene) {
  9300. switch (type) {
  9301. case 0:
  9302. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9303. case 1:
  9304. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9305. case 2:
  9306. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9307. case 3:
  9308. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9309. }
  9310. };
  9311. Light.Parse = function (parsedLight, scene) {
  9312. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9313. // Inclusion / exclusions
  9314. if (parsedLight.excludedMeshesIds) {
  9315. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9316. }
  9317. if (parsedLight.includedOnlyMeshesIds) {
  9318. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9319. }
  9320. // Parent
  9321. if (parsedLight.parentId) {
  9322. light._waitingParentId = parsedLight.parentId;
  9323. }
  9324. // Animations
  9325. if (parsedLight.animations) {
  9326. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9327. var parsedAnimation = parsedLight.animations[animationIndex];
  9328. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9329. }
  9330. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9331. }
  9332. if (parsedLight.autoAnimate) {
  9333. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9334. }
  9335. return light;
  9336. };
  9337. __decorate([
  9338. BABYLON.serializeAsColor3()
  9339. ], Light.prototype, "diffuse", void 0);
  9340. __decorate([
  9341. BABYLON.serializeAsColor3()
  9342. ], Light.prototype, "specular", void 0);
  9343. __decorate([
  9344. BABYLON.serialize()
  9345. ], Light.prototype, "intensity", void 0);
  9346. __decorate([
  9347. BABYLON.serialize()
  9348. ], Light.prototype, "range", void 0);
  9349. __decorate([
  9350. BABYLON.serialize()
  9351. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9352. __decorate([
  9353. BABYLON.serialize()
  9354. ], Light.prototype, "excludeWithLayerMask", void 0);
  9355. __decorate([
  9356. BABYLON.serialize()
  9357. ], Light.prototype, "radius", void 0);
  9358. return Light;
  9359. })(BABYLON.Node);
  9360. BABYLON.Light = Light;
  9361. })(BABYLON || (BABYLON = {}));
  9362. var BABYLON;
  9363. (function (BABYLON) {
  9364. var PointLight = (function (_super) {
  9365. __extends(PointLight, _super);
  9366. function PointLight(name, position, scene) {
  9367. _super.call(this, name, scene);
  9368. this.position = position;
  9369. }
  9370. PointLight.prototype.getAbsolutePosition = function () {
  9371. return this.transformedPosition ? this.transformedPosition : this.position;
  9372. };
  9373. PointLight.prototype.computeTransformedPosition = function () {
  9374. if (this.parent && this.parent.getWorldMatrix) {
  9375. if (!this.transformedPosition) {
  9376. this.transformedPosition = BABYLON.Vector3.Zero();
  9377. }
  9378. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9379. return true;
  9380. }
  9381. return false;
  9382. };
  9383. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9384. if (this.parent && this.parent.getWorldMatrix) {
  9385. this.computeTransformedPosition();
  9386. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9387. return;
  9388. }
  9389. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9390. };
  9391. PointLight.prototype.needCube = function () {
  9392. return true;
  9393. };
  9394. PointLight.prototype.supportsVSM = function () {
  9395. return false;
  9396. };
  9397. PointLight.prototype.needRefreshPerFrame = function () {
  9398. return false;
  9399. };
  9400. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9401. switch (faceIndex) {
  9402. case 0:
  9403. return new BABYLON.Vector3(1, 0, 0);
  9404. case 1:
  9405. return new BABYLON.Vector3(-1, 0, 0);
  9406. case 2:
  9407. return new BABYLON.Vector3(0, -1, 0);
  9408. case 3:
  9409. return new BABYLON.Vector3(0, 1, 0);
  9410. case 4:
  9411. return new BABYLON.Vector3(0, 0, 1);
  9412. case 5:
  9413. return new BABYLON.Vector3(0, 0, -1);
  9414. }
  9415. return BABYLON.Vector3.Zero();
  9416. };
  9417. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9418. var activeCamera = this.getScene().activeCamera;
  9419. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9420. };
  9421. PointLight.prototype._getWorldMatrix = function () {
  9422. if (!this._worldMatrix) {
  9423. this._worldMatrix = BABYLON.Matrix.Identity();
  9424. }
  9425. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9426. return this._worldMatrix;
  9427. };
  9428. PointLight.prototype.getTypeID = function () {
  9429. return 0;
  9430. };
  9431. __decorate([
  9432. BABYLON.serializeAsVector3()
  9433. ], PointLight.prototype, "position", void 0);
  9434. return PointLight;
  9435. })(BABYLON.Light);
  9436. BABYLON.PointLight = PointLight;
  9437. })(BABYLON || (BABYLON = {}));
  9438. var BABYLON;
  9439. (function (BABYLON) {
  9440. var SpotLight = (function (_super) {
  9441. __extends(SpotLight, _super);
  9442. function SpotLight(name, position, direction, angle, exponent, scene) {
  9443. _super.call(this, name, scene);
  9444. this.position = position;
  9445. this.direction = direction;
  9446. this.angle = angle;
  9447. this.exponent = exponent;
  9448. }
  9449. SpotLight.prototype.getAbsolutePosition = function () {
  9450. return this.transformedPosition ? this.transformedPosition : this.position;
  9451. };
  9452. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9453. var activeCamera = this.getScene().activeCamera;
  9454. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9455. };
  9456. SpotLight.prototype.needCube = function () {
  9457. return false;
  9458. };
  9459. SpotLight.prototype.supportsVSM = function () {
  9460. return true;
  9461. };
  9462. SpotLight.prototype.needRefreshPerFrame = function () {
  9463. return false;
  9464. };
  9465. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9466. return this.direction;
  9467. };
  9468. SpotLight.prototype.setDirectionToTarget = function (target) {
  9469. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9470. return this.direction;
  9471. };
  9472. SpotLight.prototype.computeTransformedPosition = function () {
  9473. if (this.parent && this.parent.getWorldMatrix) {
  9474. if (!this.transformedPosition) {
  9475. this.transformedPosition = BABYLON.Vector3.Zero();
  9476. }
  9477. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9478. return true;
  9479. }
  9480. return false;
  9481. };
  9482. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9483. var normalizeDirection;
  9484. if (this.parent && this.parent.getWorldMatrix) {
  9485. if (!this._transformedDirection) {
  9486. this._transformedDirection = BABYLON.Vector3.Zero();
  9487. }
  9488. this.computeTransformedPosition();
  9489. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9490. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9491. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9492. }
  9493. else {
  9494. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9495. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9496. }
  9497. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9498. };
  9499. SpotLight.prototype._getWorldMatrix = function () {
  9500. if (!this._worldMatrix) {
  9501. this._worldMatrix = BABYLON.Matrix.Identity();
  9502. }
  9503. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9504. return this._worldMatrix;
  9505. };
  9506. SpotLight.prototype.getTypeID = function () {
  9507. return 2;
  9508. };
  9509. __decorate([
  9510. BABYLON.serializeAsVector3()
  9511. ], SpotLight.prototype, "position", void 0);
  9512. __decorate([
  9513. BABYLON.serializeAsVector3()
  9514. ], SpotLight.prototype, "direction", void 0);
  9515. __decorate([
  9516. BABYLON.serialize()
  9517. ], SpotLight.prototype, "angle", void 0);
  9518. __decorate([
  9519. BABYLON.serialize()
  9520. ], SpotLight.prototype, "exponent", void 0);
  9521. return SpotLight;
  9522. })(BABYLON.Light);
  9523. BABYLON.SpotLight = SpotLight;
  9524. })(BABYLON || (BABYLON = {}));
  9525. var BABYLON;
  9526. (function (BABYLON) {
  9527. var HemisphericLight = (function (_super) {
  9528. __extends(HemisphericLight, _super);
  9529. function HemisphericLight(name, direction, scene) {
  9530. _super.call(this, name, scene);
  9531. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9532. this.direction = direction;
  9533. }
  9534. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9535. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9536. return this.direction;
  9537. };
  9538. HemisphericLight.prototype.getShadowGenerator = function () {
  9539. return null;
  9540. };
  9541. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9542. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9543. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9544. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9545. };
  9546. HemisphericLight.prototype._getWorldMatrix = function () {
  9547. if (!this._worldMatrix) {
  9548. this._worldMatrix = BABYLON.Matrix.Identity();
  9549. }
  9550. return this._worldMatrix;
  9551. };
  9552. HemisphericLight.prototype.getTypeID = function () {
  9553. return 3;
  9554. };
  9555. __decorate([
  9556. BABYLON.serializeAsColor3()
  9557. ], HemisphericLight.prototype, "groundColor", void 0);
  9558. __decorate([
  9559. BABYLON.serializeAsVector3()
  9560. ], HemisphericLight.prototype, "direction", void 0);
  9561. return HemisphericLight;
  9562. })(BABYLON.Light);
  9563. BABYLON.HemisphericLight = HemisphericLight;
  9564. })(BABYLON || (BABYLON = {}));
  9565. var BABYLON;
  9566. (function (BABYLON) {
  9567. var DirectionalLight = (function (_super) {
  9568. __extends(DirectionalLight, _super);
  9569. function DirectionalLight(name, direction, scene) {
  9570. _super.call(this, name, scene);
  9571. this.shadowOrthoScale = 0.5;
  9572. this.autoUpdateExtends = true;
  9573. // Cache
  9574. this._orthoLeft = Number.MAX_VALUE;
  9575. this._orthoRight = Number.MIN_VALUE;
  9576. this._orthoTop = Number.MIN_VALUE;
  9577. this._orthoBottom = Number.MAX_VALUE;
  9578. this.position = direction.scale(-1);
  9579. this.direction = direction;
  9580. }
  9581. DirectionalLight.prototype.getAbsolutePosition = function () {
  9582. return this.transformedPosition ? this.transformedPosition : this.position;
  9583. };
  9584. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9585. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9586. return this.direction;
  9587. };
  9588. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9589. var activeCamera = this.getScene().activeCamera;
  9590. // Check extends
  9591. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9592. var tempVector3 = BABYLON.Vector3.Zero();
  9593. this._orthoLeft = Number.MAX_VALUE;
  9594. this._orthoRight = Number.MIN_VALUE;
  9595. this._orthoTop = Number.MIN_VALUE;
  9596. this._orthoBottom = Number.MAX_VALUE;
  9597. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9598. var mesh = renderList[meshIndex];
  9599. if (!mesh) {
  9600. continue;
  9601. }
  9602. var boundingInfo = mesh.getBoundingInfo();
  9603. if (!boundingInfo) {
  9604. continue;
  9605. }
  9606. var boundingBox = boundingInfo.boundingBox;
  9607. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9608. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9609. if (tempVector3.x < this._orthoLeft)
  9610. this._orthoLeft = tempVector3.x;
  9611. if (tempVector3.y < this._orthoBottom)
  9612. this._orthoBottom = tempVector3.y;
  9613. if (tempVector3.x > this._orthoRight)
  9614. this._orthoRight = tempVector3.x;
  9615. if (tempVector3.y > this._orthoTop)
  9616. this._orthoTop = tempVector3.y;
  9617. }
  9618. }
  9619. }
  9620. var xOffset = this._orthoRight - this._orthoLeft;
  9621. var yOffset = this._orthoTop - this._orthoBottom;
  9622. 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);
  9623. };
  9624. DirectionalLight.prototype.supportsVSM = function () {
  9625. return true;
  9626. };
  9627. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9628. return true;
  9629. };
  9630. DirectionalLight.prototype.needCube = function () {
  9631. return false;
  9632. };
  9633. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9634. return this.direction;
  9635. };
  9636. DirectionalLight.prototype.computeTransformedPosition = function () {
  9637. if (this.parent && this.parent.getWorldMatrix) {
  9638. if (!this.transformedPosition) {
  9639. this.transformedPosition = BABYLON.Vector3.Zero();
  9640. }
  9641. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9642. return true;
  9643. }
  9644. return false;
  9645. };
  9646. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9647. if (this.parent && this.parent.getWorldMatrix) {
  9648. if (!this._transformedDirection) {
  9649. this._transformedDirection = BABYLON.Vector3.Zero();
  9650. }
  9651. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9652. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9653. return;
  9654. }
  9655. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9656. };
  9657. DirectionalLight.prototype._getWorldMatrix = function () {
  9658. if (!this._worldMatrix) {
  9659. this._worldMatrix = BABYLON.Matrix.Identity();
  9660. }
  9661. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9662. return this._worldMatrix;
  9663. };
  9664. DirectionalLight.prototype.getTypeID = function () {
  9665. return 1;
  9666. };
  9667. __decorate([
  9668. BABYLON.serializeAsVector3()
  9669. ], DirectionalLight.prototype, "position", void 0);
  9670. __decorate([
  9671. BABYLON.serializeAsVector3()
  9672. ], DirectionalLight.prototype, "direction", void 0);
  9673. __decorate([
  9674. BABYLON.serialize()
  9675. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9676. __decorate([
  9677. BABYLON.serialize()
  9678. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9679. return DirectionalLight;
  9680. })(BABYLON.Light);
  9681. BABYLON.DirectionalLight = DirectionalLight;
  9682. })(BABYLON || (BABYLON = {}));
  9683. var BABYLON;
  9684. (function (BABYLON) {
  9685. var ShadowGenerator = (function () {
  9686. function ShadowGenerator(mapSize, light) {
  9687. var _this = this;
  9688. // Members
  9689. this._filter = ShadowGenerator.FILTER_NONE;
  9690. this.blurScale = 2;
  9691. this._blurBoxOffset = 0;
  9692. this._bias = 0.00005;
  9693. this._lightDirection = BABYLON.Vector3.Zero();
  9694. this.forceBackFacesOnly = false;
  9695. this._darkness = 0;
  9696. this._transparencyShadow = false;
  9697. this._viewMatrix = BABYLON.Matrix.Zero();
  9698. this._projectionMatrix = BABYLON.Matrix.Zero();
  9699. this._transformMatrix = BABYLON.Matrix.Zero();
  9700. this._worldViewProjection = BABYLON.Matrix.Zero();
  9701. this._currentFaceIndex = 0;
  9702. this._currentFaceIndexCache = 0;
  9703. this._light = light;
  9704. this._scene = light.getScene();
  9705. this._mapSize = mapSize;
  9706. light._shadowGenerator = this;
  9707. // Render target
  9708. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9709. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9710. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9711. this._shadowMap.anisotropicFilteringLevel = 1;
  9712. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9713. this._shadowMap.renderParticles = false;
  9714. this._shadowMap.onBeforeRender = function (faceIndex) {
  9715. _this._currentFaceIndex = faceIndex;
  9716. };
  9717. this._shadowMap.onAfterUnbind = function () {
  9718. if (!_this.useBlurVarianceShadowMap) {
  9719. return;
  9720. }
  9721. if (!_this._shadowMap2) {
  9722. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9723. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9724. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9725. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9726. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9727. _this._downSamplePostprocess.onApply = function (effect) {
  9728. effect.setTexture("textureSampler", _this._shadowMap);
  9729. };
  9730. _this.blurBoxOffset = 1;
  9731. }
  9732. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9733. };
  9734. // Custom render function
  9735. var renderSubMesh = function (subMesh) {
  9736. var mesh = subMesh.getRenderingMesh();
  9737. var scene = _this._scene;
  9738. var engine = scene.getEngine();
  9739. // Culling
  9740. engine.setState(subMesh.getMaterial().backFaceCulling);
  9741. // Managing instances
  9742. var batch = mesh._getInstancesRenderList(subMesh._id);
  9743. if (batch.mustReturn) {
  9744. return;
  9745. }
  9746. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9747. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9748. engine.enableEffect(_this._effect);
  9749. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9750. var material = subMesh.getMaterial();
  9751. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9752. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9753. if (_this.getLight().needCube()) {
  9754. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9755. }
  9756. // Alpha test
  9757. if (material && material.needAlphaTesting()) {
  9758. var alphaTexture = material.getAlphaTestTexture();
  9759. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9760. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9761. }
  9762. // Bones
  9763. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9764. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9765. }
  9766. if (_this.forceBackFacesOnly) {
  9767. engine.setState(true, 0, false, true);
  9768. }
  9769. // Draw
  9770. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9771. if (_this.forceBackFacesOnly) {
  9772. engine.setState(true, 0, false, false);
  9773. }
  9774. }
  9775. else {
  9776. // Need to reset refresh rate of the shadowMap
  9777. _this._shadowMap.resetRefreshCounter();
  9778. }
  9779. };
  9780. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9781. var index;
  9782. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9783. renderSubMesh(opaqueSubMeshes.data[index]);
  9784. }
  9785. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9786. renderSubMesh(alphaTestSubMeshes.data[index]);
  9787. }
  9788. if (_this._transparencyShadow) {
  9789. for (index = 0; index < transparentSubMeshes.length; index++) {
  9790. renderSubMesh(transparentSubMeshes.data[index]);
  9791. }
  9792. }
  9793. };
  9794. this._shadowMap.onClear = function (engine) {
  9795. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9796. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9797. }
  9798. else {
  9799. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9800. }
  9801. };
  9802. }
  9803. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9804. // Static
  9805. get: function () {
  9806. return ShadowGenerator._FILTER_NONE;
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9812. get: function () {
  9813. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9819. get: function () {
  9820. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9826. get: function () {
  9827. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9833. get: function () {
  9834. return this._bias;
  9835. },
  9836. set: function (bias) {
  9837. this._bias = bias;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9843. get: function () {
  9844. return this._blurBoxOffset;
  9845. },
  9846. set: function (value) {
  9847. var _this = this;
  9848. if (this._blurBoxOffset === value) {
  9849. return;
  9850. }
  9851. this._blurBoxOffset = value;
  9852. if (this._boxBlurPostprocess) {
  9853. this._boxBlurPostprocess.dispose();
  9854. }
  9855. 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);
  9856. this._boxBlurPostprocess.onApply = function (effect) {
  9857. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9858. };
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9864. get: function () {
  9865. return this._filter;
  9866. },
  9867. set: function (value) {
  9868. if (this._filter === value) {
  9869. return;
  9870. }
  9871. this._filter = value;
  9872. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9873. this._shadowMap.anisotropicFilteringLevel = 16;
  9874. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9875. }
  9876. else {
  9877. this._shadowMap.anisotropicFilteringLevel = 1;
  9878. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9879. }
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9885. get: function () {
  9886. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9887. },
  9888. set: function (value) {
  9889. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9895. get: function () {
  9896. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9897. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9898. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9899. },
  9900. set: function (value) {
  9901. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9907. get: function () {
  9908. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9909. },
  9910. set: function (value) {
  9911. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9917. var defines = [];
  9918. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9919. defines.push("#define VSM");
  9920. }
  9921. if (this.getLight().needCube()) {
  9922. defines.push("#define CUBEMAP");
  9923. }
  9924. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9925. var mesh = subMesh.getMesh();
  9926. var material = subMesh.getMaterial();
  9927. // Alpha test
  9928. if (material && material.needAlphaTesting()) {
  9929. defines.push("#define ALPHATEST");
  9930. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9931. attribs.push(BABYLON.VertexBuffer.UVKind);
  9932. defines.push("#define UV1");
  9933. }
  9934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9935. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9936. defines.push("#define UV2");
  9937. }
  9938. }
  9939. // Bones
  9940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9943. if (mesh.numBoneInfluencers > 4) {
  9944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9946. }
  9947. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9948. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9949. }
  9950. else {
  9951. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9952. }
  9953. // Instances
  9954. if (useInstances) {
  9955. defines.push("#define INSTANCES");
  9956. attribs.push("world0");
  9957. attribs.push("world1");
  9958. attribs.push("world2");
  9959. attribs.push("world3");
  9960. }
  9961. // Get correct effect
  9962. var join = defines.join("\n");
  9963. if (this._cachedDefines !== join) {
  9964. this._cachedDefines = join;
  9965. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9966. }
  9967. return this._effect.isReady();
  9968. };
  9969. ShadowGenerator.prototype.getShadowMap = function () {
  9970. return this._shadowMap;
  9971. };
  9972. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9973. if (this._shadowMap2) {
  9974. return this._shadowMap2;
  9975. }
  9976. return this._shadowMap;
  9977. };
  9978. ShadowGenerator.prototype.getLight = function () {
  9979. return this._light;
  9980. };
  9981. // Methods
  9982. ShadowGenerator.prototype.getTransformMatrix = function () {
  9983. var scene = this._scene;
  9984. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9985. return this._transformMatrix;
  9986. }
  9987. this._currentRenderID = scene.getRenderId();
  9988. this._currentFaceIndexCache = this._currentFaceIndex;
  9989. var lightPosition = this._light.position;
  9990. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9991. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9992. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9993. }
  9994. if (this._light.computeTransformedPosition()) {
  9995. lightPosition = this._light.transformedPosition;
  9996. }
  9997. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9998. this._cachedPosition = lightPosition.clone();
  9999. this._cachedDirection = this._lightDirection.clone();
  10000. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10001. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10002. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10003. }
  10004. return this._transformMatrix;
  10005. };
  10006. ShadowGenerator.prototype.getDarkness = function () {
  10007. return this._darkness;
  10008. };
  10009. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10010. if (darkness >= 1.0)
  10011. this._darkness = 1.0;
  10012. else if (darkness <= 0.0)
  10013. this._darkness = 0.0;
  10014. else
  10015. this._darkness = darkness;
  10016. };
  10017. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10018. this._transparencyShadow = hasShadow;
  10019. };
  10020. ShadowGenerator.prototype._packHalf = function (depth) {
  10021. var scale = depth * 255.0;
  10022. var fract = scale - Math.floor(scale);
  10023. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10024. };
  10025. ShadowGenerator.prototype.dispose = function () {
  10026. this._shadowMap.dispose();
  10027. if (this._shadowMap2) {
  10028. this._shadowMap2.dispose();
  10029. }
  10030. if (this._downSamplePostprocess) {
  10031. this._downSamplePostprocess.dispose();
  10032. }
  10033. if (this._boxBlurPostprocess) {
  10034. this._boxBlurPostprocess.dispose();
  10035. }
  10036. };
  10037. ShadowGenerator.prototype.serialize = function () {
  10038. var serializationObject = {};
  10039. serializationObject.lightId = this._light.id;
  10040. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10041. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10042. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10043. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10044. serializationObject.renderList = [];
  10045. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10046. var mesh = this.getShadowMap().renderList[meshIndex];
  10047. serializationObject.renderList.push(mesh.id);
  10048. }
  10049. return serializationObject;
  10050. };
  10051. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10052. //casting to point light, as light is missing the position attr and typescript complains.
  10053. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10054. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10055. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10056. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10057. shadowGenerator.getShadowMap().renderList.push(mesh);
  10058. }
  10059. if (parsedShadowGenerator.usePoissonSampling) {
  10060. shadowGenerator.usePoissonSampling = true;
  10061. }
  10062. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10063. shadowGenerator.useVarianceShadowMap = true;
  10064. }
  10065. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10066. shadowGenerator.useBlurVarianceShadowMap = true;
  10067. if (parsedShadowGenerator.blurScale) {
  10068. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10069. }
  10070. if (parsedShadowGenerator.blurBoxOffset) {
  10071. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10072. }
  10073. }
  10074. if (parsedShadowGenerator.bias !== undefined) {
  10075. shadowGenerator.bias = parsedShadowGenerator.bias;
  10076. }
  10077. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10078. return shadowGenerator;
  10079. };
  10080. ShadowGenerator._FILTER_NONE = 0;
  10081. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10082. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10083. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10084. return ShadowGenerator;
  10085. })();
  10086. BABYLON.ShadowGenerator = ShadowGenerator;
  10087. })(BABYLON || (BABYLON = {}));
  10088. var BABYLON;
  10089. (function (BABYLON) {
  10090. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10091. if (boxMin.x > sphereCenter.x + sphereRadius)
  10092. return false;
  10093. if (sphereCenter.x - sphereRadius > boxMax.x)
  10094. return false;
  10095. if (boxMin.y > sphereCenter.y + sphereRadius)
  10096. return false;
  10097. if (sphereCenter.y - sphereRadius > boxMax.y)
  10098. return false;
  10099. if (boxMin.z > sphereCenter.z + sphereRadius)
  10100. return false;
  10101. if (sphereCenter.z - sphereRadius > boxMax.z)
  10102. return false;
  10103. return true;
  10104. };
  10105. var getLowestRoot = function (a, b, c, maxR) {
  10106. var determinant = b * b - 4.0 * a * c;
  10107. var result = { root: 0, found: false };
  10108. if (determinant < 0)
  10109. return result;
  10110. var sqrtD = Math.sqrt(determinant);
  10111. var r1 = (-b - sqrtD) / (2.0 * a);
  10112. var r2 = (-b + sqrtD) / (2.0 * a);
  10113. if (r1 > r2) {
  10114. var temp = r2;
  10115. r2 = r1;
  10116. r1 = temp;
  10117. }
  10118. if (r1 > 0 && r1 < maxR) {
  10119. result.root = r1;
  10120. result.found = true;
  10121. return result;
  10122. }
  10123. if (r2 > 0 && r2 < maxR) {
  10124. result.root = r2;
  10125. result.found = true;
  10126. return result;
  10127. }
  10128. return result;
  10129. };
  10130. var Collider = (function () {
  10131. function Collider() {
  10132. this.radius = new BABYLON.Vector3(1, 1, 1);
  10133. this.retry = 0;
  10134. this.basePointWorld = BABYLON.Vector3.Zero();
  10135. this.velocityWorld = BABYLON.Vector3.Zero();
  10136. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10137. this._collisionPoint = BABYLON.Vector3.Zero();
  10138. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10139. this._tempVector = BABYLON.Vector3.Zero();
  10140. this._tempVector2 = BABYLON.Vector3.Zero();
  10141. this._tempVector3 = BABYLON.Vector3.Zero();
  10142. this._tempVector4 = BABYLON.Vector3.Zero();
  10143. this._edge = BABYLON.Vector3.Zero();
  10144. this._baseToVertex = BABYLON.Vector3.Zero();
  10145. this._destinationPoint = BABYLON.Vector3.Zero();
  10146. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10147. this._displacementVector = BABYLON.Vector3.Zero();
  10148. }
  10149. // Methods
  10150. Collider.prototype._initialize = function (source, dir, e) {
  10151. this.velocity = dir;
  10152. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10153. this.basePoint = source;
  10154. source.multiplyToRef(this.radius, this.basePointWorld);
  10155. dir.multiplyToRef(this.radius, this.velocityWorld);
  10156. this.velocityWorldLength = this.velocityWorld.length();
  10157. this.epsilon = e;
  10158. this.collisionFound = false;
  10159. };
  10160. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10161. pa.subtractToRef(point, this._tempVector);
  10162. pb.subtractToRef(point, this._tempVector2);
  10163. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10164. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10165. if (d < 0)
  10166. return false;
  10167. pc.subtractToRef(point, this._tempVector3);
  10168. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10169. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10170. if (d < 0)
  10171. return false;
  10172. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10173. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10174. return d >= 0;
  10175. };
  10176. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10177. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10178. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10179. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10180. return false;
  10181. }
  10182. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10183. return false;
  10184. return true;
  10185. };
  10186. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10187. var t0;
  10188. var embeddedInPlane = false;
  10189. //defensive programming, actually not needed.
  10190. if (!trianglePlaneArray) {
  10191. trianglePlaneArray = [];
  10192. }
  10193. if (!trianglePlaneArray[faceIndex]) {
  10194. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10195. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10196. }
  10197. var trianglePlane = trianglePlaneArray[faceIndex];
  10198. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10199. return;
  10200. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10201. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10202. if (normalDotVelocity == 0) {
  10203. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10204. return;
  10205. embeddedInPlane = true;
  10206. t0 = 0;
  10207. }
  10208. else {
  10209. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10210. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10211. if (t0 > t1) {
  10212. var temp = t1;
  10213. t1 = t0;
  10214. t0 = temp;
  10215. }
  10216. if (t0 > 1.0 || t1 < 0.0)
  10217. return;
  10218. if (t0 < 0)
  10219. t0 = 0;
  10220. if (t0 > 1.0)
  10221. t0 = 1.0;
  10222. }
  10223. this._collisionPoint.copyFromFloats(0, 0, 0);
  10224. var found = false;
  10225. var t = 1.0;
  10226. if (!embeddedInPlane) {
  10227. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10228. this.velocity.scaleToRef(t0, this._tempVector);
  10229. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10230. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10231. found = true;
  10232. t = t0;
  10233. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10234. }
  10235. }
  10236. if (!found) {
  10237. var velocitySquaredLength = this.velocity.lengthSquared();
  10238. var a = velocitySquaredLength;
  10239. this.basePoint.subtractToRef(p1, this._tempVector);
  10240. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10241. var c = this._tempVector.lengthSquared() - 1.0;
  10242. var lowestRoot = getLowestRoot(a, b, c, t);
  10243. if (lowestRoot.found) {
  10244. t = lowestRoot.root;
  10245. found = true;
  10246. this._collisionPoint.copyFrom(p1);
  10247. }
  10248. this.basePoint.subtractToRef(p2, this._tempVector);
  10249. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10250. c = this._tempVector.lengthSquared() - 1.0;
  10251. lowestRoot = getLowestRoot(a, b, c, t);
  10252. if (lowestRoot.found) {
  10253. t = lowestRoot.root;
  10254. found = true;
  10255. this._collisionPoint.copyFrom(p2);
  10256. }
  10257. this.basePoint.subtractToRef(p3, this._tempVector);
  10258. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10259. c = this._tempVector.lengthSquared() - 1.0;
  10260. lowestRoot = getLowestRoot(a, b, c, t);
  10261. if (lowestRoot.found) {
  10262. t = lowestRoot.root;
  10263. found = true;
  10264. this._collisionPoint.copyFrom(p3);
  10265. }
  10266. p2.subtractToRef(p1, this._edge);
  10267. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10268. var edgeSquaredLength = this._edge.lengthSquared();
  10269. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10270. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10271. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10272. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10273. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10274. lowestRoot = getLowestRoot(a, b, c, t);
  10275. if (lowestRoot.found) {
  10276. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10277. if (f >= 0.0 && f <= 1.0) {
  10278. t = lowestRoot.root;
  10279. found = true;
  10280. this._edge.scaleInPlace(f);
  10281. p1.addToRef(this._edge, this._collisionPoint);
  10282. }
  10283. }
  10284. p3.subtractToRef(p2, this._edge);
  10285. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10286. edgeSquaredLength = this._edge.lengthSquared();
  10287. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10288. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10289. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10290. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10291. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10292. lowestRoot = getLowestRoot(a, b, c, t);
  10293. if (lowestRoot.found) {
  10294. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10295. if (f >= 0.0 && f <= 1.0) {
  10296. t = lowestRoot.root;
  10297. found = true;
  10298. this._edge.scaleInPlace(f);
  10299. p2.addToRef(this._edge, this._collisionPoint);
  10300. }
  10301. }
  10302. p1.subtractToRef(p3, this._edge);
  10303. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10304. edgeSquaredLength = this._edge.lengthSquared();
  10305. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10306. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10307. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10308. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10309. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10310. lowestRoot = getLowestRoot(a, b, c, t);
  10311. if (lowestRoot.found) {
  10312. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10313. if (f >= 0.0 && f <= 1.0) {
  10314. t = lowestRoot.root;
  10315. found = true;
  10316. this._edge.scaleInPlace(f);
  10317. p3.addToRef(this._edge, this._collisionPoint);
  10318. }
  10319. }
  10320. }
  10321. if (found) {
  10322. var distToCollision = t * this.velocity.length();
  10323. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10324. if (!this.intersectionPoint) {
  10325. this.intersectionPoint = this._collisionPoint.clone();
  10326. }
  10327. else {
  10328. this.intersectionPoint.copyFrom(this._collisionPoint);
  10329. }
  10330. this.nearestDistance = distToCollision;
  10331. this.collisionFound = true;
  10332. }
  10333. }
  10334. };
  10335. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10336. for (var i = indexStart; i < indexEnd; i += 3) {
  10337. var p1 = pts[indices[i] - decal];
  10338. var p2 = pts[indices[i + 1] - decal];
  10339. var p3 = pts[indices[i + 2] - decal];
  10340. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10341. }
  10342. };
  10343. Collider.prototype._getResponse = function (pos, vel) {
  10344. pos.addToRef(vel, this._destinationPoint);
  10345. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10346. this.basePoint.addToRef(vel, pos);
  10347. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10348. this._slidePlaneNormal.normalize();
  10349. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10350. pos.addInPlace(this._displacementVector);
  10351. this.intersectionPoint.addInPlace(this._displacementVector);
  10352. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10353. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10354. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10355. };
  10356. return Collider;
  10357. })();
  10358. BABYLON.Collider = Collider;
  10359. })(BABYLON || (BABYLON = {}));
  10360. var BABYLON;
  10361. (function (BABYLON) {
  10362. //WebWorker code will be inserted to this variable.
  10363. BABYLON.CollisionWorker = "";
  10364. (function (WorkerTaskType) {
  10365. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10366. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10367. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10368. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10369. var WorkerTaskType = BABYLON.WorkerTaskType;
  10370. (function (WorkerReplyType) {
  10371. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10372. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10373. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10374. var WorkerReplyType = BABYLON.WorkerReplyType;
  10375. var CollisionCoordinatorWorker = (function () {
  10376. function CollisionCoordinatorWorker() {
  10377. var _this = this;
  10378. this._scaledPosition = BABYLON.Vector3.Zero();
  10379. this._scaledVelocity = BABYLON.Vector3.Zero();
  10380. this.onMeshUpdated = function (mesh) {
  10381. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10382. };
  10383. this.onGeometryUpdated = function (geometry) {
  10384. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10385. };
  10386. this._afterRender = function () {
  10387. if (!_this._init)
  10388. return;
  10389. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10390. return;
  10391. }
  10392. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10393. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10394. if (_this._runningUpdated > 4) {
  10395. return;
  10396. }
  10397. ++_this._runningUpdated;
  10398. var payload = {
  10399. updatedMeshes: _this._addUpdateMeshesList,
  10400. updatedGeometries: _this._addUpdateGeometriesList,
  10401. removedGeometries: _this._toRemoveGeometryArray,
  10402. removedMeshes: _this._toRemoveMeshesArray
  10403. };
  10404. var message = {
  10405. payload: payload,
  10406. taskType: WorkerTaskType.UPDATE
  10407. };
  10408. var serializable = [];
  10409. for (var id in payload.updatedGeometries) {
  10410. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10411. //prepare transferables
  10412. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10413. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10414. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10415. }
  10416. }
  10417. _this._worker.postMessage(message, serializable);
  10418. _this._addUpdateMeshesList = {};
  10419. _this._addUpdateGeometriesList = {};
  10420. _this._toRemoveGeometryArray = [];
  10421. _this._toRemoveMeshesArray = [];
  10422. };
  10423. this._onMessageFromWorker = function (e) {
  10424. var returnData = e.data;
  10425. if (returnData.error != WorkerReplyType.SUCCESS) {
  10426. //TODO what errors can be returned from the worker?
  10427. BABYLON.Tools.Warn("error returned from worker!");
  10428. return;
  10429. }
  10430. switch (returnData.taskType) {
  10431. case WorkerTaskType.INIT:
  10432. _this._init = true;
  10433. //Update the worked with ALL of the scene's current state
  10434. _this._scene.meshes.forEach(function (mesh) {
  10435. _this.onMeshAdded(mesh);
  10436. });
  10437. _this._scene.getGeometries().forEach(function (geometry) {
  10438. _this.onGeometryAdded(geometry);
  10439. });
  10440. break;
  10441. case WorkerTaskType.UPDATE:
  10442. _this._runningUpdated--;
  10443. break;
  10444. case WorkerTaskType.COLLIDE:
  10445. _this._runningCollisionTask = false;
  10446. var returnPayload = returnData.payload;
  10447. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10448. return;
  10449. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10450. //cleanup
  10451. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10452. break;
  10453. }
  10454. };
  10455. this._collisionsCallbackArray = [];
  10456. this._init = false;
  10457. this._runningUpdated = 0;
  10458. this._runningCollisionTask = false;
  10459. this._addUpdateMeshesList = {};
  10460. this._addUpdateGeometriesList = {};
  10461. this._toRemoveGeometryArray = [];
  10462. this._toRemoveMeshesArray = [];
  10463. }
  10464. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10465. if (!this._init)
  10466. return;
  10467. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10468. return;
  10469. position.divideToRef(collider.radius, this._scaledPosition);
  10470. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10471. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10472. var payload = {
  10473. collider: {
  10474. position: this._scaledPosition.asArray(),
  10475. velocity: this._scaledVelocity.asArray(),
  10476. radius: collider.radius.asArray()
  10477. },
  10478. collisionId: collisionIndex,
  10479. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10480. maximumRetry: maximumRetry
  10481. };
  10482. var message = {
  10483. payload: payload,
  10484. taskType: WorkerTaskType.COLLIDE
  10485. };
  10486. this._worker.postMessage(message);
  10487. };
  10488. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10489. this._scene = scene;
  10490. this._scene.registerAfterRender(this._afterRender);
  10491. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10492. this._worker = new Worker(workerUrl);
  10493. this._worker.onmessage = this._onMessageFromWorker;
  10494. var message = {
  10495. payload: {},
  10496. taskType: WorkerTaskType.INIT
  10497. };
  10498. this._worker.postMessage(message);
  10499. };
  10500. CollisionCoordinatorWorker.prototype.destroy = function () {
  10501. this._scene.unregisterAfterRender(this._afterRender);
  10502. this._worker.terminate();
  10503. };
  10504. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10505. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10506. this.onMeshUpdated(mesh);
  10507. };
  10508. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10509. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10510. };
  10511. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10512. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10513. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10514. this.onGeometryUpdated(geometry);
  10515. };
  10516. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10517. this._toRemoveGeometryArray.push(geometry.id);
  10518. };
  10519. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10520. var submeshes = [];
  10521. if (mesh.subMeshes) {
  10522. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10523. return {
  10524. position: idx,
  10525. verticesStart: sm.verticesStart,
  10526. verticesCount: sm.verticesCount,
  10527. indexStart: sm.indexStart,
  10528. indexCount: sm.indexCount,
  10529. hasMaterial: !!sm.getMaterial(),
  10530. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10531. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10532. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10533. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10534. };
  10535. });
  10536. }
  10537. var geometryId = null;
  10538. if (mesh instanceof BABYLON.Mesh) {
  10539. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10540. }
  10541. else if (mesh instanceof BABYLON.InstancedMesh) {
  10542. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10543. }
  10544. return {
  10545. uniqueId: mesh.uniqueId,
  10546. id: mesh.id,
  10547. name: mesh.name,
  10548. geometryId: geometryId,
  10549. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10550. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10551. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10552. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10553. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10554. subMeshes: submeshes,
  10555. checkCollisions: mesh.checkCollisions
  10556. };
  10557. };
  10558. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10559. return {
  10560. id: geometry.id,
  10561. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10562. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10563. indices: new Int32Array(geometry.getIndices() || []),
  10564. };
  10565. };
  10566. return CollisionCoordinatorWorker;
  10567. })();
  10568. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10569. var CollisionCoordinatorLegacy = (function () {
  10570. function CollisionCoordinatorLegacy() {
  10571. this._scaledPosition = BABYLON.Vector3.Zero();
  10572. this._scaledVelocity = BABYLON.Vector3.Zero();
  10573. this._finalPosition = BABYLON.Vector3.Zero();
  10574. }
  10575. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10576. position.divideToRef(collider.radius, this._scaledPosition);
  10577. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10578. collider.collidedMesh = null;
  10579. collider.retry = 0;
  10580. collider.initialVelocity = this._scaledVelocity;
  10581. collider.initialPosition = this._scaledPosition;
  10582. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10583. this._finalPosition.multiplyInPlace(collider.radius);
  10584. //run the callback
  10585. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10586. };
  10587. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10588. this._scene = scene;
  10589. };
  10590. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10591. //Legacy need no destruction method.
  10592. };
  10593. //No update in legacy mode
  10594. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10595. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10596. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10597. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10598. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10599. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10600. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10601. if (excludedMesh === void 0) { excludedMesh = null; }
  10602. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10603. if (collider.retry >= maximumRetry) {
  10604. finalPosition.copyFrom(position);
  10605. return;
  10606. }
  10607. collider._initialize(position, velocity, closeDistance);
  10608. // Check all meshes
  10609. for (var index = 0; index < this._scene.meshes.length; index++) {
  10610. var mesh = this._scene.meshes[index];
  10611. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10612. mesh._checkCollision(collider);
  10613. }
  10614. }
  10615. if (!collider.collisionFound) {
  10616. position.addToRef(velocity, finalPosition);
  10617. return;
  10618. }
  10619. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10620. collider._getResponse(position, velocity);
  10621. }
  10622. if (velocity.length() <= closeDistance) {
  10623. finalPosition.copyFrom(position);
  10624. return;
  10625. }
  10626. collider.retry++;
  10627. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10628. };
  10629. return CollisionCoordinatorLegacy;
  10630. })();
  10631. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10632. })(BABYLON || (BABYLON = {}));
  10633. var BABYLON;
  10634. (function (BABYLON) {
  10635. var Camera = (function (_super) {
  10636. __extends(Camera, _super);
  10637. function Camera(name, position, scene) {
  10638. _super.call(this, name, scene);
  10639. this.upVector = BABYLON.Vector3.Up();
  10640. this.orthoLeft = null;
  10641. this.orthoRight = null;
  10642. this.orthoBottom = null;
  10643. this.orthoTop = null;
  10644. this.fov = 0.8;
  10645. this.minZ = 1.0;
  10646. this.maxZ = 10000.0;
  10647. this.inertia = 0.9;
  10648. this.mode = Camera.PERSPECTIVE_CAMERA;
  10649. this.isIntermediate = false;
  10650. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10651. this.layerMask = 0x0FFFFFFF;
  10652. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10653. // Camera rig members
  10654. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10655. this._rigCameras = new Array();
  10656. // Cache
  10657. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10658. this._projectionMatrix = new BABYLON.Matrix();
  10659. this._postProcesses = new Array();
  10660. this._postProcessesTakenIndices = [];
  10661. this._activeMeshes = new BABYLON.SmartArray(256);
  10662. this._globalPosition = BABYLON.Vector3.Zero();
  10663. scene.addCamera(this);
  10664. if (!scene.activeCamera) {
  10665. scene.activeCamera = this;
  10666. }
  10667. this.position = position;
  10668. }
  10669. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10670. get: function () {
  10671. return Camera._PERSPECTIVE_CAMERA;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10677. get: function () {
  10678. return Camera._ORTHOGRAPHIC_CAMERA;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10684. get: function () {
  10685. return Camera._FOVMODE_VERTICAL_FIXED;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10691. get: function () {
  10692. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10698. get: function () {
  10699. return Camera._RIG_MODE_NONE;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10705. get: function () {
  10706. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10712. get: function () {
  10713. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10719. get: function () {
  10720. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10726. get: function () {
  10727. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10733. get: function () {
  10734. return Camera._RIG_MODE_VR;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. /**
  10740. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10741. */
  10742. Camera.prototype.toString = function (fullDetails) {
  10743. var ret = "Name: " + this.name;
  10744. ret += ", type: " + this.getTypeName();
  10745. if (this.animations) {
  10746. for (var i = 0; i < this.animations.length; i++) {
  10747. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10748. }
  10749. }
  10750. if (fullDetails) {
  10751. }
  10752. return ret;
  10753. };
  10754. Object.defineProperty(Camera.prototype, "globalPosition", {
  10755. get: function () {
  10756. return this._globalPosition;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Camera.prototype.getActiveMeshes = function () {
  10762. return this._activeMeshes;
  10763. };
  10764. Camera.prototype.isActiveMesh = function (mesh) {
  10765. return (this._activeMeshes.indexOf(mesh) !== -1);
  10766. };
  10767. //Cache
  10768. Camera.prototype._initCache = function () {
  10769. _super.prototype._initCache.call(this);
  10770. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10771. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10772. this._cache.mode = undefined;
  10773. this._cache.minZ = undefined;
  10774. this._cache.maxZ = undefined;
  10775. this._cache.fov = undefined;
  10776. this._cache.aspectRatio = undefined;
  10777. this._cache.orthoLeft = undefined;
  10778. this._cache.orthoRight = undefined;
  10779. this._cache.orthoBottom = undefined;
  10780. this._cache.orthoTop = undefined;
  10781. this._cache.renderWidth = undefined;
  10782. this._cache.renderHeight = undefined;
  10783. };
  10784. Camera.prototype._updateCache = function (ignoreParentClass) {
  10785. if (!ignoreParentClass) {
  10786. _super.prototype._updateCache.call(this);
  10787. }
  10788. var engine = this.getEngine();
  10789. this._cache.position.copyFrom(this.position);
  10790. this._cache.upVector.copyFrom(this.upVector);
  10791. this._cache.mode = this.mode;
  10792. this._cache.minZ = this.minZ;
  10793. this._cache.maxZ = this.maxZ;
  10794. this._cache.fov = this.fov;
  10795. this._cache.aspectRatio = engine.getAspectRatio(this);
  10796. this._cache.orthoLeft = this.orthoLeft;
  10797. this._cache.orthoRight = this.orthoRight;
  10798. this._cache.orthoBottom = this.orthoBottom;
  10799. this._cache.orthoTop = this.orthoTop;
  10800. this._cache.renderWidth = engine.getRenderWidth();
  10801. this._cache.renderHeight = engine.getRenderHeight();
  10802. };
  10803. Camera.prototype._updateFromScene = function () {
  10804. this.updateCache();
  10805. this._update();
  10806. };
  10807. // Synchronized
  10808. Camera.prototype._isSynchronized = function () {
  10809. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10810. };
  10811. Camera.prototype._isSynchronizedViewMatrix = function () {
  10812. if (!_super.prototype._isSynchronized.call(this))
  10813. return false;
  10814. return this._cache.position.equals(this.position)
  10815. && this._cache.upVector.equals(this.upVector)
  10816. && this.isSynchronizedWithParent();
  10817. };
  10818. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10819. var check = this._cache.mode === this.mode
  10820. && this._cache.minZ === this.minZ
  10821. && this._cache.maxZ === this.maxZ;
  10822. if (!check) {
  10823. return false;
  10824. }
  10825. var engine = this.getEngine();
  10826. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10827. check = this._cache.fov === this.fov
  10828. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10829. }
  10830. else {
  10831. check = this._cache.orthoLeft === this.orthoLeft
  10832. && this._cache.orthoRight === this.orthoRight
  10833. && this._cache.orthoBottom === this.orthoBottom
  10834. && this._cache.orthoTop === this.orthoTop
  10835. && this._cache.renderWidth === engine.getRenderWidth()
  10836. && this._cache.renderHeight === engine.getRenderHeight();
  10837. }
  10838. return check;
  10839. };
  10840. // Controls
  10841. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10842. };
  10843. Camera.prototype.detachControl = function (element) {
  10844. };
  10845. Camera.prototype._update = function () {
  10846. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10847. this._updateRigCameras();
  10848. }
  10849. this._checkInputs();
  10850. };
  10851. Camera.prototype._checkInputs = function () {
  10852. };
  10853. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10854. if (insertAt === void 0) { insertAt = null; }
  10855. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10856. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10857. return 0;
  10858. }
  10859. if (insertAt == null || insertAt < 0) {
  10860. this._postProcesses.push(postProcess);
  10861. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10862. return this._postProcesses.length - 1;
  10863. }
  10864. var add = 0;
  10865. var i;
  10866. var start;
  10867. if (this._postProcesses[insertAt]) {
  10868. start = this._postProcesses.length - 1;
  10869. for (i = start; i >= insertAt + 1; --i) {
  10870. this._postProcesses[i + 1] = this._postProcesses[i];
  10871. }
  10872. add = 1;
  10873. }
  10874. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10875. if (this._postProcessesTakenIndices[i] < insertAt) {
  10876. continue;
  10877. }
  10878. start = this._postProcessesTakenIndices.length - 1;
  10879. for (var j = start; j >= i; --j) {
  10880. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10881. }
  10882. this._postProcessesTakenIndices[i] = insertAt;
  10883. break;
  10884. }
  10885. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10886. this._postProcessesTakenIndices.push(insertAt);
  10887. }
  10888. var result = insertAt + add;
  10889. this._postProcesses[result] = postProcess;
  10890. return result;
  10891. };
  10892. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10893. if (atIndices === void 0) { atIndices = null; }
  10894. var result = [];
  10895. var i;
  10896. var index;
  10897. if (!atIndices) {
  10898. var length = this._postProcesses.length;
  10899. for (i = 0; i < length; i++) {
  10900. if (this._postProcesses[i] !== postProcess) {
  10901. continue;
  10902. }
  10903. delete this._postProcesses[i];
  10904. index = this._postProcessesTakenIndices.indexOf(i);
  10905. this._postProcessesTakenIndices.splice(index, 1);
  10906. }
  10907. }
  10908. else {
  10909. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10910. for (i = 0; i < atIndices.length; i++) {
  10911. var foundPostProcess = this._postProcesses[atIndices[i]];
  10912. if (foundPostProcess !== postProcess) {
  10913. result.push(i);
  10914. continue;
  10915. }
  10916. delete this._postProcesses[atIndices[i]];
  10917. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10918. this._postProcessesTakenIndices.splice(index, 1);
  10919. }
  10920. }
  10921. return result;
  10922. };
  10923. Camera.prototype.getWorldMatrix = function () {
  10924. if (!this._worldMatrix) {
  10925. this._worldMatrix = BABYLON.Matrix.Identity();
  10926. }
  10927. var viewMatrix = this.getViewMatrix();
  10928. viewMatrix.invertToRef(this._worldMatrix);
  10929. return this._worldMatrix;
  10930. };
  10931. Camera.prototype._getViewMatrix = function () {
  10932. return BABYLON.Matrix.Identity();
  10933. };
  10934. Camera.prototype.getViewMatrix = function (force) {
  10935. this._computedViewMatrix = this._computeViewMatrix(force);
  10936. if (!force && this._isSynchronizedViewMatrix()) {
  10937. return this._computedViewMatrix;
  10938. }
  10939. if (!this.parent || !this.parent.getWorldMatrix) {
  10940. this._globalPosition.copyFrom(this.position);
  10941. }
  10942. else {
  10943. if (!this._worldMatrix) {
  10944. this._worldMatrix = BABYLON.Matrix.Identity();
  10945. }
  10946. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10947. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10948. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10949. this._computedViewMatrix.invert();
  10950. this._markSyncedWithParent();
  10951. }
  10952. this._currentRenderId = this.getScene().getRenderId();
  10953. return this._computedViewMatrix;
  10954. };
  10955. Camera.prototype._computeViewMatrix = function (force) {
  10956. if (!force && this._isSynchronizedViewMatrix()) {
  10957. return this._computedViewMatrix;
  10958. }
  10959. this._computedViewMatrix = this._getViewMatrix();
  10960. this._currentRenderId = this.getScene().getRenderId();
  10961. return this._computedViewMatrix;
  10962. };
  10963. Camera.prototype.getProjectionMatrix = function (force) {
  10964. if (!force && this._isSynchronizedProjectionMatrix()) {
  10965. return this._projectionMatrix;
  10966. }
  10967. var engine = this.getEngine();
  10968. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10969. if (this.minZ <= 0) {
  10970. this.minZ = 0.1;
  10971. }
  10972. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10973. return this._projectionMatrix;
  10974. }
  10975. var halfWidth = engine.getRenderWidth() / 2.0;
  10976. var halfHeight = engine.getRenderHeight() / 2.0;
  10977. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10978. return this._projectionMatrix;
  10979. };
  10980. Camera.prototype.dispose = function () {
  10981. // Animations
  10982. this.getScene().stopAnimation(this);
  10983. // Remove from scene
  10984. this.getScene().removeCamera(this);
  10985. while (this._rigCameras.length > 0) {
  10986. this._rigCameras.pop().dispose();
  10987. }
  10988. // Postprocesses
  10989. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10990. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10991. }
  10992. _super.prototype.dispose.call(this);
  10993. };
  10994. // ---- Camera rigs section ----
  10995. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10996. while (this._rigCameras.length > 0) {
  10997. this._rigCameras.pop().dispose();
  10998. }
  10999. this.cameraRigMode = mode;
  11000. this._cameraRigParams = {};
  11001. switch (this.cameraRigMode) {
  11002. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11003. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11004. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11005. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11006. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11007. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11008. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11009. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11010. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11011. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11012. break;
  11013. }
  11014. var postProcesses = new Array();
  11015. switch (this.cameraRigMode) {
  11016. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11017. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11018. this._rigCameras[0].isIntermediate = true;
  11019. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11020. postProcesses[1].onApply = function (effect) {
  11021. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11022. };
  11023. break;
  11024. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11025. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11026. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11027. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11028. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11029. var secondCamIndex = 1 - firstCamIndex;
  11030. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11031. this._rigCameras[firstCamIndex].isIntermediate = true;
  11032. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11033. break;
  11034. case Camera.RIG_MODE_VR:
  11035. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11036. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11037. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11038. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11039. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11040. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11041. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11042. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11043. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11044. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11045. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11046. if (metrics.compensateDistortion) {
  11047. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11048. }
  11049. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11050. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11051. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11052. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11053. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11054. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11055. if (metrics.compensateDistortion) {
  11056. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11057. }
  11058. break;
  11059. }
  11060. this._update();
  11061. };
  11062. Camera.prototype._getVRProjectionMatrix = function () {
  11063. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11064. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11065. return this._projectionMatrix;
  11066. };
  11067. Camera.prototype.setCameraRigParameter = function (name, value) {
  11068. this._cameraRigParams[name] = value;
  11069. //provisionnally:
  11070. if (name === "interaxialDistance") {
  11071. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11072. }
  11073. };
  11074. /**
  11075. * May needs to be overridden by children so sub has required properties to be copied
  11076. */
  11077. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11078. return null;
  11079. };
  11080. /**
  11081. * May needs to be overridden by children
  11082. */
  11083. Camera.prototype._updateRigCameras = function () {
  11084. for (var i = 0; i < this._rigCameras.length; i++) {
  11085. this._rigCameras[i].minZ = this.minZ;
  11086. this._rigCameras[i].maxZ = this.maxZ;
  11087. this._rigCameras[i].fov = this.fov;
  11088. }
  11089. // only update viewport when ANAGLYPH
  11090. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11091. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11092. }
  11093. };
  11094. Camera.prototype.serialize = function () {
  11095. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11096. // Type
  11097. serializationObject.type = this.getTypeName();
  11098. // Parent
  11099. if (this.parent) {
  11100. serializationObject.parentId = this.parent.id;
  11101. }
  11102. if (this.inputs) {
  11103. this.inputs.serialize(serializationObject);
  11104. }
  11105. // Animations
  11106. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11107. serializationObject.ranges = this.serializeAnimationRanges();
  11108. return serializationObject;
  11109. };
  11110. Camera.prototype.getTypeName = function () {
  11111. return "Camera";
  11112. };
  11113. Camera.prototype.clone = function (name) {
  11114. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11115. };
  11116. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11117. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11118. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11119. switch (type) {
  11120. case "ArcRotateCamera":
  11121. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11122. case "DeviceOrientationCamera":
  11123. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11124. case "FollowCamera":
  11125. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11126. case "ArcFollowCamera":
  11127. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11128. case "GamepadCamera":
  11129. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11130. case "TouchCamera":
  11131. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11132. case "VirtualJoysticksCamera":
  11133. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11134. case "WebVRFreeCamera":
  11135. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11136. case "VRDeviceOrientationFreeCamera":
  11137. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11138. case "AnaglyphArcRotateCamera":
  11139. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11140. case "AnaglyphFreeCamera":
  11141. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11142. case "AnaglyphGamepadCamera":
  11143. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11144. case "AnaglyphUniversalCamera":
  11145. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11146. case "StereoscopicArcRotateCamera":
  11147. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11148. case "StereoscopicFreeCamera":
  11149. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11150. case "StereoscopicGamepadCamera":
  11151. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11152. case "StereoscopicUniversalCamera":
  11153. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11154. case "FreeCamera":
  11155. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11156. default:
  11157. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11158. }
  11159. };
  11160. Camera.Parse = function (parsedCamera, scene) {
  11161. var type = parsedCamera.type;
  11162. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11163. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11164. // Parent
  11165. if (parsedCamera.parentId) {
  11166. camera._waitingParentId = parsedCamera.parentId;
  11167. }
  11168. //If camera has an input manager, let it parse inputs settings
  11169. if (camera.inputs) {
  11170. camera.inputs.parse(parsedCamera);
  11171. }
  11172. // Target
  11173. if (parsedCamera.target) {
  11174. if (camera.setTarget) {
  11175. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11176. }
  11177. }
  11178. // Apply 3d rig, when found
  11179. if (parsedCamera.cameraRigMode) {
  11180. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11181. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11182. }
  11183. // Animations
  11184. if (parsedCamera.animations) {
  11185. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11186. var parsedAnimation = parsedCamera.animations[animationIndex];
  11187. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11188. }
  11189. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11190. }
  11191. if (parsedCamera.autoAnimate) {
  11192. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11193. }
  11194. return camera;
  11195. };
  11196. // Statics
  11197. Camera._PERSPECTIVE_CAMERA = 0;
  11198. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11199. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11200. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11201. Camera._RIG_MODE_NONE = 0;
  11202. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11203. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11204. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11205. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11206. Camera._RIG_MODE_VR = 20;
  11207. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11208. __decorate([
  11209. BABYLON.serializeAsVector3()
  11210. ], Camera.prototype, "position", void 0);
  11211. __decorate([
  11212. BABYLON.serializeAsVector3()
  11213. ], Camera.prototype, "upVector", void 0);
  11214. __decorate([
  11215. BABYLON.serialize()
  11216. ], Camera.prototype, "orthoLeft", void 0);
  11217. __decorate([
  11218. BABYLON.serialize()
  11219. ], Camera.prototype, "orthoRight", void 0);
  11220. __decorate([
  11221. BABYLON.serialize()
  11222. ], Camera.prototype, "orthoBottom", void 0);
  11223. __decorate([
  11224. BABYLON.serialize()
  11225. ], Camera.prototype, "orthoTop", void 0);
  11226. __decorate([
  11227. BABYLON.serialize()
  11228. ], Camera.prototype, "fov", void 0);
  11229. __decorate([
  11230. BABYLON.serialize()
  11231. ], Camera.prototype, "minZ", void 0);
  11232. __decorate([
  11233. BABYLON.serialize()
  11234. ], Camera.prototype, "maxZ", void 0);
  11235. __decorate([
  11236. BABYLON.serialize()
  11237. ], Camera.prototype, "inertia", void 0);
  11238. __decorate([
  11239. BABYLON.serialize()
  11240. ], Camera.prototype, "mode", void 0);
  11241. __decorate([
  11242. BABYLON.serialize()
  11243. ], Camera.prototype, "layerMask", void 0);
  11244. __decorate([
  11245. BABYLON.serialize()
  11246. ], Camera.prototype, "fovMode", void 0);
  11247. __decorate([
  11248. BABYLON.serialize()
  11249. ], Camera.prototype, "cameraRigMode", void 0);
  11250. __decorate([
  11251. BABYLON.serialize()
  11252. ], Camera.prototype, "interaxialDistance", void 0);
  11253. __decorate([
  11254. BABYLON.serialize()
  11255. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11256. return Camera;
  11257. })(BABYLON.Node);
  11258. BABYLON.Camera = Camera;
  11259. })(BABYLON || (BABYLON = {}));
  11260. var BABYLON;
  11261. (function (BABYLON) {
  11262. BABYLON.CameraInputTypes = {};
  11263. var CameraInputsManager = (function () {
  11264. function CameraInputsManager(camera) {
  11265. this.attached = {};
  11266. this.camera = camera;
  11267. this.checkInputs = function () { };
  11268. }
  11269. CameraInputsManager.prototype.add = function (input) {
  11270. var type = input.getSimpleName();
  11271. if (this.attached[type]) {
  11272. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11273. return;
  11274. }
  11275. this.attached[type] = input;
  11276. input.camera = this.camera;
  11277. //for checkInputs, we are dynamically creating a function
  11278. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11279. if (input.checkInputs) {
  11280. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11281. }
  11282. if (this.attachedElement) {
  11283. input.attachControl(this.attachedElement);
  11284. }
  11285. };
  11286. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11287. for (var cam in this.attached) {
  11288. var input = this.attached[cam];
  11289. if (input === inputToRemove) {
  11290. input.detachControl(this.attachedElement);
  11291. delete this.attached[cam];
  11292. this.rebuildInputCheck();
  11293. }
  11294. }
  11295. };
  11296. CameraInputsManager.prototype.removeByType = function (inputType) {
  11297. for (var cam in this.attached) {
  11298. var input = this.attached[cam];
  11299. if (input.getTypeName() === inputType) {
  11300. input.detachControl(this.attachedElement);
  11301. delete this.attached[cam];
  11302. this.rebuildInputCheck();
  11303. }
  11304. }
  11305. };
  11306. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11307. var current = this.checkInputs;
  11308. return function () {
  11309. current();
  11310. fn();
  11311. };
  11312. };
  11313. CameraInputsManager.prototype.attachInput = function (input) {
  11314. input.attachControl(this.attachedElement, this.noPreventDefault);
  11315. };
  11316. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11317. if (this.attachedElement) {
  11318. return;
  11319. }
  11320. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11321. this.attachedElement = element;
  11322. this.noPreventDefault = noPreventDefault;
  11323. for (var cam in this.attached) {
  11324. var input = this.attached[cam];
  11325. this.attached[cam].attachControl(element, noPreventDefault);
  11326. }
  11327. };
  11328. CameraInputsManager.prototype.detachElement = function (element) {
  11329. if (this.attachedElement !== element) {
  11330. return;
  11331. }
  11332. for (var cam in this.attached) {
  11333. var input = this.attached[cam];
  11334. this.attached[cam].detachControl(element);
  11335. }
  11336. this.attachedElement = null;
  11337. };
  11338. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11339. this.checkInputs = function () { };
  11340. for (var cam in this.attached) {
  11341. var input = this.attached[cam];
  11342. if (input.checkInputs) {
  11343. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11344. }
  11345. }
  11346. };
  11347. CameraInputsManager.prototype.clear = function () {
  11348. if (this.attachedElement) {
  11349. this.detachElement(this.attachedElement);
  11350. }
  11351. this.attached = {};
  11352. this.attachedElement = null;
  11353. this.checkInputs = function () { };
  11354. };
  11355. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11356. var inputs = {};
  11357. for (var cam in this.attached) {
  11358. var input = this.attached[cam];
  11359. var res = BABYLON.SerializationHelper.Serialize(input);
  11360. inputs[input.getTypeName()] = res;
  11361. }
  11362. serializedCamera.inputsmgr = inputs;
  11363. };
  11364. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11365. var parsedInputs = parsedCamera.inputsmgr;
  11366. if (parsedInputs) {
  11367. this.clear();
  11368. for (var n in parsedInputs) {
  11369. var construct = BABYLON.CameraInputTypes[n];
  11370. if (construct) {
  11371. var parsedinput = parsedInputs[n];
  11372. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11373. this.add(input);
  11374. }
  11375. }
  11376. }
  11377. else {
  11378. //2016-03-08 this part is for managing backward compatibility
  11379. for (var n in this.attached) {
  11380. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11381. if (construct) {
  11382. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11383. this.add(input);
  11384. }
  11385. }
  11386. }
  11387. };
  11388. return CameraInputsManager;
  11389. })();
  11390. BABYLON.CameraInputsManager = CameraInputsManager;
  11391. })(BABYLON || (BABYLON = {}));
  11392. var BABYLON;
  11393. (function (BABYLON) {
  11394. var FreeCameraMouseInput = (function () {
  11395. function FreeCameraMouseInput() {
  11396. this.angularSensibility = 2000.0;
  11397. }
  11398. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11399. var _this = this;
  11400. if (!this._onMouseDown) {
  11401. var camera = this.camera;
  11402. var engine = this.camera.getEngine();
  11403. this._onMouseDown = function (evt) {
  11404. _this.previousPosition = {
  11405. x: evt.clientX,
  11406. y: evt.clientY
  11407. };
  11408. if (!noPreventDefault) {
  11409. evt.preventDefault();
  11410. }
  11411. };
  11412. this._onMouseUp = function (evt) {
  11413. _this.previousPosition = null;
  11414. if (!noPreventDefault) {
  11415. evt.preventDefault();
  11416. }
  11417. };
  11418. this._onMouseOut = function (evt) {
  11419. _this.previousPosition = null;
  11420. if (!noPreventDefault) {
  11421. evt.preventDefault();
  11422. }
  11423. };
  11424. this._onMouseMove = function (evt) {
  11425. if (!_this.previousPosition && !engine.isPointerLock) {
  11426. return;
  11427. }
  11428. var offsetX;
  11429. var offsetY;
  11430. if (!engine.isPointerLock) {
  11431. offsetX = evt.clientX - _this.previousPosition.x;
  11432. offsetY = evt.clientY - _this.previousPosition.y;
  11433. }
  11434. else {
  11435. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11436. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11437. }
  11438. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11439. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11440. _this.previousPosition = {
  11441. x: evt.clientX,
  11442. y: evt.clientY
  11443. };
  11444. if (!noPreventDefault) {
  11445. evt.preventDefault();
  11446. }
  11447. };
  11448. }
  11449. element.addEventListener("mousedown", this._onMouseDown, false);
  11450. element.addEventListener("mouseup", this._onMouseUp, false);
  11451. element.addEventListener("mouseout", this._onMouseOut, false);
  11452. element.addEventListener("mousemove", this._onMouseMove, false);
  11453. };
  11454. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11455. if (this._onMouseDown && element) {
  11456. this.previousPosition = null;
  11457. element.removeEventListener("mousedown", this._onMouseDown);
  11458. element.removeEventListener("mouseup", this._onMouseUp);
  11459. element.removeEventListener("mouseout", this._onMouseOut);
  11460. element.removeEventListener("mousemove", this._onMouseMove);
  11461. this._onMouseDown = null;
  11462. this._onMouseUp = null;
  11463. this._onMouseOut = null;
  11464. this._onMouseMove = null;
  11465. }
  11466. };
  11467. FreeCameraMouseInput.prototype.getTypeName = function () {
  11468. return "FreeCameraMouseInput";
  11469. };
  11470. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11471. return "mouse";
  11472. };
  11473. __decorate([
  11474. BABYLON.serialize()
  11475. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11476. return FreeCameraMouseInput;
  11477. })();
  11478. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11479. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11480. })(BABYLON || (BABYLON = {}));
  11481. var BABYLON;
  11482. (function (BABYLON) {
  11483. var FreeCameraKeyboardMoveInput = (function () {
  11484. function FreeCameraKeyboardMoveInput() {
  11485. this._keys = [];
  11486. this.keysUp = [38];
  11487. this.keysDown = [40];
  11488. this.keysLeft = [37];
  11489. this.keysRight = [39];
  11490. }
  11491. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11492. var _this = this;
  11493. if (!this._onKeyDown) {
  11494. this._onKeyDown = function (evt) {
  11495. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11496. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11497. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11498. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11499. var index = _this._keys.indexOf(evt.keyCode);
  11500. if (index === -1) {
  11501. _this._keys.push(evt.keyCode);
  11502. }
  11503. if (!noPreventDefault) {
  11504. evt.preventDefault();
  11505. }
  11506. }
  11507. };
  11508. this._onKeyUp = function (evt) {
  11509. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11510. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11511. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11512. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11513. var index = _this._keys.indexOf(evt.keyCode);
  11514. if (index >= 0) {
  11515. _this._keys.splice(index, 1);
  11516. }
  11517. if (!noPreventDefault) {
  11518. evt.preventDefault();
  11519. }
  11520. }
  11521. };
  11522. BABYLON.Tools.RegisterTopRootEvents([
  11523. { name: "keydown", handler: this._onKeyDown },
  11524. { name: "keyup", handler: this._onKeyUp },
  11525. { name: "blur", handler: this._onLostFocus }
  11526. ]);
  11527. }
  11528. };
  11529. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11530. if (this._onKeyDown) {
  11531. BABYLON.Tools.UnregisterTopRootEvents([
  11532. { name: "keydown", handler: this._onKeyDown },
  11533. { name: "keyup", handler: this._onKeyUp },
  11534. { name: "blur", handler: this._onLostFocus }
  11535. ]);
  11536. this._keys = [];
  11537. this._onKeyDown = null;
  11538. this._onKeyUp = null;
  11539. }
  11540. };
  11541. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11542. if (this._onKeyDown) {
  11543. var camera = this.camera;
  11544. // Keyboard
  11545. for (var index = 0; index < this._keys.length; index++) {
  11546. var keyCode = this._keys[index];
  11547. var speed = camera._computeLocalCameraSpeed();
  11548. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11549. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11550. }
  11551. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11552. camera._localDirection.copyFromFloats(0, 0, speed);
  11553. }
  11554. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11555. camera._localDirection.copyFromFloats(speed, 0, 0);
  11556. }
  11557. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11558. camera._localDirection.copyFromFloats(0, 0, -speed);
  11559. }
  11560. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11561. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11562. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11563. }
  11564. }
  11565. };
  11566. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11567. return "FreeCameraKeyboardMoveInput";
  11568. };
  11569. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11570. this._keys = [];
  11571. };
  11572. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11573. return "keyboard";
  11574. };
  11575. __decorate([
  11576. BABYLON.serialize()
  11577. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11578. __decorate([
  11579. BABYLON.serialize()
  11580. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11581. __decorate([
  11582. BABYLON.serialize()
  11583. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11584. __decorate([
  11585. BABYLON.serialize()
  11586. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11587. return FreeCameraKeyboardMoveInput;
  11588. })();
  11589. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11590. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11591. })(BABYLON || (BABYLON = {}));
  11592. var BABYLON;
  11593. (function (BABYLON) {
  11594. var FreeCameraTouchInput = (function () {
  11595. function FreeCameraTouchInput() {
  11596. this._offsetX = null;
  11597. this._offsetY = null;
  11598. this._pointerCount = 0;
  11599. this._pointerPressed = [];
  11600. this.touchAngularSensibility = 200000.0;
  11601. this.touchMoveSensibility = 250.0;
  11602. }
  11603. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11604. var _this = this;
  11605. var previousPosition;
  11606. if (this._onPointerDown === undefined) {
  11607. this._onLostFocus = function (evt) {
  11608. _this._offsetX = null;
  11609. _this._offsetY = null;
  11610. };
  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. element.addEventListener("blur", this._onLostFocus);
  11665. element.addEventListener("pointerdown", this._onPointerDown);
  11666. element.addEventListener("pointerup", this._onPointerUp);
  11667. element.addEventListener("pointerout", this._onPointerUp);
  11668. element.addEventListener("pointermove", this._onPointerMove);
  11669. };
  11670. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11671. if (this._onPointerDown && element) {
  11672. element.removeEventListener("blur", this._onLostFocus);
  11673. element.removeEventListener("pointerdown", this._onPointerDown);
  11674. element.removeEventListener("pointerup", this._onPointerUp);
  11675. element.removeEventListener("pointerout", this._onPointerUp);
  11676. element.removeEventListener("pointermove", this._onPointerMove);
  11677. this._onPointerDown = null;
  11678. this._onPointerUp = null;
  11679. this._onPointerMove = null;
  11680. this._onLostFocus = null;
  11681. this._pointerPressed = [];
  11682. this._offsetX = null;
  11683. this._offsetY = null;
  11684. this._pointerCount = 0;
  11685. }
  11686. };
  11687. FreeCameraTouchInput.prototype.checkInputs = function () {
  11688. if (this._offsetX) {
  11689. var camera = this.camera;
  11690. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11691. if (this._pointerPressed.length > 1) {
  11692. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11693. }
  11694. else {
  11695. var speed = camera._computeLocalCameraSpeed();
  11696. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11697. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11698. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11699. }
  11700. }
  11701. };
  11702. FreeCameraTouchInput.prototype.getTypeName = function () {
  11703. return "FreeCameraTouchInput";
  11704. };
  11705. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11706. return "touch";
  11707. };
  11708. __decorate([
  11709. BABYLON.serialize()
  11710. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11711. __decorate([
  11712. BABYLON.serialize()
  11713. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11714. return FreeCameraTouchInput;
  11715. })();
  11716. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11717. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11718. })(BABYLON || (BABYLON = {}));
  11719. var BABYLON;
  11720. (function (BABYLON) {
  11721. var FreeCameraDeviceOrientationInput = (function () {
  11722. function FreeCameraDeviceOrientationInput() {
  11723. this._offsetX = null;
  11724. this._offsetY = null;
  11725. this._orientationGamma = 0;
  11726. this._orientationBeta = 0;
  11727. this._initialOrientationGamma = 0;
  11728. this._initialOrientationBeta = 0;
  11729. this.angularSensibility = 10000.0;
  11730. this.moveSensibility = 50.0;
  11731. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11732. this._orientationChanged = this.orientationChanged.bind(this);
  11733. }
  11734. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11735. window.addEventListener("resize", this._resetOrientationGamma, false);
  11736. window.addEventListener("deviceorientation", this._orientationChanged);
  11737. };
  11738. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11739. this._initialOrientationGamma = null;
  11740. };
  11741. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11742. if (!this._initialOrientationGamma) {
  11743. this._initialOrientationGamma = evt.gamma;
  11744. this._initialOrientationBeta = evt.beta;
  11745. }
  11746. this._orientationGamma = evt.gamma;
  11747. this._orientationBeta = evt.beta;
  11748. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11749. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11750. };
  11751. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11752. window.removeEventListener("resize", this._resetOrientationGamma);
  11753. window.removeEventListener("deviceorientation", this._orientationChanged);
  11754. this._orientationGamma = 0;
  11755. this._orientationBeta = 0;
  11756. this._initialOrientationGamma = 0;
  11757. this._initialOrientationBeta = 0;
  11758. this._offsetX = null;
  11759. this._offsetY = null;
  11760. };
  11761. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11762. if (!this._offsetX) {
  11763. return;
  11764. }
  11765. var camera = this.camera;
  11766. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11767. var speed = camera._computeLocalCameraSpeed();
  11768. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11769. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11770. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11771. };
  11772. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11773. return "FreeCameraDeviceOrientationInput";
  11774. };
  11775. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11776. return "deviceOrientation";
  11777. };
  11778. __decorate([
  11779. BABYLON.serialize()
  11780. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11781. __decorate([
  11782. BABYLON.serialize()
  11783. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11784. return FreeCameraDeviceOrientationInput;
  11785. })();
  11786. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11787. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11788. })(BABYLON || (BABYLON = {}));
  11789. var BABYLON;
  11790. (function (BABYLON) {
  11791. var FreeCameraVRDeviceOrientationInput = (function () {
  11792. function FreeCameraVRDeviceOrientationInput() {
  11793. this.alphaCorrection = 1;
  11794. this.betaCorrection = 1;
  11795. this.gammaCorrection = 1;
  11796. this._alpha = 0;
  11797. this._beta = 0;
  11798. this._gamma = 0;
  11799. this._dirty = false;
  11800. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11801. }
  11802. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11803. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11804. };
  11805. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11806. var camera = this.camera;
  11807. this._alpha = +evt.alpha | 0;
  11808. this._beta = +evt.beta | 0;
  11809. this._gamma = +evt.gamma | 0;
  11810. this._dirty = true;
  11811. };
  11812. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11813. if (this._dirty) {
  11814. this._dirty = false;
  11815. var rotationX = this._gamma;
  11816. if (rotationX < 0) {
  11817. rotationX = 90 + rotationX;
  11818. }
  11819. else {
  11820. // Incline it in the correct angle.
  11821. rotationX = 270 - rotationX;
  11822. }
  11823. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11824. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11825. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11826. }
  11827. };
  11828. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11829. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11830. };
  11831. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11832. return "FreeCameraVRDeviceOrientationInput";
  11833. };
  11834. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11835. return "VRDeviceOrientation";
  11836. };
  11837. return FreeCameraVRDeviceOrientationInput;
  11838. })();
  11839. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11840. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11841. })(BABYLON || (BABYLON = {}));
  11842. var BABYLON;
  11843. (function (BABYLON) {
  11844. var FreeCameraGamepadInput = (function () {
  11845. function FreeCameraGamepadInput() {
  11846. this.gamepadAngularSensibility = 200;
  11847. this.gamepadMoveSensibility = 40;
  11848. }
  11849. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  11850. var _this = this;
  11851. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11852. };
  11853. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  11854. if (this._gamepads) {
  11855. this._gamepads.dispose();
  11856. }
  11857. this.gamepad = null;
  11858. };
  11859. FreeCameraGamepadInput.prototype.checkInputs = function () {
  11860. if (this.gamepad) {
  11861. var camera = this.camera;
  11862. var LSValues = this.gamepad.leftStick;
  11863. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  11864. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  11865. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11866. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11867. var RSValues = this.gamepad.rightStick;
  11868. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  11869. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  11870. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11871. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11872. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11873. var speed = camera._computeLocalCameraSpeed() * 50.0;
  11874. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11875. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11876. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11877. }
  11878. };
  11879. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  11880. // Only the first gamepad can control the camera
  11881. if (gamepad.index === 0) {
  11882. this.gamepad = gamepad;
  11883. }
  11884. };
  11885. FreeCameraGamepadInput.prototype.getTypeName = function () {
  11886. return "FreeCameraGamepadInput";
  11887. };
  11888. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  11889. return "gamepad";
  11890. };
  11891. __decorate([
  11892. BABYLON.serialize()
  11893. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  11894. __decorate([
  11895. BABYLON.serialize()
  11896. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  11897. return FreeCameraGamepadInput;
  11898. })();
  11899. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  11900. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  11901. })(BABYLON || (BABYLON = {}));
  11902. var BABYLON;
  11903. (function (BABYLON) {
  11904. var FreeCameraVirtualJoystickInput = (function () {
  11905. function FreeCameraVirtualJoystickInput() {
  11906. }
  11907. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  11908. return this._leftjoystick;
  11909. };
  11910. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  11911. return this._rightjoystick;
  11912. };
  11913. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  11914. if (this._leftjoystick) {
  11915. var camera = this.camera;
  11916. var speed = camera._computeLocalCameraSpeed() * 50;
  11917. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  11918. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  11919. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  11920. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  11921. if (!this._leftjoystick.pressed) {
  11922. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  11923. }
  11924. if (!this._rightjoystick.pressed) {
  11925. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  11926. }
  11927. }
  11928. };
  11929. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  11930. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  11931. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  11932. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  11933. this._leftjoystick.setJoystickSensibility(0.15);
  11934. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  11935. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  11936. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  11937. this._rightjoystick.reverseUpDown = true;
  11938. this._rightjoystick.setJoystickSensibility(0.05);
  11939. this._rightjoystick.setJoystickColor("yellow");
  11940. };
  11941. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  11942. this._leftjoystick.releaseCanvas();
  11943. this._rightjoystick.releaseCanvas();
  11944. };
  11945. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  11946. return "FreeCameraVirtualJoystickInput";
  11947. };
  11948. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  11949. return "virtualJoystick";
  11950. };
  11951. return FreeCameraVirtualJoystickInput;
  11952. })();
  11953. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  11954. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  11955. })(BABYLON || (BABYLON = {}));
  11956. var BABYLON;
  11957. (function (BABYLON) {
  11958. var ArcRotateCameraKeyboardMoveInput = (function () {
  11959. function ArcRotateCameraKeyboardMoveInput() {
  11960. this._keys = [];
  11961. this.keysUp = [38];
  11962. this.keysDown = [40];
  11963. this.keysLeft = [37];
  11964. this.keysRight = [39];
  11965. }
  11966. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11967. var _this = this;
  11968. this._onKeyDown = function (evt) {
  11969. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11970. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11971. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11972. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11973. var index = _this._keys.indexOf(evt.keyCode);
  11974. if (index === -1) {
  11975. _this._keys.push(evt.keyCode);
  11976. }
  11977. if (evt.preventDefault) {
  11978. if (!noPreventDefault) {
  11979. evt.preventDefault();
  11980. }
  11981. }
  11982. }
  11983. };
  11984. this._onKeyUp = function (evt) {
  11985. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11986. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11987. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11988. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11989. var index = _this._keys.indexOf(evt.keyCode);
  11990. if (index >= 0) {
  11991. _this._keys.splice(index, 1);
  11992. }
  11993. if (evt.preventDefault) {
  11994. if (!noPreventDefault) {
  11995. evt.preventDefault();
  11996. }
  11997. }
  11998. }
  11999. };
  12000. this._onLostFocus = function () {
  12001. _this._keys = [];
  12002. };
  12003. BABYLON.Tools.RegisterTopRootEvents([
  12004. { name: "keydown", handler: this._onKeyDown },
  12005. { name: "keyup", handler: this._onKeyUp },
  12006. { name: "blur", handler: this._onLostFocus }
  12007. ]);
  12008. };
  12009. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12010. BABYLON.Tools.UnregisterTopRootEvents([
  12011. { name: "keydown", handler: this._onKeyDown },
  12012. { name: "keyup", handler: this._onKeyUp },
  12013. { name: "blur", handler: this._onLostFocus }
  12014. ]);
  12015. this._keys = [];
  12016. this._onKeyDown = null;
  12017. this._onKeyUp = null;
  12018. this._onLostFocus = null;
  12019. };
  12020. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12021. if (this._onKeyDown) {
  12022. var camera = this.camera;
  12023. for (var index = 0; index < this._keys.length; index++) {
  12024. var keyCode = this._keys[index];
  12025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12026. camera.inertialAlphaOffset -= 0.01;
  12027. }
  12028. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12029. camera.inertialBetaOffset -= 0.01;
  12030. }
  12031. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12032. camera.inertialAlphaOffset += 0.01;
  12033. }
  12034. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12035. camera.inertialBetaOffset += 0.01;
  12036. }
  12037. }
  12038. }
  12039. };
  12040. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12041. return "ArcRotateCameraKeyboardMoveInput";
  12042. };
  12043. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12044. return "keyboard";
  12045. };
  12046. __decorate([
  12047. BABYLON.serialize()
  12048. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12049. __decorate([
  12050. BABYLON.serialize()
  12051. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12052. __decorate([
  12053. BABYLON.serialize()
  12054. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12055. __decorate([
  12056. BABYLON.serialize()
  12057. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12058. return ArcRotateCameraKeyboardMoveInput;
  12059. })();
  12060. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12061. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12062. })(BABYLON || (BABYLON = {}));
  12063. var BABYLON;
  12064. (function (BABYLON) {
  12065. var ArcRotateCameraMouseWheelInput = (function () {
  12066. function ArcRotateCameraMouseWheelInput() {
  12067. this.wheelPrecision = 3.0;
  12068. }
  12069. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12070. var _this = this;
  12071. this._wheel = function (event) {
  12072. var delta = 0;
  12073. if (event.wheelDelta) {
  12074. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12075. }
  12076. else if (event.detail) {
  12077. delta = -event.detail / _this.wheelPrecision;
  12078. }
  12079. if (delta)
  12080. _this.camera.inertialRadiusOffset += delta;
  12081. if (event.preventDefault) {
  12082. if (!noPreventDefault) {
  12083. event.preventDefault();
  12084. }
  12085. }
  12086. };
  12087. element.addEventListener('mousewheel', this._wheel, false);
  12088. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12089. };
  12090. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12091. if (this._wheel && element) {
  12092. element.removeEventListener('mousewheel', this._wheel);
  12093. element.removeEventListener('DOMMouseScroll', this._wheel);
  12094. this._wheel = null;
  12095. }
  12096. };
  12097. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12098. return "ArcRotateCameraMouseWheelInput";
  12099. };
  12100. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12101. return "mousewheel";
  12102. };
  12103. __decorate([
  12104. BABYLON.serialize()
  12105. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12106. return ArcRotateCameraMouseWheelInput;
  12107. })();
  12108. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12109. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12110. })(BABYLON || (BABYLON = {}));
  12111. var BABYLON;
  12112. (function (BABYLON) {
  12113. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12114. var ArcRotateCameraPointersInput = (function () {
  12115. function ArcRotateCameraPointersInput() {
  12116. this.angularSensibilityX = 1000.0;
  12117. this.angularSensibilityY = 1000.0;
  12118. this.pinchPrecision = 6.0;
  12119. this.panningSensibility = 50.0;
  12120. this._isRightClick = false;
  12121. this._isCtrlPushed = false;
  12122. this.pinchInwards = true;
  12123. }
  12124. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12125. var _this = this;
  12126. var engine = this.camera.getEngine();
  12127. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12128. var pointers = new BABYLON.SmartCollection();
  12129. var previousPinchDistance = 0;
  12130. this._onContextMenu = function (evt) {
  12131. evt.preventDefault();
  12132. };
  12133. if (!this.camera._useCtrlForPanning) {
  12134. element.addEventListener("contextmenu", this._onContextMenu, false);
  12135. }
  12136. this._onLostFocus = function () {
  12137. //this._keys = [];
  12138. pointers.empty();
  12139. previousPinchDistance = 0;
  12140. cacheSoloPointer = null;
  12141. };
  12142. this._onKeyDown = function (evt) {
  12143. _this._isCtrlPushed = evt.ctrlKey;
  12144. };
  12145. this._onKeyUp = function (evt) {
  12146. _this._isCtrlPushed = evt.ctrlKey;
  12147. };
  12148. this._onPointerDown = function (evt) {
  12149. // Manage panning with right click
  12150. _this._isRightClick = evt.button === 2;
  12151. // manage pointers
  12152. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12153. cacheSoloPointer = pointers.item(evt.pointerId);
  12154. if (!noPreventDefault) {
  12155. evt.preventDefault();
  12156. }
  12157. };
  12158. this._onPointerUp = function (evt) {
  12159. cacheSoloPointer = null;
  12160. previousPinchDistance = 0;
  12161. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12162. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12163. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12164. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12165. pointers.empty();
  12166. if (!noPreventDefault) {
  12167. evt.preventDefault();
  12168. }
  12169. };
  12170. this._onPointerMove = function (evt) {
  12171. if (!noPreventDefault) {
  12172. evt.preventDefault();
  12173. }
  12174. switch (pointers.count) {
  12175. case 1:
  12176. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12177. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12178. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12179. }
  12180. else {
  12181. var offsetX = evt.clientX - cacheSoloPointer.x;
  12182. var offsetY = evt.clientY - cacheSoloPointer.y;
  12183. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12184. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12185. }
  12186. cacheSoloPointer.x = evt.clientX;
  12187. cacheSoloPointer.y = evt.clientY;
  12188. break;
  12189. case 2:
  12190. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12191. pointers.item(evt.pointerId).x = evt.clientX;
  12192. pointers.item(evt.pointerId).y = evt.clientY;
  12193. var direction = _this.pinchInwards ? 1 : -1;
  12194. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12195. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12196. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12197. if (previousPinchDistance === 0) {
  12198. previousPinchDistance = pinchSquaredDistance;
  12199. return;
  12200. }
  12201. if (pinchSquaredDistance !== previousPinchDistance) {
  12202. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12203. previousPinchDistance = pinchSquaredDistance;
  12204. }
  12205. break;
  12206. default:
  12207. if (pointers.item(evt.pointerId)) {
  12208. pointers.item(evt.pointerId).x = evt.clientX;
  12209. pointers.item(evt.pointerId).y = evt.clientY;
  12210. }
  12211. }
  12212. };
  12213. this._onMouseMove = function (evt) {
  12214. if (!engine.isPointerLock) {
  12215. return;
  12216. }
  12217. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12218. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12219. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12220. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12221. if (!noPreventDefault) {
  12222. evt.preventDefault();
  12223. }
  12224. };
  12225. this._onGestureStart = function (e) {
  12226. if (window.MSGesture === undefined) {
  12227. return;
  12228. }
  12229. if (!_this._MSGestureHandler) {
  12230. _this._MSGestureHandler = new MSGesture();
  12231. _this._MSGestureHandler.target = element;
  12232. }
  12233. _this._MSGestureHandler.addPointer(e.pointerId);
  12234. };
  12235. this._onGesture = function (e) {
  12236. _this.camera.radius *= e.scale;
  12237. if (e.preventDefault) {
  12238. if (!noPreventDefault) {
  12239. e.stopPropagation();
  12240. e.preventDefault();
  12241. }
  12242. }
  12243. };
  12244. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12245. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12246. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12247. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12248. element.addEventListener("mousemove", this._onMouseMove, false);
  12249. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12250. element.addEventListener("MSGestureChange", this._onGesture, false);
  12251. BABYLON.Tools.RegisterTopRootEvents([
  12252. { name: "keydown", handler: this._onKeyDown },
  12253. { name: "keyup", handler: this._onKeyUp },
  12254. { name: "blur", handler: this._onLostFocus }
  12255. ]);
  12256. };
  12257. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12258. if (element && this._onPointerDown) {
  12259. element.removeEventListener("contextmenu", this._onContextMenu);
  12260. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12261. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12262. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12263. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12264. element.removeEventListener("mousemove", this._onMouseMove);
  12265. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12266. element.removeEventListener("MSGestureChange", this._onGesture);
  12267. this._isRightClick = false;
  12268. this._isCtrlPushed = false;
  12269. this.pinchInwards = true;
  12270. this._onKeyDown = null;
  12271. this._onKeyUp = null;
  12272. this._onPointerDown = null;
  12273. this._onPointerUp = null;
  12274. this._onPointerMove = null;
  12275. this._onMouseMove = null;
  12276. this._onGestureStart = null;
  12277. this._onGesture = null;
  12278. this._MSGestureHandler = null;
  12279. this._onLostFocus = null;
  12280. this._onContextMenu = null;
  12281. }
  12282. BABYLON.Tools.UnregisterTopRootEvents([
  12283. { name: "keydown", handler: this._onKeyDown },
  12284. { name: "keyup", handler: this._onKeyUp },
  12285. { name: "blur", handler: this._onLostFocus }
  12286. ]);
  12287. };
  12288. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12289. return "ArcRotateCameraPointersInput";
  12290. };
  12291. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12292. return "pointers";
  12293. };
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12297. __decorate([
  12298. BABYLON.serialize()
  12299. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12303. __decorate([
  12304. BABYLON.serialize()
  12305. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12306. return ArcRotateCameraPointersInput;
  12307. })();
  12308. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12309. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12310. })(BABYLON || (BABYLON = {}));
  12311. var BABYLON;
  12312. (function (BABYLON) {
  12313. var ArcRotateCameraGamepadInput = (function () {
  12314. function ArcRotateCameraGamepadInput() {
  12315. this.gamepadRotationSensibility = 80;
  12316. this.gamepadMoveSensibility = 40;
  12317. }
  12318. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12319. var _this = this;
  12320. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12321. };
  12322. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12323. if (this._gamepads) {
  12324. this._gamepads.dispose();
  12325. }
  12326. this.gamepad = null;
  12327. };
  12328. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12329. if (this.gamepad) {
  12330. var camera = this.camera;
  12331. var RSValues = this.gamepad.rightStick;
  12332. if (RSValues.x != 0) {
  12333. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12334. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12335. camera.inertialAlphaOffset += normalizedRX;
  12336. }
  12337. }
  12338. if (RSValues.y != 0) {
  12339. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12340. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12341. camera.inertialBetaOffset += normalizedRY;
  12342. }
  12343. }
  12344. var LSValues = this.gamepad.leftStick;
  12345. if (LSValues.y != 0) {
  12346. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12347. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12348. this.camera.inertialRadiusOffset -= normalizedLY;
  12349. }
  12350. }
  12351. }
  12352. };
  12353. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12354. // Only the first gamepad can control the camera
  12355. if (gamepad.index === 0) {
  12356. this.gamepad = gamepad;
  12357. }
  12358. };
  12359. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12360. return "ArcRotateCameraGamepadInput";
  12361. };
  12362. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12363. return "gamepad";
  12364. };
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12368. __decorate([
  12369. BABYLON.serialize()
  12370. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12371. return ArcRotateCameraGamepadInput;
  12372. })();
  12373. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12374. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12375. })(BABYLON || (BABYLON = {}));
  12376. var BABYLON;
  12377. (function (BABYLON) {
  12378. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12379. function ArcRotateCameraVRDeviceOrientationInput() {
  12380. this.alphaCorrection = 1;
  12381. this.betaCorrection = 1;
  12382. this.gammaCorrection = 1;
  12383. this._alpha = 0;
  12384. this._beta = 0;
  12385. this._gamma = 0;
  12386. this._dirty = false;
  12387. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12388. }
  12389. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12390. this.camera.attachControl(element, noPreventDefault);
  12391. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12392. };
  12393. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12394. var camera = this.camera;
  12395. this._alpha = +evt.alpha | 0;
  12396. this._beta = +evt.beta | 0;
  12397. this._gamma = +evt.gamma | 0;
  12398. this._dirty = true;
  12399. };
  12400. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12401. if (this._dirty) {
  12402. this._dirty = false;
  12403. if (this._gamma < 0) {
  12404. this._gamma = 180 + this._gamma;
  12405. }
  12406. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12407. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12408. }
  12409. };
  12410. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12411. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12412. };
  12413. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12414. return "ArcRotateCameraVRDeviceOrientationInput";
  12415. };
  12416. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12417. return "VRDeviceOrientation";
  12418. };
  12419. return ArcRotateCameraVRDeviceOrientationInput;
  12420. })();
  12421. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12422. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12423. })(BABYLON || (BABYLON = {}));
  12424. var BABYLON;
  12425. (function (BABYLON) {
  12426. var TargetCamera = (function (_super) {
  12427. __extends(TargetCamera, _super);
  12428. function TargetCamera(name, position, scene) {
  12429. _super.call(this, name, position, scene);
  12430. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12431. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12432. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12433. this.speed = 2.0;
  12434. this.noRotationConstraint = false;
  12435. this.lockedTarget = null;
  12436. this._currentTarget = BABYLON.Vector3.Zero();
  12437. this._viewMatrix = BABYLON.Matrix.Zero();
  12438. this._camMatrix = BABYLON.Matrix.Zero();
  12439. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12440. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12441. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12442. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12443. this._lookAtTemp = BABYLON.Matrix.Zero();
  12444. this._tempMatrix = BABYLON.Matrix.Zero();
  12445. }
  12446. TargetCamera.prototype.getFrontPosition = function (distance) {
  12447. var direction = this.getTarget().subtract(this.position);
  12448. direction.normalize();
  12449. direction.scaleInPlace(distance);
  12450. return this.globalPosition.add(direction);
  12451. };
  12452. TargetCamera.prototype._getLockedTargetPosition = function () {
  12453. if (!this.lockedTarget) {
  12454. return null;
  12455. }
  12456. return this.lockedTarget.position || this.lockedTarget;
  12457. };
  12458. // Cache
  12459. TargetCamera.prototype._initCache = function () {
  12460. _super.prototype._initCache.call(this);
  12461. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12462. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12463. };
  12464. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12465. if (!ignoreParentClass) {
  12466. _super.prototype._updateCache.call(this);
  12467. }
  12468. var lockedTargetPosition = this._getLockedTargetPosition();
  12469. if (!lockedTargetPosition) {
  12470. this._cache.lockedTarget = null;
  12471. }
  12472. else {
  12473. if (!this._cache.lockedTarget) {
  12474. this._cache.lockedTarget = lockedTargetPosition.clone();
  12475. }
  12476. else {
  12477. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12478. }
  12479. }
  12480. this._cache.rotation.copyFrom(this.rotation);
  12481. };
  12482. // Synchronized
  12483. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12484. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12485. return false;
  12486. }
  12487. var lockedTargetPosition = this._getLockedTargetPosition();
  12488. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12489. && this._cache.rotation.equals(this.rotation);
  12490. };
  12491. // Methods
  12492. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12493. var engine = this.getEngine();
  12494. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12495. };
  12496. // Target
  12497. TargetCamera.prototype.setTarget = function (target) {
  12498. this.upVector.normalize();
  12499. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12500. this._camMatrix.invert();
  12501. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12502. var vDir = target.subtract(this.position);
  12503. if (vDir.x >= 0.0) {
  12504. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12505. }
  12506. else {
  12507. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12508. }
  12509. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12510. if (isNaN(this.rotation.x)) {
  12511. this.rotation.x = 0;
  12512. }
  12513. if (isNaN(this.rotation.y)) {
  12514. this.rotation.y = 0;
  12515. }
  12516. if (isNaN(this.rotation.z)) {
  12517. this.rotation.z = 0;
  12518. }
  12519. };
  12520. TargetCamera.prototype.getTarget = function () {
  12521. return this._currentTarget;
  12522. };
  12523. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12524. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12525. };
  12526. TargetCamera.prototype._updatePosition = function () {
  12527. this.position.addInPlace(this.cameraDirection);
  12528. };
  12529. TargetCamera.prototype._checkInputs = function () {
  12530. var needToMove = this._decideIfNeedsToMove();
  12531. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12532. // Move
  12533. if (needToMove) {
  12534. this._updatePosition();
  12535. }
  12536. // Rotate
  12537. if (needToRotate) {
  12538. this.rotation.x += this.cameraRotation.x;
  12539. this.rotation.y += this.cameraRotation.y;
  12540. if (!this.noRotationConstraint) {
  12541. var limit = (Math.PI / 2) * 0.95;
  12542. if (this.rotation.x > limit)
  12543. this.rotation.x = limit;
  12544. if (this.rotation.x < -limit)
  12545. this.rotation.x = -limit;
  12546. }
  12547. }
  12548. // Inertia
  12549. if (needToMove) {
  12550. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12551. this.cameraDirection.x = 0;
  12552. }
  12553. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12554. this.cameraDirection.y = 0;
  12555. }
  12556. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12557. this.cameraDirection.z = 0;
  12558. }
  12559. this.cameraDirection.scaleInPlace(this.inertia);
  12560. }
  12561. if (needToRotate) {
  12562. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12563. this.cameraRotation.x = 0;
  12564. }
  12565. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12566. this.cameraRotation.y = 0;
  12567. }
  12568. this.cameraRotation.scaleInPlace(this.inertia);
  12569. }
  12570. _super.prototype._checkInputs.call(this);
  12571. };
  12572. TargetCamera.prototype._getViewMatrix = function () {
  12573. if (!this.lockedTarget) {
  12574. // Compute
  12575. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12576. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12578. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12579. this._lookAtTemp.invert();
  12580. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12581. }
  12582. else {
  12583. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12584. }
  12585. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12586. // Computing target and final matrix
  12587. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12588. }
  12589. else {
  12590. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12591. }
  12592. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12593. return this._viewMatrix;
  12594. };
  12595. TargetCamera.prototype._getVRViewMatrix = function () {
  12596. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12597. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12598. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12599. // Computing target and final matrix
  12600. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12601. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12602. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12603. return this._viewMatrix;
  12604. };
  12605. /**
  12606. * @override
  12607. * Override Camera.createRigCamera
  12608. */
  12609. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12610. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12611. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12612. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12613. rigCamera._cameraRigParams = {};
  12614. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12615. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12616. }
  12617. return rigCamera;
  12618. }
  12619. return null;
  12620. };
  12621. /**
  12622. * @override
  12623. * Override Camera._updateRigCameras
  12624. */
  12625. TargetCamera.prototype._updateRigCameras = function () {
  12626. switch (this.cameraRigMode) {
  12627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12628. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12629. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12631. case BABYLON.Camera.RIG_MODE_VR:
  12632. var camLeft = this._rigCameras[0];
  12633. var camRight = this._rigCameras[1];
  12634. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12635. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12636. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12637. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12638. camLeft.position.copyFrom(this.position);
  12639. camRight.position.copyFrom(this.position);
  12640. }
  12641. else {
  12642. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12643. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12644. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12645. camLeft.setTarget(this.getTarget());
  12646. camRight.setTarget(this.getTarget());
  12647. }
  12648. break;
  12649. }
  12650. _super.prototype._updateRigCameras.call(this);
  12651. };
  12652. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12653. if (!this._rigCamTransformMatrix) {
  12654. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12655. }
  12656. var target = this.getTarget();
  12657. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12658. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12660. };
  12661. TargetCamera.prototype.getTypeName = function () {
  12662. return "TargetCamera";
  12663. };
  12664. __decorate([
  12665. BABYLON.serializeAsVector3()
  12666. ], TargetCamera.prototype, "rotation", void 0);
  12667. __decorate([
  12668. BABYLON.serialize()
  12669. ], TargetCamera.prototype, "speed", void 0);
  12670. __decorate([
  12671. BABYLON.serializeAsMeshReference("lockedTargetId")
  12672. ], TargetCamera.prototype, "lockedTarget", void 0);
  12673. return TargetCamera;
  12674. })(BABYLON.Camera);
  12675. BABYLON.TargetCamera = TargetCamera;
  12676. })(BABYLON || (BABYLON = {}));
  12677. var BABYLON;
  12678. (function (BABYLON) {
  12679. var FreeCamera = (function (_super) {
  12680. __extends(FreeCamera, _super);
  12681. function FreeCamera(name, position, scene) {
  12682. var _this = this;
  12683. _super.call(this, name, position, scene);
  12684. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12685. this.checkCollisions = false;
  12686. this.applyGravity = false;
  12687. this._collider = new BABYLON.Collider();
  12688. this._needMoveForGravity = false;
  12689. this._oldPosition = BABYLON.Vector3.Zero();
  12690. this._diffPosition = BABYLON.Vector3.Zero();
  12691. this._newPosition = BABYLON.Vector3.Zero();
  12692. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12693. if (collidedMesh === void 0) { collidedMesh = null; }
  12694. //TODO move this to the collision coordinator!
  12695. if (_this.getScene().workerCollisions)
  12696. newPosition.multiplyInPlace(_this._collider.radius);
  12697. var updatePosition = function (newPos) {
  12698. _this._newPosition.copyFrom(newPos);
  12699. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12700. var oldPosition = _this.position.clone();
  12701. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12702. _this.position.addInPlace(_this._diffPosition);
  12703. if (_this.onCollide && collidedMesh) {
  12704. _this.onCollide(collidedMesh);
  12705. }
  12706. }
  12707. };
  12708. updatePosition(newPosition);
  12709. };
  12710. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12711. this.inputs.addKeyboard().addMouse();
  12712. }
  12713. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12714. //-- begin properties for backward compatibility for inputs
  12715. get: function () {
  12716. var mouse = this.inputs.attached["mouse"];
  12717. if (mouse)
  12718. return mouse.angularSensibility;
  12719. },
  12720. set: function (value) {
  12721. var mouse = this.inputs.attached["mouse"];
  12722. if (mouse)
  12723. mouse.angularSensibility = value;
  12724. },
  12725. enumerable: true,
  12726. configurable: true
  12727. });
  12728. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12729. get: function () {
  12730. var keyboard = this.inputs.attached["keyboard"];
  12731. if (keyboard)
  12732. return keyboard.keysUp;
  12733. },
  12734. set: function (value) {
  12735. var keyboard = this.inputs.attached["keyboard"];
  12736. if (keyboard)
  12737. keyboard.keysUp = value;
  12738. },
  12739. enumerable: true,
  12740. configurable: true
  12741. });
  12742. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12743. get: function () {
  12744. var keyboard = this.inputs.attached["keyboard"];
  12745. if (keyboard)
  12746. return keyboard.keysDown;
  12747. },
  12748. set: function (value) {
  12749. var keyboard = this.inputs.attached["keyboard"];
  12750. if (keyboard)
  12751. keyboard.keysDown = value;
  12752. },
  12753. enumerable: true,
  12754. configurable: true
  12755. });
  12756. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12757. get: function () {
  12758. var keyboard = this.inputs.attached["keyboard"];
  12759. if (keyboard)
  12760. return keyboard.keysLeft;
  12761. },
  12762. set: function (value) {
  12763. var keyboard = this.inputs.attached["keyboard"];
  12764. if (keyboard)
  12765. keyboard.keysLeft = value;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12771. get: function () {
  12772. var keyboard = this.inputs.attached["keyboard"];
  12773. if (keyboard)
  12774. return keyboard.keysRight;
  12775. },
  12776. set: function (value) {
  12777. var keyboard = this.inputs.attached["keyboard"];
  12778. if (keyboard)
  12779. keyboard.keysRight = value;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. // Controls
  12785. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12786. this.inputs.attachElement(element, noPreventDefault);
  12787. };
  12788. FreeCamera.prototype.detachControl = function (element) {
  12789. this.inputs.detachElement(element);
  12790. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12791. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12792. };
  12793. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12794. var globalPosition;
  12795. if (this.parent) {
  12796. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12797. }
  12798. else {
  12799. globalPosition = this.position;
  12800. }
  12801. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12802. this._collider.radius = this.ellipsoid;
  12803. //no need for clone, as long as gravity is not on.
  12804. var actualVelocity = velocity;
  12805. //add gravity to the velocity to prevent the dual-collision checking
  12806. if (this.applyGravity) {
  12807. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12808. actualVelocity = velocity.add(this.getScene().gravity);
  12809. }
  12810. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12811. };
  12812. FreeCamera.prototype._checkInputs = function () {
  12813. if (!this._localDirection) {
  12814. this._localDirection = BABYLON.Vector3.Zero();
  12815. this._transformedDirection = BABYLON.Vector3.Zero();
  12816. }
  12817. this.inputs.checkInputs();
  12818. _super.prototype._checkInputs.call(this);
  12819. };
  12820. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12821. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12822. };
  12823. FreeCamera.prototype._updatePosition = function () {
  12824. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12825. this._collideWithWorld(this.cameraDirection);
  12826. }
  12827. else {
  12828. this.position.addInPlace(this.cameraDirection);
  12829. }
  12830. };
  12831. FreeCamera.prototype.dispose = function () {
  12832. this.inputs.clear();
  12833. _super.prototype.dispose.call(this);
  12834. };
  12835. FreeCamera.prototype.getTypeName = function () {
  12836. return "FreeCamera";
  12837. };
  12838. __decorate([
  12839. BABYLON.serializeAsVector3()
  12840. ], FreeCamera.prototype, "ellipsoid", void 0);
  12841. __decorate([
  12842. BABYLON.serialize()
  12843. ], FreeCamera.prototype, "checkCollisions", void 0);
  12844. __decorate([
  12845. BABYLON.serialize()
  12846. ], FreeCamera.prototype, "applyGravity", void 0);
  12847. return FreeCamera;
  12848. })(BABYLON.TargetCamera);
  12849. BABYLON.FreeCamera = FreeCamera;
  12850. })(BABYLON || (BABYLON = {}));
  12851. var BABYLON;
  12852. (function (BABYLON) {
  12853. var FreeCameraInputsManager = (function (_super) {
  12854. __extends(FreeCameraInputsManager, _super);
  12855. function FreeCameraInputsManager(camera) {
  12856. _super.call(this, camera);
  12857. }
  12858. FreeCameraInputsManager.prototype.addKeyboard = function () {
  12859. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  12860. return this;
  12861. };
  12862. FreeCameraInputsManager.prototype.addMouse = function () {
  12863. this.add(new BABYLON.FreeCameraMouseInput());
  12864. return this;
  12865. };
  12866. FreeCameraInputsManager.prototype.addGamepad = function () {
  12867. this.add(new BABYLON.FreeCameraGamepadInput());
  12868. return this;
  12869. };
  12870. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  12871. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  12872. return this;
  12873. };
  12874. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  12875. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  12876. return this;
  12877. };
  12878. FreeCameraInputsManager.prototype.addTouch = function () {
  12879. this.add(new BABYLON.FreeCameraTouchInput());
  12880. return this;
  12881. };
  12882. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  12883. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  12884. return this;
  12885. };
  12886. return FreeCameraInputsManager;
  12887. })(BABYLON.CameraInputsManager);
  12888. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  12889. })(BABYLON || (BABYLON = {}));
  12890. var BABYLON;
  12891. (function (BABYLON) {
  12892. var FollowCamera = (function (_super) {
  12893. __extends(FollowCamera, _super);
  12894. function FollowCamera(name, position, scene, target) {
  12895. _super.call(this, name, position, scene);
  12896. this.radius = 12;
  12897. this.rotationOffset = 0;
  12898. this.heightOffset = 4;
  12899. this.cameraAcceleration = 0.05;
  12900. this.maxCameraSpeed = 20;
  12901. this.target = target;
  12902. }
  12903. FollowCamera.prototype.getRadians = function (degrees) {
  12904. return degrees * Math.PI / 180;
  12905. };
  12906. FollowCamera.prototype.follow = function (cameraTarget) {
  12907. if (!cameraTarget)
  12908. return;
  12909. var yRotation;
  12910. if (cameraTarget.rotationQuaternion) {
  12911. var rotMatrix = new BABYLON.Matrix();
  12912. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  12913. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  12914. }
  12915. else {
  12916. yRotation = cameraTarget.rotation.y;
  12917. }
  12918. var radians = this.getRadians(this.rotationOffset) + yRotation;
  12919. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  12920. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  12921. var dx = targetX - this.position.x;
  12922. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  12923. var dz = (targetZ) - this.position.z;
  12924. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  12925. var vy = dy * this.cameraAcceleration;
  12926. var vz = dz * this.cameraAcceleration * 2;
  12927. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  12928. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12929. }
  12930. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  12931. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12932. }
  12933. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  12934. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  12935. }
  12936. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  12937. this.setTarget(cameraTarget.position);
  12938. };
  12939. FollowCamera.prototype._checkInputs = function () {
  12940. _super.prototype._checkInputs.call(this);
  12941. this.follow(this.target);
  12942. };
  12943. FollowCamera.prototype.getTypeName = function () {
  12944. return "FollowCamera";
  12945. };
  12946. __decorate([
  12947. BABYLON.serialize()
  12948. ], FollowCamera.prototype, "radius", void 0);
  12949. __decorate([
  12950. BABYLON.serialize()
  12951. ], FollowCamera.prototype, "rotationOffset", void 0);
  12952. __decorate([
  12953. BABYLON.serialize()
  12954. ], FollowCamera.prototype, "heightOffset", void 0);
  12955. __decorate([
  12956. BABYLON.serialize()
  12957. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  12958. __decorate([
  12959. BABYLON.serialize()
  12960. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  12961. __decorate([
  12962. BABYLON.serializeAsMeshReference("lockedTargetId")
  12963. ], FollowCamera.prototype, "target", void 0);
  12964. return FollowCamera;
  12965. })(BABYLON.TargetCamera);
  12966. BABYLON.FollowCamera = FollowCamera;
  12967. var ArcFollowCamera = (function (_super) {
  12968. __extends(ArcFollowCamera, _super);
  12969. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  12970. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  12971. this.alpha = alpha;
  12972. this.beta = beta;
  12973. this.radius = radius;
  12974. this.target = target;
  12975. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  12976. this.follow();
  12977. }
  12978. ArcFollowCamera.prototype.follow = function () {
  12979. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  12980. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  12981. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  12982. this.position = this.target.position.add(this._cartesianCoordinates);
  12983. this.setTarget(this.target.position);
  12984. };
  12985. ArcFollowCamera.prototype._checkInputs = function () {
  12986. _super.prototype._checkInputs.call(this);
  12987. this.follow();
  12988. };
  12989. ArcFollowCamera.prototype.getTypeName = function () {
  12990. return "ArcFollowCamera";
  12991. };
  12992. return ArcFollowCamera;
  12993. })(BABYLON.TargetCamera);
  12994. BABYLON.ArcFollowCamera = ArcFollowCamera;
  12995. })(BABYLON || (BABYLON = {}));
  12996. var BABYLON;
  12997. (function (BABYLON) {
  12998. // We're mainly based on the logic defined into the FreeCamera code
  12999. var TouchCamera = (function (_super) {
  13000. __extends(TouchCamera, _super);
  13001. //-- end properties for backward compatibility for inputs
  13002. function TouchCamera(name, position, scene) {
  13003. _super.call(this, name, position, scene);
  13004. this.inputs.addTouch();
  13005. }
  13006. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13007. //-- Begin properties for backward compatibility for inputs
  13008. get: function () {
  13009. var touch = this.inputs.attached["touch"];
  13010. if (touch)
  13011. return touch.touchAngularSensibility;
  13012. },
  13013. set: function (value) {
  13014. var touch = this.inputs.attached["touch"];
  13015. if (touch)
  13016. touch.touchAngularSensibility = value;
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13022. get: function () {
  13023. var touch = this.inputs.attached["touch"];
  13024. if (touch)
  13025. return touch.touchMoveSensibility;
  13026. },
  13027. set: function (value) {
  13028. var touch = this.inputs.attached["touch"];
  13029. if (touch)
  13030. touch.touchMoveSensibility = value;
  13031. },
  13032. enumerable: true,
  13033. configurable: true
  13034. });
  13035. TouchCamera.prototype.getTypeName = function () {
  13036. return "TouchCamera";
  13037. };
  13038. return TouchCamera;
  13039. })(BABYLON.FreeCamera);
  13040. BABYLON.TouchCamera = TouchCamera;
  13041. })(BABYLON || (BABYLON = {}));
  13042. var BABYLON;
  13043. (function (BABYLON) {
  13044. var ArcRotateCamera = (function (_super) {
  13045. __extends(ArcRotateCamera, _super);
  13046. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13047. var _this = this;
  13048. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13049. this.inertialAlphaOffset = 0;
  13050. this.inertialBetaOffset = 0;
  13051. this.inertialRadiusOffset = 0;
  13052. this.lowerAlphaLimit = null;
  13053. this.upperAlphaLimit = null;
  13054. this.lowerBetaLimit = 0.01;
  13055. this.upperBetaLimit = Math.PI;
  13056. this.lowerRadiusLimit = null;
  13057. this.upperRadiusLimit = null;
  13058. this.inertialPanningX = 0;
  13059. this.inertialPanningY = 0;
  13060. //-- end properties for backward compatibility for inputs
  13061. this.zoomOnFactor = 1;
  13062. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13063. this.allowUpsideDown = true;
  13064. this._viewMatrix = new BABYLON.Matrix();
  13065. // Panning
  13066. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13067. this.checkCollisions = false;
  13068. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13069. this._collider = new BABYLON.Collider();
  13070. this._previousPosition = BABYLON.Vector3.Zero();
  13071. this._collisionVelocity = BABYLON.Vector3.Zero();
  13072. this._newPosition = BABYLON.Vector3.Zero();
  13073. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13074. if (collidedMesh === void 0) { collidedMesh = null; }
  13075. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13076. newPosition.multiplyInPlace(_this._collider.radius);
  13077. }
  13078. if (!collidedMesh) {
  13079. _this._previousPosition.copyFrom(_this.position);
  13080. }
  13081. else {
  13082. _this.setPosition(newPosition);
  13083. if (_this.onCollide) {
  13084. _this.onCollide(collidedMesh);
  13085. }
  13086. }
  13087. // Recompute because of constraints
  13088. var cosa = Math.cos(_this.alpha);
  13089. var sina = Math.sin(_this.alpha);
  13090. var cosb = Math.cos(_this.beta);
  13091. var sinb = Math.sin(_this.beta);
  13092. if (sinb === 0) {
  13093. sinb = 0.0001;
  13094. }
  13095. var target = _this._getTargetPosition();
  13096. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13097. _this.position.copyFrom(_this._newPosition);
  13098. var up = _this.upVector;
  13099. if (_this.allowUpsideDown && _this.beta < 0) {
  13100. up = up.clone();
  13101. up = up.negate();
  13102. }
  13103. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13104. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13105. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13106. _this._collisionTriggered = false;
  13107. };
  13108. if (!target) {
  13109. this.target = BABYLON.Vector3.Zero();
  13110. }
  13111. else {
  13112. this.target = target;
  13113. }
  13114. this.alpha = alpha;
  13115. this.beta = beta;
  13116. this.radius = radius;
  13117. this.getViewMatrix();
  13118. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13119. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13120. }
  13121. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13122. //-- begin properties for backward compatibility for inputs
  13123. get: function () {
  13124. var pointers = this.inputs.attached["pointers"];
  13125. if (pointers)
  13126. return pointers.angularSensibilityX;
  13127. },
  13128. set: function (value) {
  13129. var pointers = this.inputs.attached["pointers"];
  13130. if (pointers) {
  13131. pointers.angularSensibilityX = value;
  13132. }
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13138. get: function () {
  13139. var pointers = this.inputs.attached["pointers"];
  13140. if (pointers)
  13141. return pointers.angularSensibilityY;
  13142. },
  13143. set: function (value) {
  13144. var pointers = this.inputs.attached["pointers"];
  13145. if (pointers) {
  13146. pointers.angularSensibilityY = value;
  13147. }
  13148. },
  13149. enumerable: true,
  13150. configurable: true
  13151. });
  13152. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13153. get: function () {
  13154. var pointers = this.inputs.attached["pointers"];
  13155. if (pointers)
  13156. return pointers.pinchPrecision;
  13157. },
  13158. set: function (value) {
  13159. var pointers = this.inputs.attached["pointers"];
  13160. if (pointers) {
  13161. pointers.pinchPrecision = value;
  13162. }
  13163. },
  13164. enumerable: true,
  13165. configurable: true
  13166. });
  13167. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13168. get: function () {
  13169. var pointers = this.inputs.attached["pointers"];
  13170. if (pointers)
  13171. return pointers.panningSensibility;
  13172. },
  13173. set: function (value) {
  13174. var pointers = this.inputs.attached["pointers"];
  13175. if (pointers) {
  13176. pointers.panningSensibility = value;
  13177. }
  13178. },
  13179. enumerable: true,
  13180. configurable: true
  13181. });
  13182. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13183. get: function () {
  13184. var keyboard = this.inputs.attached["keyboard"];
  13185. if (keyboard)
  13186. return keyboard.keysUp;
  13187. },
  13188. set: function (value) {
  13189. var keyboard = this.inputs.attached["keyboard"];
  13190. if (keyboard)
  13191. keyboard.keysUp = value;
  13192. },
  13193. enumerable: true,
  13194. configurable: true
  13195. });
  13196. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13197. get: function () {
  13198. var keyboard = this.inputs.attached["keyboard"];
  13199. if (keyboard)
  13200. return keyboard.keysDown;
  13201. },
  13202. set: function (value) {
  13203. var keyboard = this.inputs.attached["keyboard"];
  13204. if (keyboard)
  13205. keyboard.keysDown = value;
  13206. },
  13207. enumerable: true,
  13208. configurable: true
  13209. });
  13210. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13211. get: function () {
  13212. var keyboard = this.inputs.attached["keyboard"];
  13213. if (keyboard)
  13214. return keyboard.keysLeft;
  13215. },
  13216. set: function (value) {
  13217. var keyboard = this.inputs.attached["keyboard"];
  13218. if (keyboard)
  13219. keyboard.keysLeft = value;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13225. get: function () {
  13226. var keyboard = this.inputs.attached["keyboard"];
  13227. if (keyboard)
  13228. return keyboard.keysRight;
  13229. },
  13230. set: function (value) {
  13231. var keyboard = this.inputs.attached["keyboard"];
  13232. if (keyboard)
  13233. keyboard.keysRight = value;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13239. get: function () {
  13240. var mousewheel = this.inputs.attached["mousewheel"];
  13241. if (mousewheel)
  13242. return mousewheel.wheelPrecision;
  13243. },
  13244. set: function (value) {
  13245. var mousewheel = this.inputs.attached["mousewheel"];
  13246. if (mousewheel)
  13247. mousewheel.wheelPrecision = value;
  13248. },
  13249. enumerable: true,
  13250. configurable: true
  13251. });
  13252. // Cache
  13253. ArcRotateCamera.prototype._initCache = function () {
  13254. _super.prototype._initCache.call(this);
  13255. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13256. this._cache.alpha = undefined;
  13257. this._cache.beta = undefined;
  13258. this._cache.radius = undefined;
  13259. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13260. };
  13261. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13262. if (!ignoreParentClass) {
  13263. _super.prototype._updateCache.call(this);
  13264. }
  13265. this._cache.target.copyFrom(this._getTargetPosition());
  13266. this._cache.alpha = this.alpha;
  13267. this._cache.beta = this.beta;
  13268. this._cache.radius = this.radius;
  13269. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13270. };
  13271. ArcRotateCamera.prototype._getTargetPosition = function () {
  13272. if (this.target.getAbsolutePosition) {
  13273. return this.target.getAbsolutePosition();
  13274. }
  13275. return this.target;
  13276. };
  13277. // Synchronized
  13278. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13279. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13280. return false;
  13281. return this._cache.target.equals(this.target)
  13282. && this._cache.alpha === this.alpha
  13283. && this._cache.beta === this.beta
  13284. && this._cache.radius === this.radius
  13285. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13286. };
  13287. // Methods
  13288. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13289. var _this = this;
  13290. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13291. this._useCtrlForPanning = useCtrlForPanning;
  13292. this.inputs.attachElement(element, noPreventDefault);
  13293. this._reset = function () {
  13294. _this.inertialAlphaOffset = 0;
  13295. _this.inertialBetaOffset = 0;
  13296. _this.inertialRadiusOffset = 0;
  13297. };
  13298. };
  13299. ArcRotateCamera.prototype.detachControl = function (element) {
  13300. this.inputs.detachElement(element);
  13301. if (this._reset) {
  13302. this._reset();
  13303. }
  13304. };
  13305. ArcRotateCamera.prototype._checkInputs = function () {
  13306. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13307. if (this._collisionTriggered) {
  13308. return;
  13309. }
  13310. this.inputs.checkInputs();
  13311. // Inertia
  13312. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13313. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13314. this.beta += this.inertialBetaOffset;
  13315. this.radius -= this.inertialRadiusOffset;
  13316. this.inertialAlphaOffset *= this.inertia;
  13317. this.inertialBetaOffset *= this.inertia;
  13318. this.inertialRadiusOffset *= this.inertia;
  13319. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13320. this.inertialAlphaOffset = 0;
  13321. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13322. this.inertialBetaOffset = 0;
  13323. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13324. this.inertialRadiusOffset = 0;
  13325. }
  13326. // Panning inertia
  13327. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13328. if (!this._localDirection) {
  13329. this._localDirection = BABYLON.Vector3.Zero();
  13330. this._transformedDirection = BABYLON.Vector3.Zero();
  13331. }
  13332. this.inertialPanningX *= this.inertia;
  13333. this.inertialPanningY *= this.inertia;
  13334. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13335. this.inertialPanningX = 0;
  13336. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13337. this.inertialPanningY = 0;
  13338. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13339. this._localDirection.multiplyInPlace(this.panningAxis);
  13340. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13341. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13342. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13343. if (!this.panningAxis.y) {
  13344. this._transformedDirection.y = 0;
  13345. }
  13346. this.target.addInPlace(this._transformedDirection);
  13347. }
  13348. // Limits
  13349. this._checkLimits();
  13350. _super.prototype._checkInputs.call(this);
  13351. };
  13352. ArcRotateCamera.prototype._checkLimits = function () {
  13353. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13354. if (this.allowUpsideDown && this.beta > Math.PI) {
  13355. this.beta = this.beta - (2 * Math.PI);
  13356. }
  13357. }
  13358. else {
  13359. if (this.beta < this.lowerBetaLimit) {
  13360. this.beta = this.lowerBetaLimit;
  13361. }
  13362. }
  13363. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13364. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13365. this.beta = this.beta + (2 * Math.PI);
  13366. }
  13367. }
  13368. else {
  13369. if (this.beta > this.upperBetaLimit) {
  13370. this.beta = this.upperBetaLimit;
  13371. }
  13372. }
  13373. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13374. this.alpha = this.lowerAlphaLimit;
  13375. }
  13376. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13377. this.alpha = this.upperAlphaLimit;
  13378. }
  13379. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13380. this.radius = this.lowerRadiusLimit;
  13381. }
  13382. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13383. this.radius = this.upperRadiusLimit;
  13384. }
  13385. };
  13386. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13387. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13388. this.radius = radiusv3.length();
  13389. // Alpha
  13390. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13391. if (radiusv3.z < 0) {
  13392. this.alpha = 2 * Math.PI - this.alpha;
  13393. }
  13394. // Beta
  13395. this.beta = Math.acos(radiusv3.y / this.radius);
  13396. this._checkLimits();
  13397. };
  13398. ArcRotateCamera.prototype.setPosition = function (position) {
  13399. if (this.position.equals(position)) {
  13400. return;
  13401. }
  13402. this.position = position;
  13403. this.rebuildAnglesAndRadius();
  13404. };
  13405. ArcRotateCamera.prototype.setTarget = function (target) {
  13406. if (this._getTargetPosition().equals(target)) {
  13407. return;
  13408. }
  13409. this.target = target;
  13410. this.rebuildAnglesAndRadius();
  13411. };
  13412. ArcRotateCamera.prototype._getViewMatrix = function () {
  13413. // Compute
  13414. var cosa = Math.cos(this.alpha);
  13415. var sina = Math.sin(this.alpha);
  13416. var cosb = Math.cos(this.beta);
  13417. var sinb = Math.sin(this.beta);
  13418. if (sinb === 0) {
  13419. sinb = 0.0001;
  13420. }
  13421. var target = this._getTargetPosition();
  13422. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13423. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13424. this._collider.radius = this.collisionRadius;
  13425. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13426. this._collisionTriggered = true;
  13427. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13428. }
  13429. else {
  13430. this.position.copyFrom(this._newPosition);
  13431. var up = this.upVector;
  13432. if (this.allowUpsideDown && this.beta < 0) {
  13433. up = up.clone();
  13434. up = up.negate();
  13435. }
  13436. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13437. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13438. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13439. }
  13440. return this._viewMatrix;
  13441. };
  13442. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13443. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13444. meshes = meshes || this.getScene().meshes;
  13445. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13446. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13447. this.radius = distance * this.zoomOnFactor;
  13448. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13449. };
  13450. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13451. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13452. var meshesOrMinMaxVector;
  13453. var distance;
  13454. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13455. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13456. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13457. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13458. }
  13459. else {
  13460. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13461. distance = meshesOrMinMaxVectorAndDistance.distance;
  13462. }
  13463. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13464. if (!doNotUpdateMaxZ) {
  13465. this.maxZ = distance * 2;
  13466. }
  13467. };
  13468. /**
  13469. * @override
  13470. * Override Camera.createRigCamera
  13471. */
  13472. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13473. switch (this.cameraRigMode) {
  13474. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13475. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13476. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13478. case BABYLON.Camera.RIG_MODE_VR:
  13479. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13480. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13481. rigCam._cameraRigParams = {};
  13482. return rigCam;
  13483. }
  13484. return null;
  13485. };
  13486. /**
  13487. * @override
  13488. * Override Camera._updateRigCameras
  13489. */
  13490. ArcRotateCamera.prototype._updateRigCameras = function () {
  13491. switch (this.cameraRigMode) {
  13492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13493. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13494. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13495. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13496. case BABYLON.Camera.RIG_MODE_VR:
  13497. var camLeft = this._rigCameras[0];
  13498. var camRight = this._rigCameras[1];
  13499. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13500. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13501. camLeft.beta = camRight.beta = this.beta;
  13502. camLeft.radius = camRight.radius = this.radius;
  13503. break;
  13504. }
  13505. _super.prototype._updateRigCameras.call(this);
  13506. };
  13507. ArcRotateCamera.prototype.dispose = function () {
  13508. this.inputs.clear();
  13509. _super.prototype.dispose.call(this);
  13510. };
  13511. ArcRotateCamera.prototype.getTypeName = function () {
  13512. return "ArcRotateCamera";
  13513. };
  13514. __decorate([
  13515. BABYLON.serialize()
  13516. ], ArcRotateCamera.prototype, "alpha", void 0);
  13517. __decorate([
  13518. BABYLON.serialize()
  13519. ], ArcRotateCamera.prototype, "beta", void 0);
  13520. __decorate([
  13521. BABYLON.serialize()
  13522. ], ArcRotateCamera.prototype, "radius", void 0);
  13523. __decorate([
  13524. BABYLON.serializeAsVector3()
  13525. ], ArcRotateCamera.prototype, "target", void 0);
  13526. __decorate([
  13527. BABYLON.serialize()
  13528. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13529. __decorate([
  13530. BABYLON.serialize()
  13531. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13532. __decorate([
  13533. BABYLON.serialize()
  13534. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13535. __decorate([
  13536. BABYLON.serialize()
  13537. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13538. __decorate([
  13539. BABYLON.serialize()
  13540. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13541. __decorate([
  13542. BABYLON.serialize()
  13543. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13544. __decorate([
  13545. BABYLON.serialize()
  13546. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13547. __decorate([
  13548. BABYLON.serialize()
  13549. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13550. __decorate([
  13551. BABYLON.serialize()
  13552. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13553. __decorate([
  13554. BABYLON.serialize()
  13555. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13556. __decorate([
  13557. BABYLON.serialize()
  13558. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13559. __decorate([
  13560. BABYLON.serialize()
  13561. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13562. __decorate([
  13563. BABYLON.serialize()
  13564. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13565. return ArcRotateCamera;
  13566. })(BABYLON.TargetCamera);
  13567. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13568. })(BABYLON || (BABYLON = {}));
  13569. var BABYLON;
  13570. (function (BABYLON) {
  13571. var ArcRotateCameraInputsManager = (function (_super) {
  13572. __extends(ArcRotateCameraInputsManager, _super);
  13573. function ArcRotateCameraInputsManager(camera) {
  13574. _super.call(this, camera);
  13575. }
  13576. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13577. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13578. return this;
  13579. };
  13580. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13581. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13582. return this;
  13583. };
  13584. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13585. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13586. return this;
  13587. };
  13588. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13589. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13590. return this;
  13591. };
  13592. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13593. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13594. return this;
  13595. };
  13596. return ArcRotateCameraInputsManager;
  13597. })(BABYLON.CameraInputsManager);
  13598. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13599. })(BABYLON || (BABYLON = {}));
  13600. var BABYLON;
  13601. (function (BABYLON) {
  13602. var RenderingManager = (function () {
  13603. function RenderingManager(scene) {
  13604. this._renderingGroups = new Array();
  13605. this._scene = scene;
  13606. }
  13607. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13608. if (this._scene._activeParticleSystems.length === 0) {
  13609. return;
  13610. }
  13611. // Particles
  13612. var activeCamera = this._scene.activeCamera;
  13613. var beforeParticlesDate = BABYLON.Tools.Now;
  13614. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13615. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13616. if (particleSystem.renderingGroupId !== index) {
  13617. continue;
  13618. }
  13619. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13620. continue;
  13621. }
  13622. this._clearDepthBuffer();
  13623. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13624. this._scene._activeParticles += particleSystem.render();
  13625. }
  13626. }
  13627. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13628. };
  13629. RenderingManager.prototype._renderSprites = function (index) {
  13630. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13631. return;
  13632. }
  13633. // Sprites
  13634. var activeCamera = this._scene.activeCamera;
  13635. var beforeSpritessDate = BABYLON.Tools.Now;
  13636. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13637. var spriteManager = this._scene.spriteManagers[id];
  13638. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13639. this._clearDepthBuffer();
  13640. spriteManager.render();
  13641. }
  13642. }
  13643. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13644. };
  13645. RenderingManager.prototype._clearDepthBuffer = function () {
  13646. if (this._depthBufferAlreadyCleaned) {
  13647. return;
  13648. }
  13649. this._scene.getEngine().clear(0, false, true);
  13650. this._depthBufferAlreadyCleaned = true;
  13651. };
  13652. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13653. if (this._currentRenderSprites) {
  13654. this._renderSprites(this._currentIndex);
  13655. }
  13656. if (this._currentRenderParticles) {
  13657. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13658. }
  13659. };
  13660. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13661. this._currentActiveMeshes = activeMeshes;
  13662. this._currentRenderParticles = renderParticles;
  13663. this._currentRenderSprites = renderSprites;
  13664. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13665. this._depthBufferAlreadyCleaned = index == 0;
  13666. var renderingGroup = this._renderingGroups[index];
  13667. var needToStepBack = false;
  13668. this._currentIndex = index;
  13669. if (renderingGroup) {
  13670. this._clearDepthBuffer();
  13671. if (!renderingGroup.onBeforeTransparentRendering) {
  13672. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13673. }
  13674. if (!renderingGroup.render(customRenderFunction)) {
  13675. this._renderingGroups.splice(index, 1);
  13676. needToStepBack = true;
  13677. this._renderSpritesAndParticles();
  13678. }
  13679. }
  13680. else {
  13681. this._renderSpritesAndParticles();
  13682. }
  13683. if (needToStepBack) {
  13684. index--;
  13685. }
  13686. }
  13687. };
  13688. RenderingManager.prototype.reset = function () {
  13689. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13690. if (renderingGroup) {
  13691. renderingGroup.prepare();
  13692. }
  13693. });
  13694. };
  13695. RenderingManager.prototype.dispatch = function (subMesh) {
  13696. var mesh = subMesh.getMesh();
  13697. var renderingGroupId = mesh.renderingGroupId || 0;
  13698. if (!this._renderingGroups[renderingGroupId]) {
  13699. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13700. }
  13701. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13702. };
  13703. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13704. return RenderingManager;
  13705. })();
  13706. BABYLON.RenderingManager = RenderingManager;
  13707. })(BABYLON || (BABYLON = {}));
  13708. var BABYLON;
  13709. (function (BABYLON) {
  13710. var RenderingGroup = (function () {
  13711. function RenderingGroup(index, scene) {
  13712. this.index = index;
  13713. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13714. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13715. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13716. this._scene = scene;
  13717. }
  13718. RenderingGroup.prototype.render = function (customRenderFunction) {
  13719. if (customRenderFunction) {
  13720. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13721. return true;
  13722. }
  13723. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13724. if (this.onBeforeTransparentRendering) {
  13725. this.onBeforeTransparentRendering();
  13726. }
  13727. return false;
  13728. }
  13729. var engine = this._scene.getEngine();
  13730. // Opaque
  13731. var subIndex;
  13732. var submesh;
  13733. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13734. submesh = this._opaqueSubMeshes.data[subIndex];
  13735. submesh.render(false);
  13736. }
  13737. // Alpha test
  13738. engine.setAlphaTesting(true);
  13739. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13740. submesh = this._alphaTestSubMeshes.data[subIndex];
  13741. submesh.render(false);
  13742. }
  13743. engine.setAlphaTesting(false);
  13744. if (this.onBeforeTransparentRendering) {
  13745. this.onBeforeTransparentRendering();
  13746. }
  13747. // Transparent
  13748. if (this._transparentSubMeshes.length) {
  13749. // Sorting
  13750. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13751. submesh = this._transparentSubMeshes.data[subIndex];
  13752. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13753. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13754. }
  13755. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13756. sortedArray.sort(function (a, b) {
  13757. // Alpha index first
  13758. if (a._alphaIndex > b._alphaIndex) {
  13759. return 1;
  13760. }
  13761. if (a._alphaIndex < b._alphaIndex) {
  13762. return -1;
  13763. }
  13764. // Then distance to camera
  13765. if (a._distanceToCamera < b._distanceToCamera) {
  13766. return 1;
  13767. }
  13768. if (a._distanceToCamera > b._distanceToCamera) {
  13769. return -1;
  13770. }
  13771. return 0;
  13772. });
  13773. // Rendering
  13774. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13775. submesh = sortedArray[subIndex];
  13776. submesh.render(true);
  13777. }
  13778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13779. }
  13780. return true;
  13781. };
  13782. RenderingGroup.prototype.prepare = function () {
  13783. this._opaqueSubMeshes.reset();
  13784. this._transparentSubMeshes.reset();
  13785. this._alphaTestSubMeshes.reset();
  13786. };
  13787. RenderingGroup.prototype.dispatch = function (subMesh) {
  13788. var material = subMesh.getMaterial();
  13789. var mesh = subMesh.getMesh();
  13790. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13791. this._transparentSubMeshes.push(subMesh);
  13792. }
  13793. else if (material.needAlphaTesting()) {
  13794. this._alphaTestSubMeshes.push(subMesh);
  13795. }
  13796. else {
  13797. this._opaqueSubMeshes.push(subMesh); // Opaque
  13798. }
  13799. };
  13800. return RenderingGroup;
  13801. })();
  13802. BABYLON.RenderingGroup = RenderingGroup;
  13803. })(BABYLON || (BABYLON = {}));
  13804. var BABYLON;
  13805. (function (BABYLON) {
  13806. /**
  13807. * Represents a scene to be rendered by the engine.
  13808. * @see http://doc.babylonjs.com/page.php?p=21911
  13809. */
  13810. var Scene = (function () {
  13811. /**
  13812. * @constructor
  13813. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13814. */
  13815. function Scene(engine) {
  13816. // Members
  13817. this.autoClear = true;
  13818. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13819. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13820. this.forceWireframe = false;
  13821. this.forcePointsCloud = false;
  13822. this.forceShowBoundingBoxes = false;
  13823. this.animationsEnabled = true;
  13824. this.constantlyUpdateMeshUnderPointer = false;
  13825. // Events
  13826. /**
  13827. * An event triggered when the scene is disposed.
  13828. * @type {BABYLON.Observable}
  13829. */
  13830. this.onDisposeObservable = new BABYLON.Observable();
  13831. /**
  13832. * An event triggered before rendering the scene
  13833. * @type {BABYLON.Observable}
  13834. */
  13835. this.onBeforeRenderObservable = new BABYLON.Observable();
  13836. /**
  13837. * An event triggered after rendering the scene
  13838. * @type {BABYLON.Observable}
  13839. */
  13840. this.onAfterRenderObservable = new BABYLON.Observable();
  13841. /**
  13842. * An event triggered when the scene is ready
  13843. * @type {BABYLON.Observable}
  13844. */
  13845. this.onReadyObservable = new BABYLON.Observable();
  13846. /**
  13847. * An event triggered before rendering a camera
  13848. * @type {BABYLON.Observable}
  13849. */
  13850. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  13851. /**
  13852. * An event triggered after rendering a camera
  13853. * @type {BABYLON.Observable}
  13854. */
  13855. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  13856. /**
  13857. * An event triggered when a camera is created
  13858. * @type {BABYLON.Observable}
  13859. */
  13860. this.onNewCameraAddedObservable = new BABYLON.Observable();
  13861. /**
  13862. * An event triggered when a camera is removed
  13863. * @type {BABYLON.Observable}
  13864. */
  13865. this.onCameraRemovedObservable = new BABYLON.Observable();
  13866. /**
  13867. * An event triggered when a light is created
  13868. * @type {BABYLON.Observable}
  13869. */
  13870. this.onNewLightAddedObservable = new BABYLON.Observable();
  13871. /**
  13872. * An event triggered when a light is removed
  13873. * @type {BABYLON.Observable}
  13874. */
  13875. this.onLightRemovedObservable = new BABYLON.Observable();
  13876. /**
  13877. * An event triggered when a geometry is created
  13878. * @type {BABYLON.Observable}
  13879. */
  13880. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  13881. /**
  13882. * An event triggered when a geometry is removed
  13883. * @type {BABYLON.Observable}
  13884. */
  13885. this.onGeometryRemovedObservable = new BABYLON.Observable();
  13886. /**
  13887. * An event triggered when a mesh is created
  13888. * @type {BABYLON.Observable}
  13889. */
  13890. this.onNewMeshAddedObservable = new BABYLON.Observable();
  13891. /**
  13892. * An event triggered when a mesh is removed
  13893. * @type {BABYLON.Observable}
  13894. */
  13895. this.onMeshRemovedObservable = new BABYLON.Observable();
  13896. // Animations
  13897. this.animations = [];
  13898. 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
  13899. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  13900. this._startingPointerTime = 0;
  13901. // Fog
  13902. /**
  13903. * is fog enabled on this scene.
  13904. * @type {boolean}
  13905. */
  13906. this.fogEnabled = true;
  13907. this.fogMode = Scene.FOGMODE_NONE;
  13908. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13909. this.fogDensity = 0.1;
  13910. this.fogStart = 0;
  13911. this.fogEnd = 1000.0;
  13912. // Lights
  13913. /**
  13914. * is shadow enabled on this scene.
  13915. * @type {boolean}
  13916. */
  13917. this.shadowsEnabled = true;
  13918. /**
  13919. * is light enabled on this scene.
  13920. * @type {boolean}
  13921. */
  13922. this.lightsEnabled = true;
  13923. /**
  13924. * All of the lights added to this scene.
  13925. * @see BABYLON.Light
  13926. * @type {BABYLON.Light[]}
  13927. */
  13928. this.lights = new Array();
  13929. // Cameras
  13930. /**
  13931. * All of the cameras added to this scene.
  13932. * @see BABYLON.Camera
  13933. * @type {BABYLON.Camera[]}
  13934. */
  13935. this.cameras = new Array();
  13936. this.activeCameras = new Array();
  13937. // Meshes
  13938. /**
  13939. * All of the (abstract) meshes added to this scene.
  13940. * @see BABYLON.AbstractMesh
  13941. * @type {BABYLON.AbstractMesh[]}
  13942. */
  13943. this.meshes = new Array();
  13944. // Geometries
  13945. this._geometries = new Array();
  13946. this.materials = new Array();
  13947. this.multiMaterials = new Array();
  13948. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  13949. // Textures
  13950. this.texturesEnabled = true;
  13951. this.textures = new Array();
  13952. // Particles
  13953. this.particlesEnabled = true;
  13954. this.particleSystems = new Array();
  13955. // Sprites
  13956. this.spritesEnabled = true;
  13957. this.spriteManagers = new Array();
  13958. // Layers
  13959. this.layers = new Array();
  13960. // Skeletons
  13961. this.skeletonsEnabled = true;
  13962. this.skeletons = new Array();
  13963. // Lens flares
  13964. this.lensFlaresEnabled = true;
  13965. this.lensFlareSystems = new Array();
  13966. // Collisions
  13967. this.collisionsEnabled = true;
  13968. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  13969. // Postprocesses
  13970. this.postProcessesEnabled = true;
  13971. // Customs render targets
  13972. this.renderTargetsEnabled = true;
  13973. this.dumpNextRenderTargets = false;
  13974. this.customRenderTargets = new Array();
  13975. // Imported meshes
  13976. this.importedMeshesFiles = new Array();
  13977. // Probes
  13978. this.probesEnabled = true;
  13979. this.reflectionProbes = new Array();
  13980. this._actionManagers = new Array();
  13981. this._meshesForIntersections = new BABYLON.SmartArray(256);
  13982. // Procedural textures
  13983. this.proceduralTexturesEnabled = true;
  13984. this._proceduralTextures = new Array();
  13985. this.soundTracks = new Array();
  13986. this._audioEnabled = true;
  13987. this._headphone = false;
  13988. this._totalVertices = 0;
  13989. this._activeIndices = 0;
  13990. this._activeParticles = 0;
  13991. this._lastFrameDuration = 0;
  13992. this._evaluateActiveMeshesDuration = 0;
  13993. this._renderTargetsDuration = 0;
  13994. this._particlesDuration = 0;
  13995. this._renderDuration = 0;
  13996. this._spritesDuration = 0;
  13997. this._animationRatio = 0;
  13998. this._renderId = 0;
  13999. this._executeWhenReadyTimeoutId = -1;
  14000. this._intermediateRendering = false;
  14001. this._toBeDisposed = new BABYLON.SmartArray(256);
  14002. this._pendingData = []; //ANY
  14003. this._activeMeshes = new BABYLON.SmartArray(256);
  14004. this._processedMaterials = new BABYLON.SmartArray(256);
  14005. this._renderTargets = new BABYLON.SmartArray(256);
  14006. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14007. this._activeSkeletons = new BABYLON.SmartArray(32);
  14008. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14009. this._activeBones = 0;
  14010. this._activeAnimatables = new Array();
  14011. this._transformMatrix = BABYLON.Matrix.Zero();
  14012. this._edgesRenderers = new BABYLON.SmartArray(16);
  14013. this._uniqueIdCounter = 0;
  14014. this._engine = engine;
  14015. engine.scenes.push(this);
  14016. this._renderingManager = new BABYLON.RenderingManager(this);
  14017. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14018. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14019. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14020. if (BABYLON.OutlineRenderer) {
  14021. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14022. }
  14023. this.attachControl();
  14024. this._debugLayer = new BABYLON.DebugLayer(this);
  14025. if (BABYLON.SoundTrack) {
  14026. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14027. }
  14028. //simplification queue
  14029. if (BABYLON.SimplificationQueue) {
  14030. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14031. }
  14032. //collision coordinator initialization. For now legacy per default.
  14033. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14034. }
  14035. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14036. get: function () {
  14037. return Scene._FOGMODE_NONE;
  14038. },
  14039. enumerable: true,
  14040. configurable: true
  14041. });
  14042. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14043. get: function () {
  14044. return Scene._FOGMODE_EXP;
  14045. },
  14046. enumerable: true,
  14047. configurable: true
  14048. });
  14049. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14050. get: function () {
  14051. return Scene._FOGMODE_EXP2;
  14052. },
  14053. enumerable: true,
  14054. configurable: true
  14055. });
  14056. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14057. get: function () {
  14058. return Scene._FOGMODE_LINEAR;
  14059. },
  14060. enumerable: true,
  14061. configurable: true
  14062. });
  14063. Object.defineProperty(Scene.prototype, "onDispose", {
  14064. set: function (callback) {
  14065. if (this._onDisposeObserver) {
  14066. this.onDisposeObservable.remove(this._onDisposeObserver);
  14067. }
  14068. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Object.defineProperty(Scene.prototype, "beforeRender", {
  14074. set: function (callback) {
  14075. if (this._onBeforeRenderObserver) {
  14076. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14077. }
  14078. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14079. },
  14080. enumerable: true,
  14081. configurable: true
  14082. });
  14083. Object.defineProperty(Scene.prototype, "afterRender", {
  14084. set: function (callback) {
  14085. if (this._onAfterRenderObserver) {
  14086. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14087. }
  14088. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14089. },
  14090. enumerable: true,
  14091. configurable: true
  14092. });
  14093. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14094. set: function (callback) {
  14095. if (this._onBeforeCameraRenderObserver) {
  14096. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14097. }
  14098. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14099. },
  14100. enumerable: true,
  14101. configurable: true
  14102. });
  14103. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14104. set: function (callback) {
  14105. if (this._onAfterCameraRenderObserver) {
  14106. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14107. }
  14108. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14109. },
  14110. enumerable: true,
  14111. configurable: true
  14112. });
  14113. Object.defineProperty(Scene.prototype, "debugLayer", {
  14114. // Properties
  14115. get: function () {
  14116. return this._debugLayer;
  14117. },
  14118. enumerable: true,
  14119. configurable: true
  14120. });
  14121. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14122. get: function () {
  14123. return this._workerCollisions;
  14124. },
  14125. set: function (enabled) {
  14126. enabled = (enabled && !!Worker);
  14127. this._workerCollisions = enabled;
  14128. if (this.collisionCoordinator) {
  14129. this.collisionCoordinator.destroy();
  14130. }
  14131. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14132. this.collisionCoordinator.init(this);
  14133. },
  14134. enumerable: true,
  14135. configurable: true
  14136. });
  14137. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14138. get: function () {
  14139. return this._selectionOctree;
  14140. },
  14141. enumerable: true,
  14142. configurable: true
  14143. });
  14144. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14145. /**
  14146. * The mesh that is currently under the pointer.
  14147. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14148. */
  14149. get: function () {
  14150. return this._pointerOverMesh;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(Scene.prototype, "pointerX", {
  14156. /**
  14157. * Current on-screen X position of the pointer
  14158. * @return {number} X position of the pointer
  14159. */
  14160. get: function () {
  14161. return this._pointerX;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Scene.prototype, "pointerY", {
  14167. /**
  14168. * Current on-screen Y position of the pointer
  14169. * @return {number} Y position of the pointer
  14170. */
  14171. get: function () {
  14172. return this._pointerY;
  14173. },
  14174. enumerable: true,
  14175. configurable: true
  14176. });
  14177. Scene.prototype.getCachedMaterial = function () {
  14178. return this._cachedMaterial;
  14179. };
  14180. Scene.prototype.getBoundingBoxRenderer = function () {
  14181. return this._boundingBoxRenderer;
  14182. };
  14183. Scene.prototype.getOutlineRenderer = function () {
  14184. return this._outlineRenderer;
  14185. };
  14186. Scene.prototype.getEngine = function () {
  14187. return this._engine;
  14188. };
  14189. Scene.prototype.getTotalVertices = function () {
  14190. return this._totalVertices;
  14191. };
  14192. Scene.prototype.getActiveIndices = function () {
  14193. return this._activeIndices;
  14194. };
  14195. Scene.prototype.getActiveParticles = function () {
  14196. return this._activeParticles;
  14197. };
  14198. Scene.prototype.getActiveBones = function () {
  14199. return this._activeBones;
  14200. };
  14201. // Stats
  14202. Scene.prototype.getLastFrameDuration = function () {
  14203. return this._lastFrameDuration;
  14204. };
  14205. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14206. return this._evaluateActiveMeshesDuration;
  14207. };
  14208. Scene.prototype.getActiveMeshes = function () {
  14209. return this._activeMeshes;
  14210. };
  14211. Scene.prototype.getRenderTargetsDuration = function () {
  14212. return this._renderTargetsDuration;
  14213. };
  14214. Scene.prototype.getRenderDuration = function () {
  14215. return this._renderDuration;
  14216. };
  14217. Scene.prototype.getParticlesDuration = function () {
  14218. return this._particlesDuration;
  14219. };
  14220. Scene.prototype.getSpritesDuration = function () {
  14221. return this._spritesDuration;
  14222. };
  14223. Scene.prototype.getAnimationRatio = function () {
  14224. return this._animationRatio;
  14225. };
  14226. Scene.prototype.getRenderId = function () {
  14227. return this._renderId;
  14228. };
  14229. Scene.prototype.incrementRenderId = function () {
  14230. this._renderId++;
  14231. };
  14232. Scene.prototype._updatePointerPosition = function (evt) {
  14233. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14234. this._pointerX = evt.clientX - canvasRect.left;
  14235. this._pointerY = evt.clientY - canvasRect.top;
  14236. this._unTranslatedPointerX = this._pointerX;
  14237. this._unTranslatedPointerY = this._pointerY;
  14238. if (this.cameraToUseForPointers) {
  14239. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14240. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14241. }
  14242. };
  14243. // Pointers handling
  14244. Scene.prototype.attachControl = function () {
  14245. var _this = this;
  14246. var spritePredicate = function (sprite) {
  14247. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14248. };
  14249. this._onPointerMove = function (evt) {
  14250. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14251. return;
  14252. }
  14253. var canvas = _this._engine.getRenderingCanvas();
  14254. _this._updatePointerPosition(evt);
  14255. if (!_this.pointerMovePredicate) {
  14256. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14257. }
  14258. // Meshes
  14259. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14260. if (pickResult.hit && pickResult.pickedMesh) {
  14261. _this.setPointerOverSprite(null);
  14262. _this.setPointerOverMesh(pickResult.pickedMesh);
  14263. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14264. canvas.style.cursor = "pointer";
  14265. }
  14266. else {
  14267. canvas.style.cursor = "";
  14268. }
  14269. }
  14270. else {
  14271. _this.setPointerOverMesh(null);
  14272. // Sprites
  14273. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14274. if (pickResult.hit && pickResult.pickedSprite) {
  14275. canvas.style.cursor = "pointer";
  14276. _this.setPointerOverSprite(pickResult.pickedSprite);
  14277. }
  14278. else {
  14279. _this.setPointerOverSprite(null);
  14280. // Restore pointer
  14281. canvas.style.cursor = "";
  14282. }
  14283. }
  14284. if (_this.onPointerMove) {
  14285. _this.onPointerMove(evt, pickResult);
  14286. }
  14287. };
  14288. this._onPointerDown = function (evt) {
  14289. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14290. return;
  14291. }
  14292. _this._updatePointerPosition(evt);
  14293. _this._startingPointerPosition.x = _this._pointerX;
  14294. _this._startingPointerPosition.y = _this._pointerY;
  14295. _this._startingPointerTime = new Date().getTime();
  14296. if (!_this.pointerDownPredicate) {
  14297. _this.pointerDownPredicate = function (mesh) {
  14298. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14299. };
  14300. }
  14301. // Meshes
  14302. _this._pickedDownMesh = null;
  14303. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14304. if (pickResult.hit && pickResult.pickedMesh) {
  14305. if (pickResult.pickedMesh.actionManager) {
  14306. _this._pickedDownMesh = pickResult.pickedMesh;
  14307. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14308. switch (evt.button) {
  14309. case 0:
  14310. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14311. break;
  14312. case 1:
  14313. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14314. break;
  14315. case 2:
  14316. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14317. break;
  14318. }
  14319. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14320. }
  14321. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14322. var that = _this;
  14323. window.setTimeout(function () {
  14324. 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);
  14325. if (pickResult.hit && pickResult.pickedMesh) {
  14326. if (pickResult.pickedMesh.actionManager) {
  14327. 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)) {
  14328. that._startingPointerTime = 0;
  14329. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14330. }
  14331. }
  14332. }
  14333. }, BABYLON.ActionManager.LongPressDelay);
  14334. }
  14335. }
  14336. }
  14337. if (_this.onPointerDown) {
  14338. _this.onPointerDown(evt, pickResult);
  14339. }
  14340. // Sprites
  14341. _this._pickedDownSprite = null;
  14342. if (_this.spriteManagers.length > 0) {
  14343. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14344. if (pickResult.hit && pickResult.pickedSprite) {
  14345. if (pickResult.pickedSprite.actionManager) {
  14346. _this._pickedDownSprite = pickResult.pickedSprite;
  14347. switch (evt.button) {
  14348. case 0:
  14349. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14350. break;
  14351. case 1:
  14352. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14353. break;
  14354. case 2:
  14355. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14356. break;
  14357. }
  14358. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14359. }
  14360. }
  14361. }
  14362. };
  14363. this._onPointerUp = function (evt) {
  14364. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14365. return;
  14366. }
  14367. _this._updatePointerPosition(evt);
  14368. if (!_this.pointerUpPredicate) {
  14369. _this.pointerUpPredicate = function (mesh) {
  14370. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14371. };
  14372. }
  14373. // Meshes
  14374. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14375. if (pickResult.hit && pickResult.pickedMesh) {
  14376. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14377. _this.onPointerPick(evt, pickResult);
  14378. }
  14379. if (pickResult.pickedMesh.actionManager) {
  14380. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14381. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14382. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14383. }
  14384. }
  14385. }
  14386. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14387. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14388. }
  14389. if (_this.onPointerUp) {
  14390. _this.onPointerUp(evt, pickResult);
  14391. }
  14392. _this._startingPointerTime = 0;
  14393. // Sprites
  14394. if (_this.spriteManagers.length > 0) {
  14395. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14396. if (pickResult.hit && pickResult.pickedSprite) {
  14397. if (pickResult.pickedSprite.actionManager) {
  14398. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14399. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14400. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14401. }
  14402. }
  14403. }
  14404. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14405. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14406. }
  14407. }
  14408. };
  14409. this._onKeyDown = function (evt) {
  14410. if (_this.actionManager) {
  14411. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14412. }
  14413. };
  14414. this._onKeyUp = function (evt) {
  14415. if (_this.actionManager) {
  14416. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14417. }
  14418. };
  14419. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14420. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14421. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14422. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14423. // Wheel
  14424. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14425. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14426. BABYLON.Tools.RegisterTopRootEvents([
  14427. { name: "keydown", handler: this._onKeyDown },
  14428. { name: "keyup", handler: this._onKeyUp }
  14429. ]);
  14430. };
  14431. Scene.prototype.detachControl = function () {
  14432. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14433. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14434. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14435. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14436. // Wheel
  14437. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14438. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14439. BABYLON.Tools.UnregisterTopRootEvents([
  14440. { name: "keydown", handler: this._onKeyDown },
  14441. { name: "keyup", handler: this._onKeyUp }
  14442. ]);
  14443. };
  14444. // Ready
  14445. Scene.prototype.isReady = function () {
  14446. if (this._pendingData.length > 0) {
  14447. return false;
  14448. }
  14449. var index;
  14450. for (index = 0; index < this._geometries.length; index++) {
  14451. var geometry = this._geometries[index];
  14452. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14453. return false;
  14454. }
  14455. }
  14456. for (index = 0; index < this.meshes.length; index++) {
  14457. var mesh = this.meshes[index];
  14458. if (!mesh.isReady()) {
  14459. return false;
  14460. }
  14461. var mat = mesh.material;
  14462. if (mat) {
  14463. if (!mat.isReady(mesh)) {
  14464. return false;
  14465. }
  14466. }
  14467. }
  14468. return true;
  14469. };
  14470. Scene.prototype.resetCachedMaterial = function () {
  14471. this._cachedMaterial = null;
  14472. };
  14473. Scene.prototype.registerBeforeRender = function (func) {
  14474. this.onBeforeRenderObservable.add(func);
  14475. };
  14476. Scene.prototype.unregisterBeforeRender = function (func) {
  14477. this.onBeforeRenderObservable.removeCallback(func);
  14478. };
  14479. Scene.prototype.registerAfterRender = function (func) {
  14480. this.onAfterRenderObservable.add(func);
  14481. };
  14482. Scene.prototype.unregisterAfterRender = function (func) {
  14483. this.onAfterRenderObservable.removeCallback(func);
  14484. };
  14485. Scene.prototype._addPendingData = function (data) {
  14486. this._pendingData.push(data);
  14487. };
  14488. Scene.prototype._removePendingData = function (data) {
  14489. var index = this._pendingData.indexOf(data);
  14490. if (index !== -1) {
  14491. this._pendingData.splice(index, 1);
  14492. }
  14493. };
  14494. Scene.prototype.getWaitingItemsCount = function () {
  14495. return this._pendingData.length;
  14496. };
  14497. /**
  14498. * Registers a function to be executed when the scene is ready.
  14499. * @param {Function} func - the function to be executed.
  14500. */
  14501. Scene.prototype.executeWhenReady = function (func) {
  14502. var _this = this;
  14503. this.onReadyObservable.add(func);
  14504. if (this._executeWhenReadyTimeoutId !== -1) {
  14505. return;
  14506. }
  14507. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14508. _this._checkIsReady();
  14509. }, 150);
  14510. };
  14511. Scene.prototype._checkIsReady = function () {
  14512. var _this = this;
  14513. if (this.isReady()) {
  14514. this.onReadyObservable.notifyObservers(this);
  14515. this.onReadyObservable.clear();
  14516. this._executeWhenReadyTimeoutId = -1;
  14517. return;
  14518. }
  14519. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14520. _this._checkIsReady();
  14521. }, 150);
  14522. };
  14523. // Animations
  14524. /**
  14525. * Will start the animation sequence of a given target
  14526. * @param target - the target
  14527. * @param {number} from - from which frame should animation start
  14528. * @param {number} to - till which frame should animation run.
  14529. * @param {boolean} [loop] - should the animation loop
  14530. * @param {number} [speedRatio] - the speed in which to run the animation
  14531. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14532. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14533. * @return {BABYLON.Animatable} the animatable object created for this animation
  14534. * @see BABYLON.Animatable
  14535. * @see http://doc.babylonjs.com/page.php?p=22081
  14536. */
  14537. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14538. if (speedRatio === void 0) { speedRatio = 1.0; }
  14539. this.stopAnimation(target);
  14540. if (!animatable) {
  14541. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14542. }
  14543. // Local animations
  14544. if (target.animations) {
  14545. animatable.appendAnimations(target, target.animations);
  14546. }
  14547. // Children animations
  14548. if (target.getAnimatables) {
  14549. var animatables = target.getAnimatables();
  14550. for (var index = 0; index < animatables.length; index++) {
  14551. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14552. }
  14553. }
  14554. animatable.reset();
  14555. return animatable;
  14556. };
  14557. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14558. if (speedRatio === undefined) {
  14559. speedRatio = 1.0;
  14560. }
  14561. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14562. return animatable;
  14563. };
  14564. Scene.prototype.getAnimatableByTarget = function (target) {
  14565. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14566. if (this._activeAnimatables[index].target === target) {
  14567. return this._activeAnimatables[index];
  14568. }
  14569. }
  14570. return null;
  14571. };
  14572. Object.defineProperty(Scene.prototype, "Animatables", {
  14573. get: function () {
  14574. return this._activeAnimatables;
  14575. },
  14576. enumerable: true,
  14577. configurable: true
  14578. });
  14579. /**
  14580. * Will stop the animation of the given target
  14581. * @param target - the target
  14582. * @see beginAnimation
  14583. */
  14584. Scene.prototype.stopAnimation = function (target) {
  14585. var animatable = this.getAnimatableByTarget(target);
  14586. if (animatable) {
  14587. animatable.stop();
  14588. }
  14589. };
  14590. Scene.prototype._animate = function () {
  14591. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14592. return;
  14593. }
  14594. if (!this._animationStartDate) {
  14595. if (this._pendingData.length > 0) {
  14596. return;
  14597. }
  14598. this._animationStartDate = BABYLON.Tools.Now;
  14599. }
  14600. // Getting time
  14601. var now = BABYLON.Tools.Now;
  14602. var delay = now - this._animationStartDate;
  14603. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14604. this._activeAnimatables[index]._animate(delay);
  14605. }
  14606. };
  14607. // Matrix
  14608. Scene.prototype.getViewMatrix = function () {
  14609. return this._viewMatrix;
  14610. };
  14611. Scene.prototype.getProjectionMatrix = function () {
  14612. return this._projectionMatrix;
  14613. };
  14614. Scene.prototype.getTransformMatrix = function () {
  14615. return this._transformMatrix;
  14616. };
  14617. Scene.prototype.setTransformMatrix = function (view, projection) {
  14618. this._viewMatrix = view;
  14619. this._projectionMatrix = projection;
  14620. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14621. };
  14622. // Methods
  14623. Scene.prototype.addMesh = function (newMesh) {
  14624. newMesh.uniqueId = this._uniqueIdCounter++;
  14625. var position = this.meshes.push(newMesh);
  14626. //notify the collision coordinator
  14627. this.collisionCoordinator.onMeshAdded(newMesh);
  14628. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14629. };
  14630. Scene.prototype.removeMesh = function (toRemove) {
  14631. var index = this.meshes.indexOf(toRemove);
  14632. if (index !== -1) {
  14633. // Remove from the scene if mesh found
  14634. this.meshes.splice(index, 1);
  14635. }
  14636. //notify the collision coordinator
  14637. this.collisionCoordinator.onMeshRemoved(toRemove);
  14638. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14639. return index;
  14640. };
  14641. Scene.prototype.removeSkeleton = function (toRemove) {
  14642. var index = this.skeletons.indexOf(toRemove);
  14643. if (index !== -1) {
  14644. // Remove from the scene if mesh found
  14645. this.skeletons.splice(index, 1);
  14646. }
  14647. return index;
  14648. };
  14649. Scene.prototype.removeLight = function (toRemove) {
  14650. var index = this.lights.indexOf(toRemove);
  14651. if (index !== -1) {
  14652. // Remove from the scene if mesh found
  14653. this.lights.splice(index, 1);
  14654. }
  14655. this.onLightRemovedObservable.notifyObservers(toRemove);
  14656. return index;
  14657. };
  14658. Scene.prototype.removeCamera = function (toRemove) {
  14659. var index = this.cameras.indexOf(toRemove);
  14660. if (index !== -1) {
  14661. // Remove from the scene if mesh found
  14662. this.cameras.splice(index, 1);
  14663. }
  14664. // Remove from activeCameras
  14665. var index2 = this.activeCameras.indexOf(toRemove);
  14666. if (index2 !== -1) {
  14667. // Remove from the scene if mesh found
  14668. this.activeCameras.splice(index2, 1);
  14669. }
  14670. // Reset the activeCamera
  14671. if (this.activeCamera === toRemove) {
  14672. if (this.cameras.length > 0) {
  14673. this.activeCamera = this.cameras[0];
  14674. }
  14675. else {
  14676. this.activeCamera = null;
  14677. }
  14678. }
  14679. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14680. return index;
  14681. };
  14682. Scene.prototype.addLight = function (newLight) {
  14683. newLight.uniqueId = this._uniqueIdCounter++;
  14684. var position = this.lights.push(newLight);
  14685. this.onNewLightAddedObservable.notifyObservers(newLight);
  14686. };
  14687. Scene.prototype.addCamera = function (newCamera) {
  14688. newCamera.uniqueId = this._uniqueIdCounter++;
  14689. var position = this.cameras.push(newCamera);
  14690. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  14691. };
  14692. /**
  14693. * Switch active camera
  14694. * @param {Camera} newCamera - new active camera
  14695. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14696. */
  14697. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14698. if (attachControl === void 0) { attachControl = true; }
  14699. var canvas = this._engine.getRenderingCanvas();
  14700. this.activeCamera.detachControl(canvas);
  14701. this.activeCamera = newCamera;
  14702. if (attachControl) {
  14703. newCamera.attachControl(canvas);
  14704. }
  14705. };
  14706. /**
  14707. * sets the active camera of the scene using its ID
  14708. * @param {string} id - the camera's ID
  14709. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14710. * @see activeCamera
  14711. */
  14712. Scene.prototype.setActiveCameraByID = function (id) {
  14713. var camera = this.getCameraByID(id);
  14714. if (camera) {
  14715. this.activeCamera = camera;
  14716. return camera;
  14717. }
  14718. return null;
  14719. };
  14720. /**
  14721. * sets the active camera of the scene using its name
  14722. * @param {string} name - the camera's name
  14723. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14724. * @see activeCamera
  14725. */
  14726. Scene.prototype.setActiveCameraByName = function (name) {
  14727. var camera = this.getCameraByName(name);
  14728. if (camera) {
  14729. this.activeCamera = camera;
  14730. return camera;
  14731. }
  14732. return null;
  14733. };
  14734. /**
  14735. * get a material using its id
  14736. * @param {string} the material's ID
  14737. * @return {BABYLON.Material|null} the material or null if none found.
  14738. */
  14739. Scene.prototype.getMaterialByID = function (id) {
  14740. for (var index = 0; index < this.materials.length; index++) {
  14741. if (this.materials[index].id === id) {
  14742. return this.materials[index];
  14743. }
  14744. }
  14745. return null;
  14746. };
  14747. /**
  14748. * get a material using its name
  14749. * @param {string} the material's name
  14750. * @return {BABYLON.Material|null} the material or null if none found.
  14751. */
  14752. Scene.prototype.getMaterialByName = function (name) {
  14753. for (var index = 0; index < this.materials.length; index++) {
  14754. if (this.materials[index].name === name) {
  14755. return this.materials[index];
  14756. }
  14757. }
  14758. return null;
  14759. };
  14760. Scene.prototype.getLensFlareSystemByName = function (name) {
  14761. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14762. if (this.lensFlareSystems[index].name === name) {
  14763. return this.lensFlareSystems[index];
  14764. }
  14765. }
  14766. return null;
  14767. };
  14768. Scene.prototype.getCameraByID = function (id) {
  14769. for (var index = 0; index < this.cameras.length; index++) {
  14770. if (this.cameras[index].id === id) {
  14771. return this.cameras[index];
  14772. }
  14773. }
  14774. return null;
  14775. };
  14776. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14777. for (var index = 0; index < this.cameras.length; index++) {
  14778. if (this.cameras[index].uniqueId === uniqueId) {
  14779. return this.cameras[index];
  14780. }
  14781. }
  14782. return null;
  14783. };
  14784. /**
  14785. * get a camera using its name
  14786. * @param {string} the camera's name
  14787. * @return {BABYLON.Camera|null} the camera or null if none found.
  14788. */
  14789. Scene.prototype.getCameraByName = function (name) {
  14790. for (var index = 0; index < this.cameras.length; index++) {
  14791. if (this.cameras[index].name === name) {
  14792. return this.cameras[index];
  14793. }
  14794. }
  14795. return null;
  14796. };
  14797. /**
  14798. * get a bone using its id
  14799. * @param {string} the bone's id
  14800. * @return {BABYLON.Bone|null} the bone or null if not found
  14801. */
  14802. Scene.prototype.getBoneByID = function (id) {
  14803. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14804. var skeleton = this.skeletons[skeletonIndex];
  14805. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14806. if (skeleton.bones[boneIndex].id === id) {
  14807. return skeleton.bones[boneIndex];
  14808. }
  14809. }
  14810. }
  14811. return null;
  14812. };
  14813. /**
  14814. * get a bone using its id
  14815. * @param {string} the bone's name
  14816. * @return {BABYLON.Bone|null} the bone or null if not found
  14817. */
  14818. Scene.prototype.getBoneByName = function (name) {
  14819. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  14820. var skeleton = this.skeletons[skeletonIndex];
  14821. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  14822. if (skeleton.bones[boneIndex].name === name) {
  14823. return skeleton.bones[boneIndex];
  14824. }
  14825. }
  14826. }
  14827. return null;
  14828. };
  14829. /**
  14830. * get a light node using its name
  14831. * @param {string} the light's name
  14832. * @return {BABYLON.Light|null} the light or null if none found.
  14833. */
  14834. Scene.prototype.getLightByName = function (name) {
  14835. for (var index = 0; index < this.lights.length; index++) {
  14836. if (this.lights[index].name === name) {
  14837. return this.lights[index];
  14838. }
  14839. }
  14840. return null;
  14841. };
  14842. /**
  14843. * get a light node using its ID
  14844. * @param {string} the light's id
  14845. * @return {BABYLON.Light|null} the light or null if none found.
  14846. */
  14847. Scene.prototype.getLightByID = function (id) {
  14848. for (var index = 0; index < this.lights.length; index++) {
  14849. if (this.lights[index].id === id) {
  14850. return this.lights[index];
  14851. }
  14852. }
  14853. return null;
  14854. };
  14855. /**
  14856. * get a light node using its scene-generated unique ID
  14857. * @param {number} the light's unique id
  14858. * @return {BABYLON.Light|null} the light or null if none found.
  14859. */
  14860. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  14861. for (var index = 0; index < this.lights.length; index++) {
  14862. if (this.lights[index].uniqueId === uniqueId) {
  14863. return this.lights[index];
  14864. }
  14865. }
  14866. return null;
  14867. };
  14868. /**
  14869. * get a particle system by id
  14870. * @param id {number} the particle system id
  14871. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  14872. */
  14873. Scene.prototype.getParticleSystemByID = function (id) {
  14874. for (var index = 0; index < this.particleSystems.length; index++) {
  14875. if (this.particleSystems[index].id === id) {
  14876. return this.particleSystems[index];
  14877. }
  14878. }
  14879. return null;
  14880. };
  14881. /**
  14882. * get a geometry using its ID
  14883. * @param {string} the geometry's id
  14884. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  14885. */
  14886. Scene.prototype.getGeometryByID = function (id) {
  14887. for (var index = 0; index < this._geometries.length; index++) {
  14888. if (this._geometries[index].id === id) {
  14889. return this._geometries[index];
  14890. }
  14891. }
  14892. return null;
  14893. };
  14894. /**
  14895. * add a new geometry to this scene.
  14896. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  14897. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  14898. * @return {boolean} was the geometry added or not
  14899. */
  14900. Scene.prototype.pushGeometry = function (geometry, force) {
  14901. if (!force && this.getGeometryByID(geometry.id)) {
  14902. return false;
  14903. }
  14904. this._geometries.push(geometry);
  14905. //notify the collision coordinator
  14906. this.collisionCoordinator.onGeometryAdded(geometry);
  14907. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  14908. return true;
  14909. };
  14910. /**
  14911. * Removes an existing geometry
  14912. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  14913. * @return {boolean} was the geometry removed or not
  14914. */
  14915. Scene.prototype.removeGeometry = function (geometry) {
  14916. var index = this._geometries.indexOf(geometry);
  14917. if (index > -1) {
  14918. this._geometries.splice(index, 1);
  14919. //notify the collision coordinator
  14920. this.collisionCoordinator.onGeometryDeleted(geometry);
  14921. this.onGeometryRemovedObservable.notifyObservers(geometry);
  14922. return true;
  14923. }
  14924. return false;
  14925. };
  14926. Scene.prototype.getGeometries = function () {
  14927. return this._geometries;
  14928. };
  14929. /**
  14930. * Get the first added mesh found of a given ID
  14931. * @param {string} id - the id to search for
  14932. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14933. */
  14934. Scene.prototype.getMeshByID = function (id) {
  14935. for (var index = 0; index < this.meshes.length; index++) {
  14936. if (this.meshes[index].id === id) {
  14937. return this.meshes[index];
  14938. }
  14939. }
  14940. return null;
  14941. };
  14942. /**
  14943. * Get a mesh with its auto-generated unique id
  14944. * @param {number} uniqueId - the unique id to search for
  14945. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14946. */
  14947. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  14948. for (var index = 0; index < this.meshes.length; index++) {
  14949. if (this.meshes[index].uniqueId === uniqueId) {
  14950. return this.meshes[index];
  14951. }
  14952. }
  14953. return null;
  14954. };
  14955. /**
  14956. * Get a the last added mesh found of a given ID
  14957. * @param {string} id - the id to search for
  14958. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  14959. */
  14960. Scene.prototype.getLastMeshByID = function (id) {
  14961. for (var index = this.meshes.length - 1; index >= 0; index--) {
  14962. if (this.meshes[index].id === id) {
  14963. return this.meshes[index];
  14964. }
  14965. }
  14966. return null;
  14967. };
  14968. /**
  14969. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  14970. * @param {string} id - the id to search for
  14971. * @return {BABYLON.Node|null} the node found or null if not found at all.
  14972. */
  14973. Scene.prototype.getLastEntryByID = function (id) {
  14974. var index;
  14975. for (index = this.meshes.length - 1; index >= 0; index--) {
  14976. if (this.meshes[index].id === id) {
  14977. return this.meshes[index];
  14978. }
  14979. }
  14980. for (index = this.cameras.length - 1; index >= 0; index--) {
  14981. if (this.cameras[index].id === id) {
  14982. return this.cameras[index];
  14983. }
  14984. }
  14985. for (index = this.lights.length - 1; index >= 0; index--) {
  14986. if (this.lights[index].id === id) {
  14987. return this.lights[index];
  14988. }
  14989. }
  14990. return null;
  14991. };
  14992. Scene.prototype.getNodeByID = function (id) {
  14993. var mesh = this.getMeshByID(id);
  14994. if (mesh) {
  14995. return mesh;
  14996. }
  14997. var light = this.getLightByID(id);
  14998. if (light) {
  14999. return light;
  15000. }
  15001. var camera = this.getCameraByID(id);
  15002. if (camera) {
  15003. return camera;
  15004. }
  15005. var bone = this.getBoneByID(id);
  15006. return bone;
  15007. };
  15008. Scene.prototype.getNodeByName = function (name) {
  15009. var mesh = this.getMeshByName(name);
  15010. if (mesh) {
  15011. return mesh;
  15012. }
  15013. var light = this.getLightByName(name);
  15014. if (light) {
  15015. return light;
  15016. }
  15017. var camera = this.getCameraByName(name);
  15018. if (camera) {
  15019. return camera;
  15020. }
  15021. var bone = this.getBoneByName(name);
  15022. return bone;
  15023. };
  15024. Scene.prototype.getMeshByName = function (name) {
  15025. for (var index = 0; index < this.meshes.length; index++) {
  15026. if (this.meshes[index].name === name) {
  15027. return this.meshes[index];
  15028. }
  15029. }
  15030. return null;
  15031. };
  15032. Scene.prototype.getSoundByName = function (name) {
  15033. var index;
  15034. if (BABYLON.AudioEngine) {
  15035. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15036. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15037. return this.mainSoundTrack.soundCollection[index];
  15038. }
  15039. }
  15040. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15041. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15042. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15043. return this.soundTracks[sdIndex].soundCollection[index];
  15044. }
  15045. }
  15046. }
  15047. }
  15048. return null;
  15049. };
  15050. Scene.prototype.getLastSkeletonByID = function (id) {
  15051. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15052. if (this.skeletons[index].id === id) {
  15053. return this.skeletons[index];
  15054. }
  15055. }
  15056. return null;
  15057. };
  15058. Scene.prototype.getSkeletonById = function (id) {
  15059. for (var index = 0; index < this.skeletons.length; index++) {
  15060. if (this.skeletons[index].id === id) {
  15061. return this.skeletons[index];
  15062. }
  15063. }
  15064. return null;
  15065. };
  15066. Scene.prototype.getSkeletonByName = function (name) {
  15067. for (var index = 0; index < this.skeletons.length; index++) {
  15068. if (this.skeletons[index].name === name) {
  15069. return this.skeletons[index];
  15070. }
  15071. }
  15072. return null;
  15073. };
  15074. Scene.prototype.isActiveMesh = function (mesh) {
  15075. return (this._activeMeshes.indexOf(mesh) !== -1);
  15076. };
  15077. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15078. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15079. var material = subMesh.getMaterial();
  15080. if (mesh.showSubMeshesBoundingBox) {
  15081. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15082. }
  15083. if (material) {
  15084. // Render targets
  15085. if (material.getRenderTargetTextures) {
  15086. if (this._processedMaterials.indexOf(material) === -1) {
  15087. this._processedMaterials.push(material);
  15088. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15089. }
  15090. }
  15091. // Dispatch
  15092. this._activeIndices += subMesh.indexCount;
  15093. this._renderingManager.dispatch(subMesh);
  15094. }
  15095. }
  15096. };
  15097. Scene.prototype._isInIntermediateRendering = function () {
  15098. return this._intermediateRendering;
  15099. };
  15100. Scene.prototype._evaluateActiveMeshes = function () {
  15101. this.activeCamera._activeMeshes.reset();
  15102. this._activeMeshes.reset();
  15103. this._renderingManager.reset();
  15104. this._processedMaterials.reset();
  15105. this._activeParticleSystems.reset();
  15106. this._activeSkeletons.reset();
  15107. this._softwareSkinnedMeshes.reset();
  15108. this._boundingBoxRenderer.reset();
  15109. this._edgesRenderers.reset();
  15110. if (!this._frustumPlanes) {
  15111. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15112. }
  15113. else {
  15114. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15115. }
  15116. // Meshes
  15117. var meshes;
  15118. var len;
  15119. if (this._selectionOctree) {
  15120. var selection = this._selectionOctree.select(this._frustumPlanes);
  15121. meshes = selection.data;
  15122. len = selection.length;
  15123. }
  15124. else {
  15125. len = this.meshes.length;
  15126. meshes = this.meshes;
  15127. }
  15128. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15129. var mesh = meshes[meshIndex];
  15130. if (mesh.isBlocked) {
  15131. continue;
  15132. }
  15133. this._totalVertices += mesh.getTotalVertices();
  15134. if (!mesh.isReady() || !mesh.isEnabled()) {
  15135. continue;
  15136. }
  15137. mesh.computeWorldMatrix();
  15138. // Intersections
  15139. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15140. this._meshesForIntersections.pushNoDuplicate(mesh);
  15141. }
  15142. // Switch to current LOD
  15143. var meshLOD = mesh.getLOD(this.activeCamera);
  15144. if (!meshLOD) {
  15145. continue;
  15146. }
  15147. mesh._preActivate();
  15148. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15149. this._activeMeshes.push(mesh);
  15150. this.activeCamera._activeMeshes.push(mesh);
  15151. mesh._activate(this._renderId);
  15152. this._activeMesh(meshLOD);
  15153. }
  15154. }
  15155. // Particle systems
  15156. var beforeParticlesDate = BABYLON.Tools.Now;
  15157. if (this.particlesEnabled) {
  15158. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15159. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15160. var particleSystem = this.particleSystems[particleIndex];
  15161. if (!particleSystem.isStarted()) {
  15162. continue;
  15163. }
  15164. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15165. this._activeParticleSystems.push(particleSystem);
  15166. particleSystem.animate();
  15167. }
  15168. }
  15169. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15170. }
  15171. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15172. };
  15173. Scene.prototype._activeMesh = function (mesh) {
  15174. if (mesh.skeleton && this.skeletonsEnabled) {
  15175. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15176. if (!mesh.computeBonesUsingShaders) {
  15177. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15178. }
  15179. }
  15180. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15181. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15182. }
  15183. if (mesh._edgesRenderer) {
  15184. this._edgesRenderers.push(mesh._edgesRenderer);
  15185. }
  15186. if (mesh && mesh.subMeshes) {
  15187. // Submeshes Octrees
  15188. var len;
  15189. var subMeshes;
  15190. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15191. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15192. len = intersections.length;
  15193. subMeshes = intersections.data;
  15194. }
  15195. else {
  15196. subMeshes = mesh.subMeshes;
  15197. len = subMeshes.length;
  15198. }
  15199. for (var subIndex = 0; subIndex < len; subIndex++) {
  15200. var subMesh = subMeshes[subIndex];
  15201. this._evaluateSubMesh(subMesh, mesh);
  15202. }
  15203. }
  15204. };
  15205. Scene.prototype.updateTransformMatrix = function (force) {
  15206. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15207. };
  15208. Scene.prototype._renderForCamera = function (camera) {
  15209. var engine = this._engine;
  15210. this.activeCamera = camera;
  15211. if (!this.activeCamera)
  15212. throw new Error("Active camera not set");
  15213. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15214. // Viewport
  15215. engine.setViewport(this.activeCamera.viewport);
  15216. // Camera
  15217. this.resetCachedMaterial();
  15218. this._renderId++;
  15219. this.updateTransformMatrix();
  15220. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15221. // Meshes
  15222. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15223. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15224. this._evaluateActiveMeshes();
  15225. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15226. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15227. // Skeletons
  15228. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15229. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15230. skeleton.prepare();
  15231. }
  15232. // Software skinning
  15233. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15234. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15235. mesh.applySkeleton(mesh.skeleton);
  15236. }
  15237. // Render targets
  15238. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15239. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15240. this._intermediateRendering = true;
  15241. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15242. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15243. var renderTarget = this._renderTargets.data[renderIndex];
  15244. if (renderTarget._shouldRender()) {
  15245. this._renderId++;
  15246. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15247. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15248. }
  15249. }
  15250. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15251. this._intermediateRendering = false;
  15252. this._renderId++;
  15253. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15254. }
  15255. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15256. // Prepare Frame
  15257. this.postProcessManager._prepareFrame();
  15258. var beforeRenderDate = BABYLON.Tools.Now;
  15259. // Backgrounds
  15260. var layerIndex;
  15261. var layer;
  15262. if (this.layers.length) {
  15263. engine.setDepthBuffer(false);
  15264. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15265. layer = this.layers[layerIndex];
  15266. if (layer.isBackground) {
  15267. layer.render();
  15268. }
  15269. }
  15270. engine.setDepthBuffer(true);
  15271. }
  15272. // Render
  15273. BABYLON.Tools.StartPerformanceCounter("Main render");
  15274. this._renderingManager.render(null, null, true, true);
  15275. BABYLON.Tools.EndPerformanceCounter("Main render");
  15276. // Bounding boxes
  15277. this._boundingBoxRenderer.render();
  15278. // Edges
  15279. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15280. this._edgesRenderers.data[edgesRendererIndex].render();
  15281. }
  15282. // Lens flares
  15283. if (this.lensFlaresEnabled) {
  15284. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15285. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15286. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15287. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15288. lensFlareSystem.render();
  15289. }
  15290. }
  15291. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15292. }
  15293. // Foregrounds
  15294. if (this.layers.length) {
  15295. engine.setDepthBuffer(false);
  15296. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15297. layer = this.layers[layerIndex];
  15298. if (!layer.isBackground) {
  15299. layer.render();
  15300. }
  15301. }
  15302. engine.setDepthBuffer(true);
  15303. }
  15304. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15305. // Finalize frame
  15306. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15307. // Update camera
  15308. this.activeCamera._updateFromScene();
  15309. // Reset some special arrays
  15310. this._renderTargets.reset();
  15311. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15312. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15313. };
  15314. Scene.prototype._processSubCameras = function (camera) {
  15315. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15316. this._renderForCamera(camera);
  15317. return;
  15318. }
  15319. // rig cameras
  15320. for (var index = 0; index < camera._rigCameras.length; index++) {
  15321. this._renderForCamera(camera._rigCameras[index]);
  15322. }
  15323. this.activeCamera = camera;
  15324. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15325. // Update camera
  15326. this.activeCamera._updateFromScene();
  15327. };
  15328. Scene.prototype._checkIntersections = function () {
  15329. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15330. var sourceMesh = this._meshesForIntersections.data[index];
  15331. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15332. var action = sourceMesh.actionManager.actions[actionIndex];
  15333. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15334. var parameters = action.getTriggerParameter();
  15335. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15336. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15337. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15338. if (areIntersecting && currentIntersectionInProgress === -1) {
  15339. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15340. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15341. sourceMesh._intersectionsInProgress.push(otherMesh);
  15342. }
  15343. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15344. sourceMesh._intersectionsInProgress.push(otherMesh);
  15345. }
  15346. }
  15347. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15348. //They intersected, and now they don't.
  15349. //is this trigger an exit trigger? execute an event.
  15350. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15351. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15352. }
  15353. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15354. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15355. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15356. }
  15357. }
  15358. }
  15359. }
  15360. }
  15361. };
  15362. Scene.prototype.render = function () {
  15363. var startDate = BABYLON.Tools.Now;
  15364. this._particlesDuration = 0;
  15365. this._spritesDuration = 0;
  15366. this._activeParticles = 0;
  15367. this._renderDuration = 0;
  15368. this._renderTargetsDuration = 0;
  15369. this._evaluateActiveMeshesDuration = 0;
  15370. this._totalVertices = 0;
  15371. this._activeIndices = 0;
  15372. this._activeBones = 0;
  15373. this.getEngine().resetDrawCalls();
  15374. this._meshesForIntersections.reset();
  15375. this.resetCachedMaterial();
  15376. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15377. // Actions
  15378. if (this.actionManager) {
  15379. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15380. }
  15381. //Simplification Queue
  15382. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15383. this.simplificationQueue.executeNext();
  15384. }
  15385. // Animations
  15386. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15387. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15388. this._animate();
  15389. // Physics
  15390. if (this._physicsEngine) {
  15391. BABYLON.Tools.StartPerformanceCounter("Physics");
  15392. this._physicsEngine._step(deltaTime / 1000.0);
  15393. BABYLON.Tools.EndPerformanceCounter("Physics");
  15394. }
  15395. // Before render
  15396. this.onBeforeRenderObservable.notifyObservers(this);
  15397. // Customs render targets
  15398. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15399. var engine = this.getEngine();
  15400. var currentActiveCamera = this.activeCamera;
  15401. if (this.renderTargetsEnabled) {
  15402. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15403. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15404. var renderTarget = this.customRenderTargets[customIndex];
  15405. if (renderTarget._shouldRender()) {
  15406. this._renderId++;
  15407. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15408. if (!this.activeCamera)
  15409. throw new Error("Active camera not set");
  15410. // Viewport
  15411. engine.setViewport(this.activeCamera.viewport);
  15412. // Camera
  15413. this.updateTransformMatrix();
  15414. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15415. }
  15416. }
  15417. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15418. this._renderId++;
  15419. }
  15420. if (this.customRenderTargets.length > 0) {
  15421. engine.restoreDefaultFramebuffer();
  15422. }
  15423. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15424. this.activeCamera = currentActiveCamera;
  15425. // Procedural textures
  15426. if (this.proceduralTexturesEnabled) {
  15427. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15428. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15429. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15430. if (proceduralTexture._shouldRender()) {
  15431. proceduralTexture.render();
  15432. }
  15433. }
  15434. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15435. }
  15436. // Clear
  15437. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15438. // Shadows
  15439. if (this.shadowsEnabled) {
  15440. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15441. var light = this.lights[lightIndex];
  15442. var shadowGenerator = light.getShadowGenerator();
  15443. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15444. this._renderTargets.push(shadowGenerator.getShadowMap());
  15445. }
  15446. }
  15447. }
  15448. // Depth renderer
  15449. if (this._depthRenderer) {
  15450. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15451. }
  15452. // RenderPipeline
  15453. this.postProcessRenderPipelineManager.update();
  15454. // Multi-cameras?
  15455. if (this.activeCameras.length > 0) {
  15456. var currentRenderId = this._renderId;
  15457. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15458. this._renderId = currentRenderId;
  15459. if (cameraIndex > 0) {
  15460. this._engine.clear(0, false, true);
  15461. }
  15462. this._processSubCameras(this.activeCameras[cameraIndex]);
  15463. }
  15464. }
  15465. else {
  15466. if (!this.activeCamera) {
  15467. throw new Error("No camera defined");
  15468. }
  15469. this._processSubCameras(this.activeCamera);
  15470. }
  15471. // Intersection checks
  15472. this._checkIntersections();
  15473. // Update the audio listener attached to the camera
  15474. if (BABYLON.AudioEngine) {
  15475. this._updateAudioParameters();
  15476. }
  15477. // After render
  15478. if (this.afterRender) {
  15479. this.afterRender();
  15480. }
  15481. this.onAfterRenderObservable.notifyObservers(this);
  15482. // Cleaning
  15483. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15484. this._toBeDisposed.data[index].dispose();
  15485. this._toBeDisposed[index] = null;
  15486. }
  15487. this._toBeDisposed.reset();
  15488. if (this.dumpNextRenderTargets) {
  15489. this.dumpNextRenderTargets = false;
  15490. }
  15491. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15492. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15493. };
  15494. Scene.prototype._updateAudioParameters = function () {
  15495. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15496. return;
  15497. }
  15498. var listeningCamera;
  15499. var audioEngine = BABYLON.Engine.audioEngine;
  15500. if (this.activeCameras.length > 0) {
  15501. listeningCamera = this.activeCameras[0];
  15502. }
  15503. else {
  15504. listeningCamera = this.activeCamera;
  15505. }
  15506. if (listeningCamera && audioEngine.canUseWebAudio) {
  15507. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15508. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15509. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15510. cameraDirection.normalize();
  15511. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15512. var i;
  15513. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15514. var sound = this.mainSoundTrack.soundCollection[i];
  15515. if (sound.useCustomAttenuation) {
  15516. sound.updateDistanceFromListener();
  15517. }
  15518. }
  15519. for (i = 0; i < this.soundTracks.length; i++) {
  15520. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15521. sound = this.soundTracks[i].soundCollection[j];
  15522. if (sound.useCustomAttenuation) {
  15523. sound.updateDistanceFromListener();
  15524. }
  15525. }
  15526. }
  15527. }
  15528. };
  15529. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15530. // Audio
  15531. get: function () {
  15532. return this._audioEnabled;
  15533. },
  15534. set: function (value) {
  15535. this._audioEnabled = value;
  15536. if (BABYLON.AudioEngine) {
  15537. if (this._audioEnabled) {
  15538. this._enableAudio();
  15539. }
  15540. else {
  15541. this._disableAudio();
  15542. }
  15543. }
  15544. },
  15545. enumerable: true,
  15546. configurable: true
  15547. });
  15548. Scene.prototype._disableAudio = function () {
  15549. var i;
  15550. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15551. this.mainSoundTrack.soundCollection[i].pause();
  15552. }
  15553. for (i = 0; i < this.soundTracks.length; i++) {
  15554. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15555. this.soundTracks[i].soundCollection[j].pause();
  15556. }
  15557. }
  15558. };
  15559. Scene.prototype._enableAudio = function () {
  15560. var i;
  15561. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15562. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15563. this.mainSoundTrack.soundCollection[i].play();
  15564. }
  15565. }
  15566. for (i = 0; i < this.soundTracks.length; i++) {
  15567. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15568. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15569. this.soundTracks[i].soundCollection[j].play();
  15570. }
  15571. }
  15572. }
  15573. };
  15574. Object.defineProperty(Scene.prototype, "headphone", {
  15575. get: function () {
  15576. return this._headphone;
  15577. },
  15578. set: function (value) {
  15579. this._headphone = value;
  15580. if (BABYLON.AudioEngine) {
  15581. if (this._headphone) {
  15582. this._switchAudioModeForHeadphones();
  15583. }
  15584. else {
  15585. this._switchAudioModeForNormalSpeakers();
  15586. }
  15587. }
  15588. },
  15589. enumerable: true,
  15590. configurable: true
  15591. });
  15592. Scene.prototype._switchAudioModeForHeadphones = function () {
  15593. this.mainSoundTrack.switchPanningModelToHRTF();
  15594. for (var i = 0; i < this.soundTracks.length; i++) {
  15595. this.soundTracks[i].switchPanningModelToHRTF();
  15596. }
  15597. };
  15598. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15599. this.mainSoundTrack.switchPanningModelToEqualPower();
  15600. for (var i = 0; i < this.soundTracks.length; i++) {
  15601. this.soundTracks[i].switchPanningModelToEqualPower();
  15602. }
  15603. };
  15604. Scene.prototype.enableDepthRenderer = function () {
  15605. if (this._depthRenderer) {
  15606. return this._depthRenderer;
  15607. }
  15608. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15609. return this._depthRenderer;
  15610. };
  15611. Scene.prototype.disableDepthRenderer = function () {
  15612. if (!this._depthRenderer) {
  15613. return;
  15614. }
  15615. this._depthRenderer.dispose();
  15616. this._depthRenderer = null;
  15617. };
  15618. Scene.prototype.freezeMaterials = function () {
  15619. for (var i = 0; i < this.materials.length; i++) {
  15620. this.materials[i].freeze();
  15621. }
  15622. };
  15623. Scene.prototype.unfreezeMaterials = function () {
  15624. for (var i = 0; i < this.materials.length; i++) {
  15625. this.materials[i].unfreeze();
  15626. }
  15627. };
  15628. Scene.prototype.dispose = function () {
  15629. this.beforeRender = null;
  15630. this.afterRender = null;
  15631. this.skeletons = [];
  15632. this._boundingBoxRenderer.dispose();
  15633. if (this._depthRenderer) {
  15634. this._depthRenderer.dispose();
  15635. }
  15636. // Debug layer
  15637. this.debugLayer.hide();
  15638. // Events
  15639. if (this.onDispose) {
  15640. this.onDispose();
  15641. }
  15642. this.onBeforeRenderObservable.clear();
  15643. this.onAfterRenderObservable.clear();
  15644. this.detachControl();
  15645. // Release sounds & sounds tracks
  15646. if (BABYLON.AudioEngine) {
  15647. this.disposeSounds();
  15648. }
  15649. // Detach cameras
  15650. var canvas = this._engine.getRenderingCanvas();
  15651. var index;
  15652. for (index = 0; index < this.cameras.length; index++) {
  15653. this.cameras[index].detachControl(canvas);
  15654. }
  15655. // Release lights
  15656. while (this.lights.length) {
  15657. this.lights[0].dispose();
  15658. }
  15659. // Release meshes
  15660. while (this.meshes.length) {
  15661. this.meshes[0].dispose(true);
  15662. }
  15663. // Release cameras
  15664. while (this.cameras.length) {
  15665. this.cameras[0].dispose();
  15666. }
  15667. // Release materials
  15668. while (this.materials.length) {
  15669. this.materials[0].dispose();
  15670. }
  15671. // Release particles
  15672. while (this.particleSystems.length) {
  15673. this.particleSystems[0].dispose();
  15674. }
  15675. // Release sprites
  15676. while (this.spriteManagers.length) {
  15677. this.spriteManagers[0].dispose();
  15678. }
  15679. // Release layers
  15680. while (this.layers.length) {
  15681. this.layers[0].dispose();
  15682. }
  15683. // Release textures
  15684. while (this.textures.length) {
  15685. this.textures[0].dispose();
  15686. }
  15687. // Post-processes
  15688. this.postProcessManager.dispose();
  15689. // Physics
  15690. if (this._physicsEngine) {
  15691. this.disablePhysicsEngine();
  15692. }
  15693. // Remove from engine
  15694. index = this._engine.scenes.indexOf(this);
  15695. if (index > -1) {
  15696. this._engine.scenes.splice(index, 1);
  15697. }
  15698. this._engine.wipeCaches();
  15699. };
  15700. // Release sounds & sounds tracks
  15701. Scene.prototype.disposeSounds = function () {
  15702. this.mainSoundTrack.dispose();
  15703. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15704. this.soundTracks[scIndex].dispose();
  15705. }
  15706. };
  15707. // Octrees
  15708. Scene.prototype.getWorldExtends = function () {
  15709. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15710. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15711. for (var index = 0; index < this.meshes.length; index++) {
  15712. var mesh = this.meshes[index];
  15713. mesh.computeWorldMatrix(true);
  15714. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15715. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15716. BABYLON.Tools.CheckExtends(minBox, min, max);
  15717. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15718. }
  15719. return {
  15720. min: min,
  15721. max: max
  15722. };
  15723. };
  15724. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15725. if (maxCapacity === void 0) { maxCapacity = 64; }
  15726. if (maxDepth === void 0) { maxDepth = 2; }
  15727. if (!this._selectionOctree) {
  15728. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15729. }
  15730. var worldExtends = this.getWorldExtends();
  15731. // Update octree
  15732. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15733. return this._selectionOctree;
  15734. };
  15735. // Picking
  15736. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15737. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15738. var engine = this._engine;
  15739. if (!camera) {
  15740. if (!this.activeCamera)
  15741. throw new Error("Active camera not set");
  15742. camera = this.activeCamera;
  15743. }
  15744. var cameraViewport = camera.viewport;
  15745. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15746. // Moving coordinates to local viewport world
  15747. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15748. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15749. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15750. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15751. };
  15752. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15753. var engine = this._engine;
  15754. if (!camera) {
  15755. if (!this.activeCamera)
  15756. throw new Error("Active camera not set");
  15757. camera = this.activeCamera;
  15758. }
  15759. var cameraViewport = camera.viewport;
  15760. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15761. var identity = BABYLON.Matrix.Identity();
  15762. // Moving coordinates to local viewport world
  15763. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15764. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15765. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15766. };
  15767. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15768. var pickingInfo = null;
  15769. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15770. var mesh = this.meshes[meshIndex];
  15771. if (predicate) {
  15772. if (!predicate(mesh)) {
  15773. continue;
  15774. }
  15775. }
  15776. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15777. continue;
  15778. }
  15779. var world = mesh.getWorldMatrix();
  15780. var ray = rayFunction(world);
  15781. var result = mesh.intersects(ray, fastCheck);
  15782. if (!result || !result.hit)
  15783. continue;
  15784. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15785. continue;
  15786. pickingInfo = result;
  15787. if (fastCheck) {
  15788. break;
  15789. }
  15790. }
  15791. return pickingInfo || new BABYLON.PickingInfo();
  15792. };
  15793. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15794. var pickingInfo = null;
  15795. camera = camera || this.activeCamera;
  15796. if (this.spriteManagers.length > 0) {
  15797. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15798. var spriteManager = this.spriteManagers[spriteIndex];
  15799. if (!spriteManager.isPickable) {
  15800. continue;
  15801. }
  15802. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  15803. if (!result || !result.hit)
  15804. continue;
  15805. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15806. continue;
  15807. pickingInfo = result;
  15808. if (fastCheck) {
  15809. break;
  15810. }
  15811. }
  15812. }
  15813. return pickingInfo || new BABYLON.PickingInfo();
  15814. };
  15815. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  15816. var _this = this;
  15817. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15818. /// <param name="x">X position on screen</param>
  15819. /// <param name="y">Y position on screen</param>
  15820. /// <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>
  15821. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15822. /// <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>
  15823. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  15824. };
  15825. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  15826. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  15827. /// <param name="x">X position on screen</param>
  15828. /// <param name="y">Y position on screen</param>
  15829. /// <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>
  15830. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  15831. /// <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>
  15832. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  15833. };
  15834. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  15835. var _this = this;
  15836. return this._internalPick(function (world) {
  15837. if (!_this._pickWithRayInverseMatrix) {
  15838. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  15839. }
  15840. world.invertToRef(_this._pickWithRayInverseMatrix);
  15841. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  15842. }, predicate, fastCheck);
  15843. };
  15844. Scene.prototype.setPointerOverMesh = function (mesh) {
  15845. if (this._pointerOverMesh === mesh) {
  15846. return;
  15847. }
  15848. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15849. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15850. }
  15851. this._pointerOverMesh = mesh;
  15852. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  15853. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  15854. }
  15855. };
  15856. Scene.prototype.getPointerOverMesh = function () {
  15857. return this._pointerOverMesh;
  15858. };
  15859. Scene.prototype.setPointerOverSprite = function (sprite) {
  15860. if (this._pointerOverSprite === sprite) {
  15861. return;
  15862. }
  15863. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15864. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15865. }
  15866. this._pointerOverSprite = sprite;
  15867. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  15868. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  15869. }
  15870. };
  15871. Scene.prototype.getPointerOverSprite = function () {
  15872. return this._pointerOverSprite;
  15873. };
  15874. // Physics
  15875. Scene.prototype.getPhysicsEngine = function () {
  15876. return this._physicsEngine;
  15877. };
  15878. /**
  15879. * Enables physics to the current scene
  15880. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  15881. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  15882. * @return {boolean} was the physics engine initialized
  15883. */
  15884. Scene.prototype.enablePhysics = function (gravity, plugin) {
  15885. if (this._physicsEngine) {
  15886. return true;
  15887. }
  15888. try {
  15889. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  15890. return true;
  15891. }
  15892. catch (e) {
  15893. BABYLON.Tools.Error(e.message);
  15894. return false;
  15895. }
  15896. };
  15897. Scene.prototype.disablePhysicsEngine = function () {
  15898. if (!this._physicsEngine) {
  15899. return;
  15900. }
  15901. this._physicsEngine.dispose();
  15902. this._physicsEngine = undefined;
  15903. };
  15904. Scene.prototype.isPhysicsEnabled = function () {
  15905. return this._physicsEngine !== undefined;
  15906. };
  15907. /**
  15908. *
  15909. * Sets the gravity of the physics engine (and NOT of the scene)
  15910. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  15911. */
  15912. Scene.prototype.setGravity = function (gravity) {
  15913. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  15914. if (!this._physicsEngine) {
  15915. return;
  15916. }
  15917. this._physicsEngine.setGravity(gravity);
  15918. };
  15919. /**
  15920. * Legacy support, using the new API
  15921. * @Deprecated
  15922. */
  15923. Scene.prototype.createCompoundImpostor = function (parts, options) {
  15924. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  15925. if (parts.parts) {
  15926. options = parts;
  15927. parts = parts.parts;
  15928. }
  15929. var mainMesh = parts[0].mesh;
  15930. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  15931. for (var index = 1; index < parts.length; index++) {
  15932. var mesh = parts[index].mesh;
  15933. if (mesh.parent !== mainMesh) {
  15934. mesh.position = mesh.position.subtract(mainMesh.position);
  15935. mesh.parent = mainMesh;
  15936. }
  15937. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  15938. }
  15939. mainMesh.physicsImpostor.forceUpdate();
  15940. };
  15941. Scene.prototype.deleteCompoundImpostor = function (compound) {
  15942. var mesh = compound.parts[0].mesh;
  15943. mesh.physicsImpostor.dispose();
  15944. mesh.physicsImpostor = null;
  15945. };
  15946. // Misc.
  15947. Scene.prototype.createDefaultCameraOrLight = function () {
  15948. // Light
  15949. if (this.lights.length === 0) {
  15950. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  15951. }
  15952. // Camera
  15953. if (!this.activeCamera) {
  15954. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  15955. // Compute position
  15956. var worldExtends = this.getWorldExtends();
  15957. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  15958. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  15959. camera.setTarget(worldCenter);
  15960. this.activeCamera = camera;
  15961. }
  15962. };
  15963. // Tags
  15964. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  15965. if (tagsQuery === undefined) {
  15966. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  15967. return list;
  15968. }
  15969. var listByTags = [];
  15970. forEach = forEach || (function (item) { return; });
  15971. for (var i in list) {
  15972. var item = list[i];
  15973. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  15974. listByTags.push(item);
  15975. forEach(item);
  15976. }
  15977. }
  15978. return listByTags;
  15979. };
  15980. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  15981. return this._getByTags(this.meshes, tagsQuery, forEach);
  15982. };
  15983. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  15984. return this._getByTags(this.cameras, tagsQuery, forEach);
  15985. };
  15986. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  15987. return this._getByTags(this.lights, tagsQuery, forEach);
  15988. };
  15989. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  15990. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  15991. };
  15992. // Statics
  15993. Scene._FOGMODE_NONE = 0;
  15994. Scene._FOGMODE_EXP = 1;
  15995. Scene._FOGMODE_EXP2 = 2;
  15996. Scene._FOGMODE_LINEAR = 3;
  15997. Scene.MinDeltaTime = 1.0;
  15998. Scene.MaxDeltaTime = 1000.0;
  15999. return Scene;
  16000. })();
  16001. BABYLON.Scene = Scene;
  16002. })(BABYLON || (BABYLON = {}));
  16003. var BABYLON;
  16004. (function (BABYLON) {
  16005. var VertexBuffer = (function () {
  16006. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16007. if (engine instanceof BABYLON.Mesh) {
  16008. this._engine = engine.getScene().getEngine();
  16009. }
  16010. else {
  16011. this._engine = engine;
  16012. }
  16013. this._updatable = updatable;
  16014. this._data = data;
  16015. if (!postponeInternalCreation) {
  16016. this.create();
  16017. }
  16018. this._kind = kind;
  16019. if (stride) {
  16020. this._strideSize = stride;
  16021. return;
  16022. }
  16023. // Deduce stride from kind
  16024. switch (kind) {
  16025. case VertexBuffer.PositionKind:
  16026. this._strideSize = 3;
  16027. break;
  16028. case VertexBuffer.NormalKind:
  16029. this._strideSize = 3;
  16030. break;
  16031. case VertexBuffer.UVKind:
  16032. case VertexBuffer.UV2Kind:
  16033. case VertexBuffer.UV3Kind:
  16034. case VertexBuffer.UV4Kind:
  16035. case VertexBuffer.UV5Kind:
  16036. case VertexBuffer.UV6Kind:
  16037. this._strideSize = 2;
  16038. break;
  16039. case VertexBuffer.ColorKind:
  16040. this._strideSize = 4;
  16041. break;
  16042. case VertexBuffer.MatricesIndicesKind:
  16043. case VertexBuffer.MatricesIndicesExtraKind:
  16044. this._strideSize = 4;
  16045. break;
  16046. case VertexBuffer.MatricesWeightsKind:
  16047. case VertexBuffer.MatricesWeightsExtraKind:
  16048. this._strideSize = 4;
  16049. break;
  16050. }
  16051. }
  16052. // Properties
  16053. VertexBuffer.prototype.isUpdatable = function () {
  16054. return this._updatable;
  16055. };
  16056. VertexBuffer.prototype.getData = function () {
  16057. return this._data;
  16058. };
  16059. VertexBuffer.prototype.getBuffer = function () {
  16060. return this._buffer;
  16061. };
  16062. VertexBuffer.prototype.getStrideSize = function () {
  16063. return this._strideSize;
  16064. };
  16065. // Methods
  16066. VertexBuffer.prototype.create = function (data) {
  16067. if (!data && this._buffer) {
  16068. return; // nothing to do
  16069. }
  16070. data = data || this._data;
  16071. if (!this._buffer) {
  16072. if (this._updatable) {
  16073. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16074. }
  16075. else {
  16076. this._buffer = this._engine.createVertexBuffer(data);
  16077. }
  16078. }
  16079. if (this._updatable) {
  16080. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16081. this._data = data;
  16082. }
  16083. };
  16084. VertexBuffer.prototype.update = function (data) {
  16085. this.create(data);
  16086. };
  16087. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16088. if (!this._buffer) {
  16089. return;
  16090. }
  16091. if (this._updatable) {
  16092. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16093. this._data = null;
  16094. }
  16095. };
  16096. VertexBuffer.prototype.dispose = function () {
  16097. if (!this._buffer) {
  16098. return;
  16099. }
  16100. if (this._engine._releaseBuffer(this._buffer)) {
  16101. this._buffer = null;
  16102. }
  16103. };
  16104. Object.defineProperty(VertexBuffer, "PositionKind", {
  16105. get: function () {
  16106. return VertexBuffer._PositionKind;
  16107. },
  16108. enumerable: true,
  16109. configurable: true
  16110. });
  16111. Object.defineProperty(VertexBuffer, "NormalKind", {
  16112. get: function () {
  16113. return VertexBuffer._NormalKind;
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. Object.defineProperty(VertexBuffer, "UVKind", {
  16119. get: function () {
  16120. return VertexBuffer._UVKind;
  16121. },
  16122. enumerable: true,
  16123. configurable: true
  16124. });
  16125. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16126. get: function () {
  16127. return VertexBuffer._UV2Kind;
  16128. },
  16129. enumerable: true,
  16130. configurable: true
  16131. });
  16132. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16133. get: function () {
  16134. return VertexBuffer._UV3Kind;
  16135. },
  16136. enumerable: true,
  16137. configurable: true
  16138. });
  16139. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16140. get: function () {
  16141. return VertexBuffer._UV4Kind;
  16142. },
  16143. enumerable: true,
  16144. configurable: true
  16145. });
  16146. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16147. get: function () {
  16148. return VertexBuffer._UV5Kind;
  16149. },
  16150. enumerable: true,
  16151. configurable: true
  16152. });
  16153. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16154. get: function () {
  16155. return VertexBuffer._UV6Kind;
  16156. },
  16157. enumerable: true,
  16158. configurable: true
  16159. });
  16160. Object.defineProperty(VertexBuffer, "ColorKind", {
  16161. get: function () {
  16162. return VertexBuffer._ColorKind;
  16163. },
  16164. enumerable: true,
  16165. configurable: true
  16166. });
  16167. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16168. get: function () {
  16169. return VertexBuffer._MatricesIndicesKind;
  16170. },
  16171. enumerable: true,
  16172. configurable: true
  16173. });
  16174. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16175. get: function () {
  16176. return VertexBuffer._MatricesWeightsKind;
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16182. get: function () {
  16183. return VertexBuffer._MatricesIndicesExtraKind;
  16184. },
  16185. enumerable: true,
  16186. configurable: true
  16187. });
  16188. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16189. get: function () {
  16190. return VertexBuffer._MatricesWeightsExtraKind;
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. // Enums
  16196. VertexBuffer._PositionKind = "position";
  16197. VertexBuffer._NormalKind = "normal";
  16198. VertexBuffer._UVKind = "uv";
  16199. VertexBuffer._UV2Kind = "uv2";
  16200. VertexBuffer._UV3Kind = "uv3";
  16201. VertexBuffer._UV4Kind = "uv4";
  16202. VertexBuffer._UV5Kind = "uv5";
  16203. VertexBuffer._UV6Kind = "uv6";
  16204. VertexBuffer._ColorKind = "color";
  16205. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16206. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16207. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16208. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16209. return VertexBuffer;
  16210. })();
  16211. BABYLON.VertexBuffer = VertexBuffer;
  16212. })(BABYLON || (BABYLON = {}));
  16213. var BABYLON;
  16214. (function (BABYLON) {
  16215. /**
  16216. * Creates an instance based on a source mesh.
  16217. */
  16218. var InstancedMesh = (function (_super) {
  16219. __extends(InstancedMesh, _super);
  16220. function InstancedMesh(name, source) {
  16221. _super.call(this, name, source.getScene());
  16222. source.instances.push(this);
  16223. this._sourceMesh = source;
  16224. this.position.copyFrom(source.position);
  16225. this.rotation.copyFrom(source.rotation);
  16226. this.scaling.copyFrom(source.scaling);
  16227. if (source.rotationQuaternion) {
  16228. this.rotationQuaternion = source.rotationQuaternion.clone();
  16229. }
  16230. this.infiniteDistance = source.infiniteDistance;
  16231. this.setPivotMatrix(source.getPivotMatrix());
  16232. this.refreshBoundingInfo();
  16233. this._syncSubMeshes();
  16234. }
  16235. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16236. // Methods
  16237. get: function () {
  16238. return this._sourceMesh.receiveShadows;
  16239. },
  16240. enumerable: true,
  16241. configurable: true
  16242. });
  16243. Object.defineProperty(InstancedMesh.prototype, "material", {
  16244. get: function () {
  16245. return this._sourceMesh.material;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16251. get: function () {
  16252. return this._sourceMesh.visibility;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16258. get: function () {
  16259. return this._sourceMesh.skeleton;
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16265. get: function () {
  16266. return this._sourceMesh.renderingGroupId;
  16267. },
  16268. enumerable: true,
  16269. configurable: true
  16270. });
  16271. InstancedMesh.prototype.getTotalVertices = function () {
  16272. return this._sourceMesh.getTotalVertices();
  16273. };
  16274. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16275. get: function () {
  16276. return this._sourceMesh;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16282. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16283. };
  16284. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16285. return this._sourceMesh.isVerticesDataPresent(kind);
  16286. };
  16287. InstancedMesh.prototype.getIndices = function () {
  16288. return this._sourceMesh.getIndices();
  16289. };
  16290. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16291. get: function () {
  16292. return this._sourceMesh._positions;
  16293. },
  16294. enumerable: true,
  16295. configurable: true
  16296. });
  16297. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16298. var meshBB = this._sourceMesh.getBoundingInfo();
  16299. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16300. this._updateBoundingInfo();
  16301. };
  16302. InstancedMesh.prototype._preActivate = function () {
  16303. if (this._currentLOD) {
  16304. this._currentLOD._preActivate();
  16305. }
  16306. };
  16307. InstancedMesh.prototype._activate = function (renderId) {
  16308. if (this._currentLOD) {
  16309. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16310. }
  16311. };
  16312. InstancedMesh.prototype.getLOD = function (camera) {
  16313. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16314. if (this._currentLOD === this.sourceMesh) {
  16315. return this;
  16316. }
  16317. return this._currentLOD;
  16318. };
  16319. InstancedMesh.prototype._syncSubMeshes = function () {
  16320. this.releaseSubMeshes();
  16321. if (this._sourceMesh.subMeshes) {
  16322. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16323. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16324. }
  16325. }
  16326. };
  16327. InstancedMesh.prototype._generatePointsArray = function () {
  16328. return this._sourceMesh._generatePointsArray();
  16329. };
  16330. // Clone
  16331. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16332. var result = this._sourceMesh.createInstance(name);
  16333. // Deep copy
  16334. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16335. // Bounding info
  16336. this.refreshBoundingInfo();
  16337. // Parent
  16338. if (newParent) {
  16339. result.parent = newParent;
  16340. }
  16341. if (!doNotCloneChildren) {
  16342. // Children
  16343. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16344. var mesh = this.getScene().meshes[index];
  16345. if (mesh.parent === this) {
  16346. mesh.clone(mesh.name, result);
  16347. }
  16348. }
  16349. }
  16350. result.computeWorldMatrix(true);
  16351. return result;
  16352. };
  16353. // Dispoe
  16354. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16355. // Remove from mesh
  16356. var index = this._sourceMesh.instances.indexOf(this);
  16357. this._sourceMesh.instances.splice(index, 1);
  16358. _super.prototype.dispose.call(this, doNotRecurse);
  16359. };
  16360. return InstancedMesh;
  16361. })(BABYLON.AbstractMesh);
  16362. BABYLON.InstancedMesh = InstancedMesh;
  16363. })(BABYLON || (BABYLON = {}));
  16364. var BABYLON;
  16365. (function (BABYLON) {
  16366. var _InstancesBatch = (function () {
  16367. function _InstancesBatch() {
  16368. this.mustReturn = false;
  16369. this.visibleInstances = new Array();
  16370. this.renderSelf = new Array();
  16371. }
  16372. return _InstancesBatch;
  16373. })();
  16374. BABYLON._InstancesBatch = _InstancesBatch;
  16375. var Mesh = (function (_super) {
  16376. __extends(Mesh, _super);
  16377. /**
  16378. * @constructor
  16379. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16380. * @param {Scene} scene - The scene to add this mesh to.
  16381. * @param {Node} parent - The parent of this mesh, if it has one
  16382. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16383. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16384. * When false, achieved by calling a clone(), also passing False.
  16385. * This will make creation of children, recursive.
  16386. */
  16387. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  16388. if (parent === void 0) { parent = null; }
  16389. _super.call(this, name, scene);
  16390. // Events
  16391. /**
  16392. * An event triggered before rendering the mesh
  16393. * @type {BABYLON.Observable}
  16394. */
  16395. this.onBeforeRenderObservable = new BABYLON.Observable();
  16396. /**
  16397. * An event triggered after rendering the mesh
  16398. * @type {BABYLON.Observable}
  16399. */
  16400. this.onAfterRenderObservable = new BABYLON.Observable();
  16401. /**
  16402. * An event triggered before drawing the mesh
  16403. * @type {BABYLON.Observable}
  16404. */
  16405. this.onBeforeDrawObservable = new BABYLON.Observable();
  16406. // Members
  16407. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16408. this.instances = new Array();
  16409. this._LODLevels = new Array();
  16410. this._visibleInstances = {};
  16411. this._renderIdForInstances = new Array();
  16412. this._batchCache = new _InstancesBatch();
  16413. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16414. this._sideOrientation = Mesh._DEFAULTSIDE;
  16415. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16416. if (source) {
  16417. // Geometry
  16418. if (source._geometry) {
  16419. source._geometry.applyToMesh(this);
  16420. }
  16421. // Deep copy
  16422. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16423. // Pivot
  16424. this.setPivotMatrix(source.getPivotMatrix());
  16425. this.id = name + "." + source.id;
  16426. // Material
  16427. this.material = source.material;
  16428. var index;
  16429. if (!doNotCloneChildren) {
  16430. // Children
  16431. for (index = 0; index < scene.meshes.length; index++) {
  16432. var mesh = scene.meshes[index];
  16433. if (mesh.parent === source) {
  16434. // doNotCloneChildren is always going to be False
  16435. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16436. }
  16437. }
  16438. }
  16439. // Particles
  16440. for (index = 0; index < scene.particleSystems.length; index++) {
  16441. var system = scene.particleSystems[index];
  16442. if (system.emitter === source) {
  16443. system.clone(system.name, this);
  16444. }
  16445. }
  16446. this.computeWorldMatrix(true);
  16447. }
  16448. // Parent
  16449. if (parent !== null) {
  16450. this.parent = parent;
  16451. }
  16452. }
  16453. Object.defineProperty(Mesh, "FRONTSIDE", {
  16454. /**
  16455. * Mesh side orientation : usually the external or front surface
  16456. */
  16457. get: function () {
  16458. return Mesh._FRONTSIDE;
  16459. },
  16460. enumerable: true,
  16461. configurable: true
  16462. });
  16463. Object.defineProperty(Mesh, "BACKSIDE", {
  16464. /**
  16465. * Mesh side orientation : usually the internal or back surface
  16466. */
  16467. get: function () {
  16468. return Mesh._BACKSIDE;
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16474. /**
  16475. * Mesh side orientation : both internal and external or front and back surfaces
  16476. */
  16477. get: function () {
  16478. return Mesh._DOUBLESIDE;
  16479. },
  16480. enumerable: true,
  16481. configurable: true
  16482. });
  16483. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16484. /**
  16485. * Mesh side orientation : by default, `FRONTSIDE`
  16486. */
  16487. get: function () {
  16488. return Mesh._DEFAULTSIDE;
  16489. },
  16490. enumerable: true,
  16491. configurable: true
  16492. });
  16493. Object.defineProperty(Mesh, "NO_CAP", {
  16494. /**
  16495. * Mesh cap setting : no cap
  16496. */
  16497. get: function () {
  16498. return Mesh._NO_CAP;
  16499. },
  16500. enumerable: true,
  16501. configurable: true
  16502. });
  16503. Object.defineProperty(Mesh, "CAP_START", {
  16504. /**
  16505. * Mesh cap setting : one cap at the beginning of the mesh
  16506. */
  16507. get: function () {
  16508. return Mesh._CAP_START;
  16509. },
  16510. enumerable: true,
  16511. configurable: true
  16512. });
  16513. Object.defineProperty(Mesh, "CAP_END", {
  16514. /**
  16515. * Mesh cap setting : one cap at the end of the mesh
  16516. */
  16517. get: function () {
  16518. return Mesh._CAP_END;
  16519. },
  16520. enumerable: true,
  16521. configurable: true
  16522. });
  16523. Object.defineProperty(Mesh, "CAP_ALL", {
  16524. /**
  16525. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16526. */
  16527. get: function () {
  16528. return Mesh._CAP_ALL;
  16529. },
  16530. enumerable: true,
  16531. configurable: true
  16532. });
  16533. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16534. set: function (callback) {
  16535. if (this._onBeforeDrawObserver) {
  16536. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16537. }
  16538. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16539. },
  16540. enumerable: true,
  16541. configurable: true
  16542. });
  16543. // Methods
  16544. /**
  16545. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16546. */
  16547. Mesh.prototype.toString = function (fullDetails) {
  16548. var ret = _super.prototype.toString.call(this, fullDetails);
  16549. ret += ", n vertices: " + this.getTotalVertices();
  16550. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16551. if (this.animations) {
  16552. for (var i = 0; i < this.animations.length; i++) {
  16553. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16554. }
  16555. }
  16556. if (fullDetails) {
  16557. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16558. }
  16559. return ret;
  16560. };
  16561. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16562. get: function () {
  16563. return this._LODLevels.length > 0;
  16564. },
  16565. enumerable: true,
  16566. configurable: true
  16567. });
  16568. Mesh.prototype._sortLODLevels = function () {
  16569. this._LODLevels.sort(function (a, b) {
  16570. if (a.distance < b.distance) {
  16571. return 1;
  16572. }
  16573. if (a.distance > b.distance) {
  16574. return -1;
  16575. }
  16576. return 0;
  16577. });
  16578. };
  16579. /**
  16580. * Add a mesh as LOD level triggered at the given distance.
  16581. * @param {number} distance - the distance from the center of the object to show this level
  16582. * @param {Mesh} mesh - the mesh to be added as LOD level
  16583. * @return {Mesh} this mesh (for chaining)
  16584. */
  16585. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16586. if (mesh && mesh._masterMesh) {
  16587. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16588. return this;
  16589. }
  16590. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16591. this._LODLevels.push(level);
  16592. if (mesh) {
  16593. mesh._masterMesh = this;
  16594. }
  16595. this._sortLODLevels();
  16596. return this;
  16597. };
  16598. /**
  16599. * Returns the LOD level mesh at the passed distance or null is not found.
  16600. * It is related to the method `addLODLevel(distance, mesh)`.
  16601. */
  16602. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16603. for (var index = 0; index < this._LODLevels.length; index++) {
  16604. var level = this._LODLevels[index];
  16605. if (level.distance === distance) {
  16606. return level.mesh;
  16607. }
  16608. }
  16609. return null;
  16610. };
  16611. /**
  16612. * Remove a mesh from the LOD array
  16613. * @param {Mesh} mesh - the mesh to be removed.
  16614. * @return {Mesh} this mesh (for chaining)
  16615. */
  16616. Mesh.prototype.removeLODLevel = function (mesh) {
  16617. for (var index = 0; index < this._LODLevels.length; index++) {
  16618. if (this._LODLevels[index].mesh === mesh) {
  16619. this._LODLevels.splice(index, 1);
  16620. if (mesh) {
  16621. mesh._masterMesh = null;
  16622. }
  16623. }
  16624. }
  16625. this._sortLODLevels();
  16626. return this;
  16627. };
  16628. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16629. if (!this._LODLevels || this._LODLevels.length === 0) {
  16630. return this;
  16631. }
  16632. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16633. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16634. if (this.onLODLevelSelection) {
  16635. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16636. }
  16637. return this;
  16638. }
  16639. for (var index = 0; index < this._LODLevels.length; index++) {
  16640. var level = this._LODLevels[index];
  16641. if (level.distance < distanceToCamera) {
  16642. if (level.mesh) {
  16643. level.mesh._preActivate();
  16644. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16645. }
  16646. if (this.onLODLevelSelection) {
  16647. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16648. }
  16649. return level.mesh;
  16650. }
  16651. }
  16652. if (this.onLODLevelSelection) {
  16653. this.onLODLevelSelection(distanceToCamera, this, this);
  16654. }
  16655. return this;
  16656. };
  16657. Object.defineProperty(Mesh.prototype, "geometry", {
  16658. /**
  16659. * Returns the mesh internal `Geometry` object.
  16660. */
  16661. get: function () {
  16662. return this._geometry;
  16663. },
  16664. enumerable: true,
  16665. configurable: true
  16666. });
  16667. /**
  16668. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  16669. */
  16670. Mesh.prototype.getTotalVertices = function () {
  16671. if (!this._geometry) {
  16672. return 0;
  16673. }
  16674. return this._geometry.getTotalVertices();
  16675. };
  16676. /**
  16677. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  16678. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  16679. * Returns null if the mesh has no geometry or no vertex buffer.
  16680. */
  16681. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16682. if (!this._geometry) {
  16683. return null;
  16684. }
  16685. return this._geometry.getVerticesData(kind, copyWhenShared);
  16686. };
  16687. /**
  16688. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  16689. * Returns `undefined` if the mesh has no geometry.
  16690. */
  16691. Mesh.prototype.getVertexBuffer = function (kind) {
  16692. if (!this._geometry) {
  16693. return undefined;
  16694. }
  16695. return this._geometry.getVertexBuffer(kind);
  16696. };
  16697. /**
  16698. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  16699. */
  16700. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16701. if (!this._geometry) {
  16702. if (this._delayInfo) {
  16703. return this._delayInfo.indexOf(kind) !== -1;
  16704. }
  16705. return false;
  16706. }
  16707. return this._geometry.isVerticesDataPresent(kind);
  16708. };
  16709. /**
  16710. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  16711. */
  16712. Mesh.prototype.getVerticesDataKinds = function () {
  16713. if (!this._geometry) {
  16714. var result = [];
  16715. if (this._delayInfo) {
  16716. for (var kind in this._delayInfo) {
  16717. result.push(kind);
  16718. }
  16719. }
  16720. return result;
  16721. }
  16722. return this._geometry.getVerticesDataKinds();
  16723. };
  16724. /**
  16725. * Returns a positive integer : the total number of indices in this mesh geometry.
  16726. * Returns zero if the mesh has no geometry.
  16727. */
  16728. Mesh.prototype.getTotalIndices = function () {
  16729. if (!this._geometry) {
  16730. return 0;
  16731. }
  16732. return this._geometry.getTotalIndices();
  16733. };
  16734. /**
  16735. * Returns an array of integers or a Int32Array populated with the mesh indices.
  16736. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  16737. * Returns an empty array if the mesh has no geometry.
  16738. */
  16739. Mesh.prototype.getIndices = function (copyWhenShared) {
  16740. if (!this._geometry) {
  16741. return [];
  16742. }
  16743. return this._geometry.getIndices(copyWhenShared);
  16744. };
  16745. Object.defineProperty(Mesh.prototype, "isBlocked", {
  16746. get: function () {
  16747. return this._masterMesh !== null && this._masterMesh !== undefined;
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Mesh.prototype.isReady = function () {
  16753. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16754. return false;
  16755. }
  16756. return _super.prototype.isReady.call(this);
  16757. };
  16758. Mesh.prototype.isDisposed = function () {
  16759. return this._isDisposed;
  16760. };
  16761. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  16762. get: function () {
  16763. return this._sideOrientation;
  16764. },
  16765. /**
  16766. * Sets the mesh side orientation : FRONTSIDE, BACKSIDE, DOUBLESIDE or DEFAULTSIDE
  16767. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  16768. */
  16769. set: function (sideO) {
  16770. this._sideOrientation = sideO;
  16771. },
  16772. enumerable: true,
  16773. configurable: true
  16774. });
  16775. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  16776. /**
  16777. * Boolean : true if the normals aren't to be recomputed on next update.
  16778. * This property is pertinent only for updatable parametric shapes.
  16779. */
  16780. get: function () {
  16781. return this._areNormalsFrozen;
  16782. },
  16783. enumerable: true,
  16784. configurable: true
  16785. });
  16786. /**
  16787. * This function affects parametric shapes on update only : ribbons, tubes, etc.
  16788. * It has no effect at all on other shapes.
  16789. * It prevents the mesh normals from being recomputed on next position update.
  16790. */
  16791. Mesh.prototype.freezeNormals = function () {
  16792. this._areNormalsFrozen = true;
  16793. };
  16794. /**
  16795. * This function affects parametric shapes on update only : ribbons, tubes, etc.
  16796. * It has no effect at all on other shapes.
  16797. * It reactivates the mesh normals computation if it was frozen.
  16798. */
  16799. Mesh.prototype.unfreezeNormals = function () {
  16800. this._areNormalsFrozen = false;
  16801. };
  16802. // Methods
  16803. Mesh.prototype._preActivate = function () {
  16804. var sceneRenderId = this.getScene().getRenderId();
  16805. if (this._preActivateId === sceneRenderId) {
  16806. return;
  16807. }
  16808. this._preActivateId = sceneRenderId;
  16809. this._visibleInstances = null;
  16810. };
  16811. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16812. if (this._visibleInstances) {
  16813. this._visibleInstances.intermediateDefaultRenderId = renderId;
  16814. }
  16815. };
  16816. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  16817. if (!this._visibleInstances) {
  16818. this._visibleInstances = {};
  16819. this._visibleInstances.defaultRenderId = renderId;
  16820. this._visibleInstances.selfDefaultRenderId = this._renderId;
  16821. }
  16822. if (!this._visibleInstances[renderId]) {
  16823. this._visibleInstances[renderId] = new Array();
  16824. }
  16825. this._visibleInstances[renderId].push(instance);
  16826. };
  16827. /**
  16828. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  16829. * This means the mesh underlying bounding box and shpere are recomputed.
  16830. */
  16831. Mesh.prototype.refreshBoundingInfo = function () {
  16832. if (this._boundingInfo.isLocked) {
  16833. return;
  16834. }
  16835. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16836. if (data) {
  16837. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  16838. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16839. }
  16840. if (this.subMeshes) {
  16841. for (var index = 0; index < this.subMeshes.length; index++) {
  16842. this.subMeshes[index].refreshBoundingInfo();
  16843. }
  16844. }
  16845. this._updateBoundingInfo();
  16846. };
  16847. Mesh.prototype._createGlobalSubMesh = function () {
  16848. var totalVertices = this.getTotalVertices();
  16849. if (!totalVertices || !this.getIndices()) {
  16850. return null;
  16851. }
  16852. this.releaseSubMeshes();
  16853. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  16854. };
  16855. Mesh.prototype.subdivide = function (count) {
  16856. if (count < 1) {
  16857. return;
  16858. }
  16859. var totalIndices = this.getTotalIndices();
  16860. var subdivisionSize = (totalIndices / count) | 0;
  16861. var offset = 0;
  16862. // Ensure that subdivisionSize is a multiple of 3
  16863. while (subdivisionSize % 3 !== 0) {
  16864. subdivisionSize++;
  16865. }
  16866. this.releaseSubMeshes();
  16867. for (var index = 0; index < count; index++) {
  16868. if (offset >= totalIndices) {
  16869. break;
  16870. }
  16871. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  16872. offset += subdivisionSize;
  16873. }
  16874. this.synchronizeInstances();
  16875. };
  16876. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16877. if (!this._geometry) {
  16878. var vertexData = new BABYLON.VertexData();
  16879. vertexData.set(data, kind);
  16880. var scene = this.getScene();
  16881. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  16882. }
  16883. else {
  16884. this._geometry.setVerticesData(kind, data, updatable, stride);
  16885. }
  16886. };
  16887. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16888. if (!this._geometry) {
  16889. return;
  16890. }
  16891. if (!makeItUnique) {
  16892. this._geometry.updateVerticesData(kind, data, updateExtends);
  16893. }
  16894. else {
  16895. this.makeGeometryUnique();
  16896. this.updateVerticesData(kind, data, updateExtends, false);
  16897. }
  16898. };
  16899. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  16900. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  16901. if (!this._geometry) {
  16902. return;
  16903. }
  16904. if (!makeItUnique) {
  16905. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  16906. }
  16907. else {
  16908. this.makeGeometryUnique();
  16909. this.updateVerticesDataDirectly(kind, data, offset, false);
  16910. }
  16911. };
  16912. /**
  16913. * This method updates the postions of a updatable mesh according to the `positionFunction` returned values.
  16914. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  16915. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  16916. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the mesh position update.
  16917. */
  16918. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  16919. if (computeNormals === void 0) { computeNormals = true; }
  16920. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16921. positionFunction(positions);
  16922. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16923. if (computeNormals) {
  16924. var indices = this.getIndices();
  16925. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16926. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16927. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16928. }
  16929. };
  16930. Mesh.prototype.makeGeometryUnique = function () {
  16931. if (!this._geometry) {
  16932. return;
  16933. }
  16934. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  16935. geometry.applyToMesh(this);
  16936. };
  16937. Mesh.prototype.setIndices = function (indices, totalVertices) {
  16938. if (!this._geometry) {
  16939. var vertexData = new BABYLON.VertexData();
  16940. vertexData.indices = indices;
  16941. var scene = this.getScene();
  16942. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  16943. }
  16944. else {
  16945. this._geometry.setIndices(indices, totalVertices);
  16946. }
  16947. };
  16948. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  16949. var engine = this.getScene().getEngine();
  16950. // Wireframe
  16951. var indexToBind;
  16952. if (this._unIndexed) {
  16953. indexToBind = null;
  16954. }
  16955. else {
  16956. switch (fillMode) {
  16957. case BABYLON.Material.PointFillMode:
  16958. indexToBind = null;
  16959. break;
  16960. case BABYLON.Material.WireFrameFillMode:
  16961. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  16962. break;
  16963. default:
  16964. case BABYLON.Material.TriangleFillMode:
  16965. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  16966. break;
  16967. }
  16968. }
  16969. // VBOs
  16970. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  16971. };
  16972. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  16973. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  16974. return;
  16975. }
  16976. this.onBeforeDrawObservable.notifyObservers(this);
  16977. var engine = this.getScene().getEngine();
  16978. // Draw order
  16979. switch (fillMode) {
  16980. case BABYLON.Material.PointFillMode:
  16981. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16982. break;
  16983. case BABYLON.Material.WireFrameFillMode:
  16984. if (this._unIndexed) {
  16985. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16986. }
  16987. else {
  16988. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  16989. }
  16990. break;
  16991. default:
  16992. if (this._unIndexed) {
  16993. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  16994. }
  16995. else {
  16996. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  16997. }
  16998. }
  16999. };
  17000. Mesh.prototype.registerBeforeRender = function (func) {
  17001. this.onBeforeRenderObservable.add(func);
  17002. };
  17003. Mesh.prototype.unregisterBeforeRender = function (func) {
  17004. this.onBeforeRenderObservable.removeCallback(func);
  17005. };
  17006. Mesh.prototype.registerAfterRender = function (func) {
  17007. this.onAfterRenderObservable.add(func);
  17008. };
  17009. Mesh.prototype.unregisterAfterRender = function (func) {
  17010. this.onAfterRenderObservable.removeCallback(func);
  17011. };
  17012. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17013. var scene = this.getScene();
  17014. this._batchCache.mustReturn = false;
  17015. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17016. this._batchCache.visibleInstances[subMeshId] = null;
  17017. if (this._visibleInstances) {
  17018. var currentRenderId = scene.getRenderId();
  17019. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17020. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17021. var selfRenderId = this._renderId;
  17022. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17023. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17024. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17025. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17026. }
  17027. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17028. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17029. this._batchCache.mustReturn = true;
  17030. return this._batchCache;
  17031. }
  17032. if (currentRenderId !== selfRenderId) {
  17033. this._batchCache.renderSelf[subMeshId] = false;
  17034. }
  17035. }
  17036. this._renderIdForInstances[subMeshId] = currentRenderId;
  17037. }
  17038. return this._batchCache;
  17039. };
  17040. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17041. var visibleInstances = batch.visibleInstances[subMesh._id];
  17042. var matricesCount = visibleInstances.length + 1;
  17043. var bufferSize = matricesCount * 16 * 4;
  17044. while (this._instancesBufferSize < bufferSize) {
  17045. this._instancesBufferSize *= 2;
  17046. }
  17047. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17048. if (this._worldMatricesInstancesBuffer) {
  17049. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17050. }
  17051. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17052. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17053. }
  17054. var offset = 0;
  17055. var instancesCount = 0;
  17056. var world = this.getWorldMatrix();
  17057. if (batch.renderSelf[subMesh._id]) {
  17058. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17059. offset += 16;
  17060. instancesCount++;
  17061. }
  17062. if (visibleInstances) {
  17063. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17064. var instance = visibleInstances[instanceIndex];
  17065. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17066. offset += 16;
  17067. instancesCount++;
  17068. }
  17069. }
  17070. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17071. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17072. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17073. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17074. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17075. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17076. this._draw(subMesh, fillMode, instancesCount);
  17077. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17078. };
  17079. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17080. var scene = this.getScene();
  17081. var engine = scene.getEngine();
  17082. if (hardwareInstancedRendering) {
  17083. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17084. }
  17085. else {
  17086. if (batch.renderSelf[subMesh._id]) {
  17087. // Draw
  17088. if (onBeforeDraw) {
  17089. onBeforeDraw(false, this.getWorldMatrix());
  17090. }
  17091. this._draw(subMesh, fillMode);
  17092. }
  17093. if (batch.visibleInstances[subMesh._id]) {
  17094. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17095. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17096. // World
  17097. var world = instance.getWorldMatrix();
  17098. if (onBeforeDraw) {
  17099. onBeforeDraw(true, world);
  17100. }
  17101. // Draw
  17102. this._draw(subMesh, fillMode);
  17103. }
  17104. }
  17105. }
  17106. };
  17107. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17108. var scene = this.getScene();
  17109. // Managing instances
  17110. var batch = this._getInstancesRenderList(subMesh._id);
  17111. if (batch.mustReturn) {
  17112. return;
  17113. }
  17114. // Checking geometry state
  17115. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17116. return;
  17117. }
  17118. var callbackIndex;
  17119. this.onBeforeRenderObservable.notifyObservers(this);
  17120. var engine = scene.getEngine();
  17121. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17122. // Material
  17123. var effectiveMaterial = subMesh.getMaterial();
  17124. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17125. return;
  17126. }
  17127. // Outline - step 1
  17128. var savedDepthWrite = engine.getDepthWrite();
  17129. if (this.renderOutline) {
  17130. engine.setDepthWrite(false);
  17131. scene.getOutlineRenderer().render(subMesh, batch);
  17132. engine.setDepthWrite(savedDepthWrite);
  17133. }
  17134. effectiveMaterial._preBind();
  17135. var effect = effectiveMaterial.getEffect();
  17136. // Bind
  17137. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17138. this._bind(subMesh, effect, fillMode);
  17139. var world = this.getWorldMatrix();
  17140. effectiveMaterial.bind(world, this);
  17141. // Alpha mode
  17142. if (enableAlphaMode) {
  17143. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17144. }
  17145. // Draw
  17146. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17147. if (isInstance) {
  17148. effectiveMaterial.bindOnlyWorldMatrix(world);
  17149. }
  17150. });
  17151. // Unbind
  17152. effectiveMaterial.unbind();
  17153. // Outline - step 2
  17154. if (this.renderOutline && savedDepthWrite) {
  17155. engine.setDepthWrite(true);
  17156. engine.setColorWrite(false);
  17157. scene.getOutlineRenderer().render(subMesh, batch);
  17158. engine.setColorWrite(true);
  17159. }
  17160. // Overlay
  17161. if (this.renderOverlay) {
  17162. var currentMode = engine.getAlphaMode();
  17163. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17164. scene.getOutlineRenderer().render(subMesh, batch, true);
  17165. engine.setAlphaMode(currentMode);
  17166. }
  17167. this.onAfterRenderObservable.notifyObservers(this);
  17168. };
  17169. Mesh.prototype.getEmittedParticleSystems = function () {
  17170. var results = new Array();
  17171. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17172. var particleSystem = this.getScene().particleSystems[index];
  17173. if (particleSystem.emitter === this) {
  17174. results.push(particleSystem);
  17175. }
  17176. }
  17177. return results;
  17178. };
  17179. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17180. var results = new Array();
  17181. var descendants = this.getDescendants();
  17182. descendants.push(this);
  17183. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17184. var particleSystem = this.getScene().particleSystems[index];
  17185. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17186. results.push(particleSystem);
  17187. }
  17188. }
  17189. return results;
  17190. };
  17191. Mesh.prototype._checkDelayState = function () {
  17192. var _this = this;
  17193. var that = this;
  17194. var scene = this.getScene();
  17195. if (this._geometry) {
  17196. this._geometry.load(scene);
  17197. }
  17198. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17199. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17200. scene._addPendingData(that);
  17201. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17202. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17203. if (data instanceof ArrayBuffer) {
  17204. _this._delayLoadingFunction(data, _this);
  17205. }
  17206. else {
  17207. _this._delayLoadingFunction(JSON.parse(data), _this);
  17208. }
  17209. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17210. scene._removePendingData(_this);
  17211. }, function () { }, scene.database, getBinaryData);
  17212. }
  17213. };
  17214. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17216. return false;
  17217. }
  17218. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17219. return false;
  17220. }
  17221. this._checkDelayState();
  17222. return true;
  17223. };
  17224. Mesh.prototype.setMaterialByID = function (id) {
  17225. var materials = this.getScene().materials;
  17226. var index;
  17227. for (index = 0; index < materials.length; index++) {
  17228. if (materials[index].id === id) {
  17229. this.material = materials[index];
  17230. return;
  17231. }
  17232. }
  17233. // Multi
  17234. var multiMaterials = this.getScene().multiMaterials;
  17235. for (index = 0; index < multiMaterials.length; index++) {
  17236. if (multiMaterials[index].id === id) {
  17237. this.material = multiMaterials[index];
  17238. return;
  17239. }
  17240. }
  17241. };
  17242. Mesh.prototype.getAnimatables = function () {
  17243. var results = [];
  17244. if (this.material) {
  17245. results.push(this.material);
  17246. }
  17247. if (this.skeleton) {
  17248. results.push(this.skeleton);
  17249. }
  17250. return results;
  17251. };
  17252. // Geometry
  17253. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17254. // Position
  17255. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17256. return;
  17257. }
  17258. this._resetPointsArrayCache();
  17259. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17260. var temp = [];
  17261. var index;
  17262. for (index = 0; index < data.length; index += 3) {
  17263. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17264. }
  17265. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17266. // Normals
  17267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17268. return;
  17269. }
  17270. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17271. temp = [];
  17272. for (index = 0; index < data.length; index += 3) {
  17273. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17274. }
  17275. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17276. // flip faces?
  17277. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17278. this.flipFaces();
  17279. }
  17280. };
  17281. // Will apply current transform to mesh and reset world matrix
  17282. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17283. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17284. this.scaling.copyFromFloats(1, 1, 1);
  17285. this.position.copyFromFloats(0, 0, 0);
  17286. this.rotation.copyFromFloats(0, 0, 0);
  17287. //only if quaternion is already set
  17288. if (this.rotationQuaternion) {
  17289. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17290. }
  17291. this._worldMatrix = BABYLON.Matrix.Identity();
  17292. };
  17293. // Cache
  17294. Mesh.prototype._resetPointsArrayCache = function () {
  17295. this._positions = null;
  17296. };
  17297. Mesh.prototype._generatePointsArray = function () {
  17298. if (this._positions)
  17299. return true;
  17300. this._positions = [];
  17301. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17302. if (!data) {
  17303. return false;
  17304. }
  17305. for (var index = 0; index < data.length; index += 3) {
  17306. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17307. }
  17308. return true;
  17309. };
  17310. // Clone
  17311. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17312. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  17313. };
  17314. // Dispose
  17315. Mesh.prototype.dispose = function (doNotRecurse) {
  17316. if (this._geometry) {
  17317. this._geometry.releaseForMesh(this, true);
  17318. }
  17319. // Instances
  17320. if (this._worldMatricesInstancesBuffer) {
  17321. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17322. this._worldMatricesInstancesBuffer = null;
  17323. }
  17324. while (this.instances.length) {
  17325. this.instances[0].dispose();
  17326. }
  17327. _super.prototype.dispose.call(this, doNotRecurse);
  17328. };
  17329. // Geometric tools
  17330. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17331. var _this = this;
  17332. var scene = this.getScene();
  17333. var onload = function (img) {
  17334. // Getting height map data
  17335. var canvas = document.createElement("canvas");
  17336. var context = canvas.getContext("2d");
  17337. var heightMapWidth = img.width;
  17338. var heightMapHeight = img.height;
  17339. canvas.width = heightMapWidth;
  17340. canvas.height = heightMapHeight;
  17341. context.drawImage(img, 0, 0);
  17342. // Create VertexData from map data
  17343. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17344. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17345. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17346. //execute success callback, if set
  17347. if (onSuccess) {
  17348. onSuccess(_this);
  17349. }
  17350. };
  17351. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17352. };
  17353. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17354. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17355. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17356. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17357. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17358. return;
  17359. }
  17360. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17361. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17362. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17363. var position = BABYLON.Vector3.Zero();
  17364. var normal = BABYLON.Vector3.Zero();
  17365. var uv = BABYLON.Vector2.Zero();
  17366. for (var index = 0; index < positions.length; index += 3) {
  17367. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17368. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17369. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17370. // Compute height
  17371. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17372. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17373. var pos = (u + v * heightMapWidth) * 4;
  17374. var r = buffer[pos] / 255.0;
  17375. var g = buffer[pos + 1] / 255.0;
  17376. var b = buffer[pos + 2] / 255.0;
  17377. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17378. normal.normalize();
  17379. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17380. position = position.add(normal);
  17381. position.toArray(positions, index);
  17382. }
  17383. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17384. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17385. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17386. };
  17387. /**
  17388. * Modify the mesh to get a flat shading rendering.
  17389. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17390. * Warning : the mesh is really modified.
  17391. */
  17392. Mesh.prototype.convertToFlatShadedMesh = function () {
  17393. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17394. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17395. var kinds = this.getVerticesDataKinds();
  17396. var vbs = [];
  17397. var data = [];
  17398. var newdata = [];
  17399. var updatableNormals = false;
  17400. var kindIndex;
  17401. var kind;
  17402. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17403. kind = kinds[kindIndex];
  17404. var vertexBuffer = this.getVertexBuffer(kind);
  17405. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17406. updatableNormals = vertexBuffer.isUpdatable();
  17407. kinds.splice(kindIndex, 1);
  17408. kindIndex--;
  17409. continue;
  17410. }
  17411. vbs[kind] = vertexBuffer;
  17412. data[kind] = vbs[kind].getData();
  17413. newdata[kind] = [];
  17414. }
  17415. // Save previous submeshes
  17416. var previousSubmeshes = this.subMeshes.slice(0);
  17417. var indices = this.getIndices();
  17418. var totalIndices = this.getTotalIndices();
  17419. // Generating unique vertices per face
  17420. var index;
  17421. for (index = 0; index < totalIndices; index++) {
  17422. var vertexIndex = indices[index];
  17423. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17424. kind = kinds[kindIndex];
  17425. var stride = vbs[kind].getStrideSize();
  17426. for (var offset = 0; offset < stride; offset++) {
  17427. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17428. }
  17429. }
  17430. }
  17431. // Updating faces & normal
  17432. var normals = [];
  17433. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17434. for (index = 0; index < totalIndices; index += 3) {
  17435. indices[index] = index;
  17436. indices[index + 1] = index + 1;
  17437. indices[index + 2] = index + 2;
  17438. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17439. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17440. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17441. var p1p2 = p1.subtract(p2);
  17442. var p3p2 = p3.subtract(p2);
  17443. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17444. // Store same normals for every vertex
  17445. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17446. normals.push(normal.x);
  17447. normals.push(normal.y);
  17448. normals.push(normal.z);
  17449. }
  17450. }
  17451. this.setIndices(indices);
  17452. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17453. // Updating vertex buffers
  17454. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17455. kind = kinds[kindIndex];
  17456. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17457. }
  17458. // Updating submeshes
  17459. this.releaseSubMeshes();
  17460. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17461. var previousOne = previousSubmeshes[submeshIndex];
  17462. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17463. }
  17464. this.synchronizeInstances();
  17465. };
  17466. /**
  17467. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17468. * In other words, more vertices, no more indices and a single bigger VBO.
  17469. */
  17470. Mesh.prototype.convertToUnIndexedMesh = function () {
  17471. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17472. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17473. var kinds = this.getVerticesDataKinds();
  17474. var vbs = [];
  17475. var data = [];
  17476. var newdata = [];
  17477. var updatableNormals = false;
  17478. var kindIndex;
  17479. var kind;
  17480. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17481. kind = kinds[kindIndex];
  17482. var vertexBuffer = this.getVertexBuffer(kind);
  17483. vbs[kind] = vertexBuffer;
  17484. data[kind] = vbs[kind].getData();
  17485. newdata[kind] = [];
  17486. }
  17487. // Save previous submeshes
  17488. var previousSubmeshes = this.subMeshes.slice(0);
  17489. var indices = this.getIndices();
  17490. var totalIndices = this.getTotalIndices();
  17491. // Generating unique vertices per face
  17492. var index;
  17493. for (index = 0; index < totalIndices; index++) {
  17494. var vertexIndex = indices[index];
  17495. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17496. kind = kinds[kindIndex];
  17497. var stride = vbs[kind].getStrideSize();
  17498. for (var offset = 0; offset < stride; offset++) {
  17499. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17500. }
  17501. }
  17502. }
  17503. // Updating indices
  17504. for (index = 0; index < totalIndices; index += 3) {
  17505. indices[index] = index;
  17506. indices[index + 1] = index + 1;
  17507. indices[index + 2] = index + 2;
  17508. }
  17509. this.setIndices(indices);
  17510. // Updating vertex buffers
  17511. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17512. kind = kinds[kindIndex];
  17513. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17514. }
  17515. // Updating submeshes
  17516. this.releaseSubMeshes();
  17517. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17518. var previousOne = previousSubmeshes[submeshIndex];
  17519. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17520. }
  17521. this._unIndexed = true;
  17522. this.synchronizeInstances();
  17523. };
  17524. /**
  17525. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  17526. * Warning : the mesh is really modified.
  17527. */
  17528. Mesh.prototype.flipFaces = function (flipNormals) {
  17529. if (flipNormals === void 0) { flipNormals = false; }
  17530. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17531. var i;
  17532. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17533. for (i = 0; i < vertex_data.normals.length; i++) {
  17534. vertex_data.normals[i] *= -1;
  17535. }
  17536. }
  17537. var temp;
  17538. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17539. // reassign indices
  17540. temp = vertex_data.indices[i + 1];
  17541. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17542. vertex_data.indices[i + 2] = temp;
  17543. }
  17544. vertex_data.applyToMesh(this);
  17545. };
  17546. // Instances
  17547. /**
  17548. * Creates a new `InstancedMesh` object from the mesh model.
  17549. */
  17550. Mesh.prototype.createInstance = function (name) {
  17551. return new BABYLON.InstancedMesh(name, this);
  17552. };
  17553. Mesh.prototype.synchronizeInstances = function () {
  17554. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17555. var instance = this.instances[instanceIndex];
  17556. instance._syncSubMeshes();
  17557. }
  17558. };
  17559. /**
  17560. * Simplify the mesh according to the given array of settings.
  17561. * Function will return immediately and will simplify async.
  17562. * @param settings a collection of simplification settings.
  17563. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17564. * @param type the type of simplification to run.
  17565. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17566. */
  17567. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17568. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17569. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17570. this.getScene().simplificationQueue.addTask({
  17571. settings: settings,
  17572. parallelProcessing: parallelProcessing,
  17573. mesh: this,
  17574. simplificationType: simplificationType,
  17575. successCallback: successCallback
  17576. });
  17577. };
  17578. /**
  17579. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17580. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17581. * This should be used together with the simplification to avoid disappearing triangles.
  17582. * @param successCallback an optional success callback to be called after the optimization finished.
  17583. */
  17584. Mesh.prototype.optimizeIndices = function (successCallback) {
  17585. var _this = this;
  17586. var indices = this.getIndices();
  17587. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17588. var vectorPositions = [];
  17589. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17590. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17591. }
  17592. var dupes = [];
  17593. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17594. var realPos = vectorPositions.length - 1 - iteration;
  17595. var testedPosition = vectorPositions[realPos];
  17596. for (var j = 0; j < realPos; ++j) {
  17597. var againstPosition = vectorPositions[j];
  17598. if (testedPosition.equals(againstPosition)) {
  17599. dupes[realPos] = j;
  17600. break;
  17601. }
  17602. }
  17603. }, function () {
  17604. for (var i = 0; i < indices.length; ++i) {
  17605. indices[i] = dupes[indices[i]] || indices[i];
  17606. }
  17607. //indices are now reordered
  17608. var originalSubMeshes = _this.subMeshes.slice(0);
  17609. _this.setIndices(indices);
  17610. _this.subMeshes = originalSubMeshes;
  17611. if (successCallback) {
  17612. successCallback(_this);
  17613. }
  17614. });
  17615. };
  17616. // Statics
  17617. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17618. var mesh = new Mesh(parsedMesh.name, scene);
  17619. mesh.id = parsedMesh.id;
  17620. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17621. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17622. if (parsedMesh.rotationQuaternion) {
  17623. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17624. }
  17625. else if (parsedMesh.rotation) {
  17626. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17627. }
  17628. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17629. if (parsedMesh.localMatrix) {
  17630. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17631. }
  17632. else if (parsedMesh.pivotMatrix) {
  17633. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17634. }
  17635. mesh.setEnabled(parsedMesh.isEnabled);
  17636. mesh.isVisible = parsedMesh.isVisible;
  17637. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17638. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17639. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17640. if (parsedMesh.applyFog !== undefined) {
  17641. mesh.applyFog = parsedMesh.applyFog;
  17642. }
  17643. if (parsedMesh.pickable !== undefined) {
  17644. mesh.isPickable = parsedMesh.pickable;
  17645. }
  17646. if (parsedMesh.alphaIndex !== undefined) {
  17647. mesh.alphaIndex = parsedMesh.alphaIndex;
  17648. }
  17649. mesh.receiveShadows = parsedMesh.receiveShadows;
  17650. mesh.billboardMode = parsedMesh.billboardMode;
  17651. if (parsedMesh.visibility !== undefined) {
  17652. mesh.visibility = parsedMesh.visibility;
  17653. }
  17654. mesh.checkCollisions = parsedMesh.checkCollisions;
  17655. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17656. // freezeWorldMatrix
  17657. if (parsedMesh.freezeWorldMatrix) {
  17658. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  17659. }
  17660. // Parent
  17661. if (parsedMesh.parentId) {
  17662. mesh._waitingParentId = parsedMesh.parentId;
  17663. }
  17664. // Actions
  17665. if (parsedMesh.actions !== undefined) {
  17666. mesh._waitingActions = parsedMesh.actions;
  17667. }
  17668. // Geometry
  17669. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17670. if (parsedMesh.delayLoadingFile) {
  17671. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17672. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17673. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17674. if (parsedMesh._binaryInfo) {
  17675. mesh._binaryInfo = parsedMesh._binaryInfo;
  17676. }
  17677. mesh._delayInfo = [];
  17678. if (parsedMesh.hasUVs) {
  17679. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17680. }
  17681. if (parsedMesh.hasUVs2) {
  17682. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17683. }
  17684. if (parsedMesh.hasUVs3) {
  17685. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  17686. }
  17687. if (parsedMesh.hasUVs4) {
  17688. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  17689. }
  17690. if (parsedMesh.hasUVs5) {
  17691. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  17692. }
  17693. if (parsedMesh.hasUVs6) {
  17694. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  17695. }
  17696. if (parsedMesh.hasColors) {
  17697. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17698. }
  17699. if (parsedMesh.hasMatricesIndices) {
  17700. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17701. }
  17702. if (parsedMesh.hasMatricesWeights) {
  17703. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17704. }
  17705. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  17706. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17707. mesh._checkDelayState();
  17708. }
  17709. }
  17710. else {
  17711. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  17712. }
  17713. // Material
  17714. if (parsedMesh.materialId) {
  17715. mesh.setMaterialByID(parsedMesh.materialId);
  17716. }
  17717. else {
  17718. mesh.material = null;
  17719. }
  17720. // Skeleton
  17721. if (parsedMesh.skeletonId > -1) {
  17722. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17723. if (parsedMesh.numBoneInfluencers) {
  17724. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  17725. }
  17726. }
  17727. // Animations
  17728. if (parsedMesh.animations) {
  17729. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17730. var parsedAnimation = parsedMesh.animations[animationIndex];
  17731. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17732. }
  17733. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  17734. }
  17735. if (parsedMesh.autoAnimate) {
  17736. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  17737. }
  17738. // Layer Mask
  17739. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17740. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17741. }
  17742. else {
  17743. mesh.layerMask = 0x0FFFFFFF;
  17744. }
  17745. // Instances
  17746. if (parsedMesh.instances) {
  17747. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17748. var parsedInstance = parsedMesh.instances[index];
  17749. var instance = mesh.createInstance(parsedInstance.name);
  17750. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17751. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17752. if (parsedInstance.rotationQuaternion) {
  17753. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17754. }
  17755. else if (parsedInstance.rotation) {
  17756. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17757. }
  17758. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17759. instance.checkCollisions = mesh.checkCollisions;
  17760. if (parsedMesh.animations) {
  17761. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17762. parsedAnimation = parsedMesh.animations[animationIndex];
  17763. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17764. }
  17765. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  17766. }
  17767. }
  17768. }
  17769. return mesh;
  17770. };
  17771. /**
  17772. * Creates a ribbon mesh.
  17773. * Please consider using the same method from the `MeshBuilder` class instead.
  17774. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  17775. *
  17776. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  17777. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  17778. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  17779. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  17780. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  17781. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  17782. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  17783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17786. */
  17787. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  17788. return BABYLON.MeshBuilder.CreateRibbon(name, {
  17789. pathArray: pathArray,
  17790. closeArray: closeArray,
  17791. closePath: closePath,
  17792. offset: offset,
  17793. updatable: updatable,
  17794. sideOrientation: sideOrientation,
  17795. instance: instance
  17796. }, scene);
  17797. };
  17798. /**
  17799. * Creates a plane polygonal mesh. By default, this is a disc.
  17800. * Please consider using the same method from the `MeshBuilder` class instead.
  17801. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  17802. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  17803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17806. */
  17807. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  17808. var options = {
  17809. radius: radius,
  17810. tessellation: tessellation,
  17811. sideOrientation: sideOrientation,
  17812. updatable: updatable
  17813. };
  17814. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  17815. };
  17816. /**
  17817. * Creates a box mesh.
  17818. * Please consider using the same method from the `MeshBuilder` class instead.
  17819. * The parameter `size` sets the size (float) of each box side (default 1).
  17820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17821. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17823. */
  17824. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  17825. var options = {
  17826. size: size,
  17827. sideOrientation: sideOrientation,
  17828. updatable: updatable
  17829. };
  17830. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  17831. };
  17832. /**
  17833. * Creates a sphere mesh.
  17834. * Please consider using the same method from the `MeshBuilder` class instead.
  17835. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  17836. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  17837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17840. */
  17841. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  17842. var options = {
  17843. segments: segments,
  17844. diameterX: diameter,
  17845. diameterY: diameter,
  17846. diameterZ: diameter,
  17847. sideOrientation: sideOrientation,
  17848. updatable: updatable
  17849. };
  17850. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  17851. };
  17852. /**
  17853. * Creates a cylinder or a cone mesh.
  17854. * Please consider using the same method from the `MeshBuilder` class instead.
  17855. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  17856. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  17857. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  17858. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  17859. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  17860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17863. */
  17864. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  17865. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  17866. if (scene !== undefined) {
  17867. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  17868. updatable = scene;
  17869. }
  17870. scene = subdivisions;
  17871. subdivisions = 1;
  17872. }
  17873. var options = {
  17874. height: height,
  17875. diameterTop: diameterTop,
  17876. diameterBottom: diameterBottom,
  17877. tessellation: tessellation,
  17878. subdivisions: subdivisions,
  17879. sideOrientation: sideOrientation,
  17880. updatable: updatable
  17881. };
  17882. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  17883. };
  17884. // Torus (Code from SharpDX.org)
  17885. /**
  17886. * Creates a torus mesh.
  17887. * Please consider using the same method from the `MeshBuilder` class instead.
  17888. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  17889. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  17890. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  17891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17894. */
  17895. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  17896. var options = {
  17897. diameter: diameter,
  17898. thickness: thickness,
  17899. tessellation: tessellation,
  17900. sideOrientation: sideOrientation,
  17901. updatable: updatable
  17902. };
  17903. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  17904. };
  17905. /**
  17906. * Creates a torus knot mesh.
  17907. * Please consider using the same method from the `MeshBuilder` class instead.
  17908. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  17909. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  17910. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  17911. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  17912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17913. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17915. */
  17916. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  17917. var options = {
  17918. radius: radius,
  17919. tube: tube,
  17920. radialSegments: radialSegments,
  17921. tubularSegments: tubularSegments,
  17922. p: p,
  17923. q: q,
  17924. sideOrientation: sideOrientation,
  17925. updatable: updatable
  17926. };
  17927. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  17928. };
  17929. /**
  17930. * Creates a line mesh.
  17931. * Please consider using the same method from the `MeshBuilder` class instead.
  17932. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  17933. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  17934. * The parameter `points` is an array successive Vector3.
  17935. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  17936. * When updating an instance, remember that only point positions can change, not the number of points.
  17937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17938. */
  17939. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  17940. var options = {
  17941. points: points,
  17942. updatable: updatable,
  17943. instance: instance
  17944. };
  17945. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  17946. };
  17947. /**
  17948. * Creates a dashed line mesh.
  17949. * Please consider using the same method from the `MeshBuilder` class instead.
  17950. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  17951. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  17952. * The parameter `points` is an array successive Vector3.
  17953. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  17954. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  17955. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  17956. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  17957. * When updating an instance, remember that only point positions can change, not the number of points.
  17958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17959. */
  17960. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  17961. var options = {
  17962. points: points,
  17963. dashSize: dashSize,
  17964. gapSize: gapSize,
  17965. dashNb: dashNb,
  17966. updatable: updatable
  17967. };
  17968. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  17969. };
  17970. /**
  17971. * Creates an extruded shape mesh.
  17972. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  17973. * Please consider using the same method from the `MeshBuilder` class instead.
  17974. *
  17975. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  17976. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  17977. * extruded along the Z axis.
  17978. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  17979. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  17980. * The parameter `scale` (float, default 1) is the value to scale the shape.
  17981. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  17982. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  17983. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  17984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  17985. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  17986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  17987. */
  17988. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  17989. var options = {
  17990. shape: shape,
  17991. path: path,
  17992. scale: scale,
  17993. rotation: rotation,
  17994. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  17995. sideOrientation: sideOrientation,
  17996. instance: instance,
  17997. updatable: updatable
  17998. };
  17999. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18000. };
  18001. /**
  18002. * Creates an custom extruded shape mesh.
  18003. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18004. * Please consider using the same method from the `MeshBuilder` class instead.
  18005. *
  18006. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18007. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18008. * extruded along the Z axis.
  18009. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18010. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18011. * and the distance of this point from the begining of the path :
  18012. * ```rotationFunction = function(i, distance) {
  18013. * // do things
  18014. * return rotationValue; }```
  18015. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18016. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18017. * and the distance of this point from the begining of the path :
  18018. * ````scaleFunction = function(i, distance) {
  18019. * // do things
  18020. * return scaleValue;}```
  18021. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18022. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18023. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18024. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18025. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18026. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18030. */
  18031. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18032. var options = {
  18033. shape: shape,
  18034. path: path,
  18035. scaleFunction: scaleFunction,
  18036. rotationFunction: rotationFunction,
  18037. ribbonCloseArray: ribbonCloseArray,
  18038. ribbonClosePath: ribbonClosePath,
  18039. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18040. sideOrientation: sideOrientation,
  18041. instance: instance,
  18042. updatable: updatable
  18043. };
  18044. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18045. };
  18046. /**
  18047. * Creates lathe mesh.
  18048. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18049. * Please consider using the same method from the `MeshBuilder` class instead.
  18050. *
  18051. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18052. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18053. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18054. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18058. */
  18059. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18060. var options = {
  18061. shape: shape,
  18062. radius: radius,
  18063. tessellation: tessellation,
  18064. sideOrientation: sideOrientation,
  18065. updatable: updatable
  18066. };
  18067. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18068. };
  18069. /**
  18070. * Creates a plane mesh.
  18071. * Please consider using the same method from the `MeshBuilder` class instead.
  18072. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18076. */
  18077. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18078. var options = {
  18079. size: size,
  18080. width: size,
  18081. height: size,
  18082. sideOrientation: sideOrientation,
  18083. updatable: updatable
  18084. };
  18085. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18086. };
  18087. /**
  18088. * Creates a ground mesh.
  18089. * Please consider using the same method from the `MeshBuilder` class instead.
  18090. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18091. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18093. */
  18094. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18095. var options = {
  18096. width: width,
  18097. height: height,
  18098. subdivisions: subdivisions,
  18099. updatable: updatable
  18100. };
  18101. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18102. };
  18103. /**
  18104. * Creates a tiled ground mesh.
  18105. * Please consider using the same method from the `MeshBuilder` class instead.
  18106. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18107. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18108. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18109. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18110. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18111. * numbers of subdivisions on the ground width and height of each tile.
  18112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18113. */
  18114. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18115. var options = {
  18116. xmin: xmin,
  18117. zmin: zmin,
  18118. xmax: xmax,
  18119. zmax: zmax,
  18120. subdivisions: subdivisions,
  18121. precision: precision,
  18122. updatable: updatable
  18123. };
  18124. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18125. };
  18126. /**
  18127. * Creates a ground mesh from a height map.
  18128. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18129. * Please consider using the same method from the `MeshBuilder` class instead.
  18130. * The parameter `url` sets the URL of the height map image resource.
  18131. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18132. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18133. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18134. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18135. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18136. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18137. * return; }```
  18138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18139. */
  18140. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18141. var options = {
  18142. width: width,
  18143. height: height,
  18144. subdivisions: subdivisions,
  18145. minHeight: minHeight,
  18146. maxHeight: maxHeight,
  18147. updatable: updatable,
  18148. onReady: onReady
  18149. };
  18150. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18151. };
  18152. /**
  18153. * Creates a tube mesh.
  18154. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18155. *
  18156. * Please consider using the same method from the `MeshBuilder` class instead.
  18157. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18158. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18159. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18160. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18161. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18162. * It must return a radius value (positive float) :
  18163. * ```var radiusFunction = function(i, distance) {
  18164. * // do things
  18165. * return radius; }```
  18166. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18167. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18171. */
  18172. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18173. var options = {
  18174. path: path,
  18175. radius: radius,
  18176. tessellation: tessellation,
  18177. radiusFunction: radiusFunction,
  18178. arc: 1,
  18179. cap: cap,
  18180. updatable: updatable,
  18181. sideOrientation: sideOrientation,
  18182. instance: instance
  18183. };
  18184. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18185. };
  18186. /**
  18187. * Creates a polyhedron mesh.
  18188. *
  18189. * Please consider using the same method from the `MeshBuilder` class instead.
  18190. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  18191. * to choose the wanted type.
  18192. * The parameter `size` (positive float, default 1) sets the polygon size.
  18193. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18194. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  18195. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  18196. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  18197. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18198. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  18199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18202. */
  18203. Mesh.CreatePolyhedron = function (name, options, scene) {
  18204. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18205. };
  18206. /**
  18207. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18208. * Please consider using the same method from the `MeshBuilder` class instead.
  18209. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18210. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  18211. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18212. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  18213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18216. */
  18217. Mesh.CreateIcoSphere = function (name, options, scene) {
  18218. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18219. };
  18220. /**
  18221. * Creates a decal mesh.
  18222. * Please consider using the same method from the `MeshBuilder` class instead.
  18223. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  18224. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18225. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18226. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18227. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18228. */
  18229. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18230. var options = {
  18231. position: position,
  18232. normal: normal,
  18233. size: size,
  18234. angle: angle
  18235. };
  18236. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18237. };
  18238. // Skeletons
  18239. /**
  18240. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18241. */
  18242. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18243. var source;
  18244. if (!this._sourcePositions) {
  18245. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18246. this._sourcePositions = new Float32Array(source);
  18247. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18248. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18249. }
  18250. }
  18251. return this._sourcePositions;
  18252. };
  18253. /**
  18254. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18255. */
  18256. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18257. var source;
  18258. if (!this._sourceNormals) {
  18259. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18260. this._sourceNormals = new Float32Array(source);
  18261. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18262. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18263. }
  18264. }
  18265. return this._sourceNormals;
  18266. };
  18267. /**
  18268. * Update the vertex buffers by applying transformation from the bones
  18269. * @param {skeleton} skeleton to apply
  18270. */
  18271. Mesh.prototype.applySkeleton = function (skeleton) {
  18272. if (!this.geometry) {
  18273. return;
  18274. }
  18275. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18276. return;
  18277. }
  18278. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18279. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18280. return this;
  18281. }
  18282. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18283. return this;
  18284. }
  18285. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18286. return this;
  18287. }
  18288. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18289. return this;
  18290. }
  18291. if (!this._sourcePositions) {
  18292. this.setPositionsForCPUSkinning();
  18293. }
  18294. if (!this._sourceNormals) {
  18295. this.setNormalsForCPUSkinning();
  18296. }
  18297. // positionsData checks for not being Float32Array will only pass at most once
  18298. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18299. if (!(positionsData instanceof Float32Array)) {
  18300. positionsData = new Float32Array(positionsData);
  18301. }
  18302. // normalsData checks for not being Float32Array will only pass at most once
  18303. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18304. if (!(normalsData instanceof Float32Array)) {
  18305. normalsData = new Float32Array(normalsData);
  18306. }
  18307. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18308. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18309. var needExtras = this.numBoneInfluencers > 4;
  18310. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18311. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18312. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18313. var tempVector3 = BABYLON.Vector3.Zero();
  18314. var finalMatrix = new BABYLON.Matrix();
  18315. var tempMatrix = new BABYLON.Matrix();
  18316. var matWeightIdx = 0;
  18317. var inf;
  18318. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18319. var weight;
  18320. for (inf = 0; inf < 4; inf++) {
  18321. weight = matricesWeightsData[matWeightIdx + inf];
  18322. if (weight > 0) {
  18323. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18324. finalMatrix.addToSelf(tempMatrix);
  18325. }
  18326. else
  18327. break;
  18328. }
  18329. if (needExtras) {
  18330. for (inf = 0; inf < 4; inf++) {
  18331. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18332. if (weight > 0) {
  18333. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18334. finalMatrix.addToSelf(tempMatrix);
  18335. }
  18336. else
  18337. break;
  18338. }
  18339. }
  18340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18341. tempVector3.toArray(positionsData, index);
  18342. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18343. tempVector3.toArray(normalsData, index);
  18344. finalMatrix.reset();
  18345. }
  18346. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18347. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18348. return this;
  18349. };
  18350. // Tools
  18351. Mesh.MinMax = function (meshes) {
  18352. var minVector = null;
  18353. var maxVector = null;
  18354. for (var i in meshes) {
  18355. var mesh = meshes[i];
  18356. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18357. if (!minVector) {
  18358. minVector = boundingBox.minimumWorld;
  18359. maxVector = boundingBox.maximumWorld;
  18360. continue;
  18361. }
  18362. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18363. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18364. }
  18365. return {
  18366. min: minVector,
  18367. max: maxVector
  18368. };
  18369. };
  18370. Mesh.Center = function (meshesOrMinMaxVector) {
  18371. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18372. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18373. };
  18374. /**
  18375. * Merge the array of meshes into a single mesh for performance reasons.
  18376. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18377. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18378. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18379. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18380. */
  18381. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18382. if (disposeSource === void 0) { disposeSource = true; }
  18383. var index;
  18384. if (!allow32BitsIndices) {
  18385. var totalVertices = 0;
  18386. // Counting vertices
  18387. for (index = 0; index < meshes.length; index++) {
  18388. if (meshes[index]) {
  18389. totalVertices += meshes[index].getTotalVertices();
  18390. if (totalVertices > 65536) {
  18391. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18392. return null;
  18393. }
  18394. }
  18395. }
  18396. }
  18397. // Merge
  18398. var vertexData;
  18399. var otherVertexData;
  18400. var source;
  18401. for (index = 0; index < meshes.length; index++) {
  18402. if (meshes[index]) {
  18403. meshes[index].computeWorldMatrix(true);
  18404. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18405. otherVertexData.transform(meshes[index].getWorldMatrix());
  18406. if (vertexData) {
  18407. vertexData.merge(otherVertexData);
  18408. }
  18409. else {
  18410. vertexData = otherVertexData;
  18411. source = meshes[index];
  18412. }
  18413. }
  18414. }
  18415. if (!meshSubclass) {
  18416. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18417. }
  18418. vertexData.applyToMesh(meshSubclass);
  18419. // Setting properties
  18420. meshSubclass.material = source.material;
  18421. meshSubclass.checkCollisions = source.checkCollisions;
  18422. // Cleaning
  18423. if (disposeSource) {
  18424. for (index = 0; index < meshes.length; index++) {
  18425. if (meshes[index]) {
  18426. meshes[index].dispose();
  18427. }
  18428. }
  18429. }
  18430. return meshSubclass;
  18431. };
  18432. // Consts
  18433. Mesh._FRONTSIDE = 0;
  18434. Mesh._BACKSIDE = 1;
  18435. Mesh._DOUBLESIDE = 2;
  18436. Mesh._DEFAULTSIDE = 0;
  18437. Mesh._NO_CAP = 0;
  18438. Mesh._CAP_START = 1;
  18439. Mesh._CAP_END = 2;
  18440. Mesh._CAP_ALL = 3;
  18441. return Mesh;
  18442. })(BABYLON.AbstractMesh);
  18443. BABYLON.Mesh = Mesh;
  18444. })(BABYLON || (BABYLON = {}));
  18445. var BABYLON;
  18446. (function (BABYLON) {
  18447. var SubMesh = (function () {
  18448. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18449. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18450. this.materialIndex = materialIndex;
  18451. this.verticesStart = verticesStart;
  18452. this.verticesCount = verticesCount;
  18453. this.indexStart = indexStart;
  18454. this.indexCount = indexCount;
  18455. this._renderId = 0;
  18456. this._mesh = mesh;
  18457. this._renderingMesh = renderingMesh || mesh;
  18458. mesh.subMeshes.push(this);
  18459. this._trianglePlanes = [];
  18460. this._id = mesh.subMeshes.length - 1;
  18461. if (createBoundingBox) {
  18462. this.refreshBoundingInfo();
  18463. mesh.computeWorldMatrix(true);
  18464. }
  18465. }
  18466. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18467. get: function () {
  18468. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. SubMesh.prototype.getBoundingInfo = function () {
  18474. if (this.IsGlobal) {
  18475. return this._mesh.getBoundingInfo();
  18476. }
  18477. return this._boundingInfo;
  18478. };
  18479. SubMesh.prototype.getMesh = function () {
  18480. return this._mesh;
  18481. };
  18482. SubMesh.prototype.getRenderingMesh = function () {
  18483. return this._renderingMesh;
  18484. };
  18485. SubMesh.prototype.getMaterial = function () {
  18486. var rootMaterial = this._renderingMesh.material;
  18487. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18488. var multiMaterial = rootMaterial;
  18489. return multiMaterial.getSubMaterial(this.materialIndex);
  18490. }
  18491. if (!rootMaterial) {
  18492. return this._mesh.getScene().defaultMaterial;
  18493. }
  18494. return rootMaterial;
  18495. };
  18496. // Methods
  18497. SubMesh.prototype.refreshBoundingInfo = function () {
  18498. this._lastColliderWorldVertices = null;
  18499. if (this.IsGlobal) {
  18500. return;
  18501. }
  18502. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18503. if (!data) {
  18504. this._boundingInfo = this._mesh._boundingInfo;
  18505. return;
  18506. }
  18507. var indices = this._renderingMesh.getIndices();
  18508. var extend;
  18509. //is this the only submesh?
  18510. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18511. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18512. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18513. }
  18514. else {
  18515. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  18516. }
  18517. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18518. };
  18519. SubMesh.prototype._checkCollision = function (collider) {
  18520. return this.getBoundingInfo()._checkCollision(collider);
  18521. };
  18522. SubMesh.prototype.updateBoundingInfo = function (world) {
  18523. if (!this.getBoundingInfo()) {
  18524. this.refreshBoundingInfo();
  18525. }
  18526. this.getBoundingInfo().update(world);
  18527. };
  18528. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  18529. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  18530. };
  18531. SubMesh.prototype.render = function (enableAlphaMode) {
  18532. this._renderingMesh.render(this, enableAlphaMode);
  18533. };
  18534. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  18535. if (!this._linesIndexBuffer) {
  18536. var linesIndices = [];
  18537. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18538. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  18539. }
  18540. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  18541. this.linesIndexCount = linesIndices.length;
  18542. }
  18543. return this._linesIndexBuffer;
  18544. };
  18545. SubMesh.prototype.canIntersects = function (ray) {
  18546. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  18547. };
  18548. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  18549. var intersectInfo = null;
  18550. // Triangles test
  18551. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18552. var p0 = positions[indices[index]];
  18553. var p1 = positions[indices[index + 1]];
  18554. var p2 = positions[indices[index + 2]];
  18555. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  18556. if (currentIntersectInfo) {
  18557. if (currentIntersectInfo.distance < 0) {
  18558. continue;
  18559. }
  18560. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18561. intersectInfo = currentIntersectInfo;
  18562. intersectInfo.faceId = index / 3;
  18563. if (fastCheck) {
  18564. break;
  18565. }
  18566. }
  18567. }
  18568. }
  18569. return intersectInfo;
  18570. };
  18571. // Clone
  18572. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  18573. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  18574. if (!this.IsGlobal) {
  18575. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  18576. }
  18577. return result;
  18578. };
  18579. // Dispose
  18580. SubMesh.prototype.dispose = function () {
  18581. if (this._linesIndexBuffer) {
  18582. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  18583. this._linesIndexBuffer = null;
  18584. }
  18585. // Remove from mesh
  18586. var index = this._mesh.subMeshes.indexOf(this);
  18587. this._mesh.subMeshes.splice(index, 1);
  18588. };
  18589. // Statics
  18590. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  18591. var minVertexIndex = Number.MAX_VALUE;
  18592. var maxVertexIndex = -Number.MAX_VALUE;
  18593. renderingMesh = renderingMesh || mesh;
  18594. var indices = renderingMesh.getIndices();
  18595. for (var index = startIndex; index < startIndex + indexCount; index++) {
  18596. var vertexIndex = indices[index];
  18597. if (vertexIndex < minVertexIndex)
  18598. minVertexIndex = vertexIndex;
  18599. if (vertexIndex > maxVertexIndex)
  18600. maxVertexIndex = vertexIndex;
  18601. }
  18602. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  18603. };
  18604. return SubMesh;
  18605. })();
  18606. BABYLON.SubMesh = SubMesh;
  18607. })(BABYLON || (BABYLON = {}));
  18608. var BABYLON;
  18609. (function (BABYLON) {
  18610. var MeshBuilder = (function () {
  18611. function MeshBuilder() {
  18612. }
  18613. /**
  18614. * Creates a box mesh.
  18615. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  18616. * The parameter `size` sets the size (float) of each box side (default 1).
  18617. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  18618. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  18619. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18623. */
  18624. MeshBuilder.CreateBox = function (name, options, scene) {
  18625. var box = new BABYLON.Mesh(name, scene);
  18626. var vertexData = BABYLON.VertexData.CreateBox(options);
  18627. vertexData.applyToMesh(box, options.updatable);
  18628. return box;
  18629. };
  18630. /**
  18631. * Creates a sphere mesh.
  18632. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  18633. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18634. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  18635. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18636. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  18637. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  18638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18641. */
  18642. MeshBuilder.CreateSphere = function (name, options, scene) {
  18643. var sphere = new BABYLON.Mesh(name, scene);
  18644. var vertexData = BABYLON.VertexData.CreateSphere(options);
  18645. vertexData.applyToMesh(sphere, options.updatable);
  18646. return sphere;
  18647. };
  18648. /**
  18649. * Creates a plane polygonal mesh. By default, this is a disc.
  18650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  18651. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18652. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  18653. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  18654. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18657. */
  18658. MeshBuilder.CreateDisc = function (name, options, scene) {
  18659. var disc = new BABYLON.Mesh(name, scene);
  18660. var vertexData = BABYLON.VertexData.CreateDisc(options);
  18661. vertexData.applyToMesh(disc, options.updatable);
  18662. return disc;
  18663. };
  18664. /**
  18665. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  18667. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18668. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  18669. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18670. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  18671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18674. */
  18675. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  18676. var sphere = new BABYLON.Mesh(name, scene);
  18677. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  18678. vertexData.applyToMesh(sphere, options.updatable);
  18679. return sphere;
  18680. };
  18681. ;
  18682. /**
  18683. * Creates a ribbon mesh.
  18684. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18685. *
  18686. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18687. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18688. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18689. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18690. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18691. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18692. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  18693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18696. */
  18697. MeshBuilder.CreateRibbon = function (name, options, scene) {
  18698. var pathArray = options.pathArray;
  18699. var closeArray = options.closeArray;
  18700. var closePath = options.closePath;
  18701. var offset = options.offset;
  18702. var sideOrientation = options.sideOrientation;
  18703. var instance = options.instance;
  18704. var updatable = options.updatable;
  18705. if (instance) {
  18706. // positionFunction : ribbon case
  18707. // only pathArray and sideOrientation parameters are taken into account for positions update
  18708. var positionFunction = function (positions) {
  18709. var minlg = pathArray[0].length;
  18710. var i = 0;
  18711. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  18712. for (var si = 1; si <= ns; si++) {
  18713. for (var p = 0; p < pathArray.length; p++) {
  18714. var path = pathArray[p];
  18715. var l = path.length;
  18716. minlg = (minlg < l) ? minlg : l;
  18717. var j = 0;
  18718. while (j < minlg) {
  18719. positions[i] = path[j].x;
  18720. positions[i + 1] = path[j].y;
  18721. positions[i + 2] = path[j].z;
  18722. j++;
  18723. i += 3;
  18724. }
  18725. if (instance._closePath) {
  18726. positions[i] = path[0].x;
  18727. positions[i + 1] = path[0].y;
  18728. positions[i + 2] = path[0].z;
  18729. i += 3;
  18730. }
  18731. }
  18732. }
  18733. };
  18734. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18735. positionFunction(positions);
  18736. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18737. if (!(instance.areNormalsFrozen)) {
  18738. var indices = instance.getIndices();
  18739. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18740. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18741. if (instance._closePath) {
  18742. var indexFirst = 0;
  18743. var indexLast = 0;
  18744. for (var p = 0; p < pathArray.length; p++) {
  18745. indexFirst = instance._idx[p] * 3;
  18746. if (p + 1 < pathArray.length) {
  18747. indexLast = (instance._idx[p + 1] - 1) * 3;
  18748. }
  18749. else {
  18750. indexLast = normals.length - 3;
  18751. }
  18752. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  18753. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  18754. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  18755. normals[indexLast] = normals[indexFirst];
  18756. normals[indexLast + 1] = normals[indexFirst + 1];
  18757. normals[indexLast + 2] = normals[indexFirst + 2];
  18758. }
  18759. }
  18760. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18761. }
  18762. return instance;
  18763. }
  18764. else {
  18765. var ribbon = new BABYLON.Mesh(name, scene);
  18766. ribbon.sideOrientation = sideOrientation;
  18767. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  18768. if (closePath) {
  18769. ribbon._idx = vertexData._idx;
  18770. }
  18771. ribbon._closePath = closePath;
  18772. ribbon._closeArray = closeArray;
  18773. vertexData.applyToMesh(ribbon, updatable);
  18774. return ribbon;
  18775. }
  18776. };
  18777. /**
  18778. * Creates a cylinder or a cone mesh.
  18779. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  18780. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18781. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18782. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  18783. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18784. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18785. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  18786. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  18787. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  18788. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  18789. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  18790. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  18791. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  18792. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  18793. * If `enclose` is false, a ring surface is one element.
  18794. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  18795. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  18796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18799. */
  18800. MeshBuilder.CreateCylinder = function (name, options, scene) {
  18801. var cylinder = new BABYLON.Mesh(name, scene);
  18802. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  18803. vertexData.applyToMesh(cylinder, options.updatable);
  18804. return cylinder;
  18805. };
  18806. /**
  18807. * Creates a torus mesh.
  18808. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  18809. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18810. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18811. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18815. */
  18816. MeshBuilder.CreateTorus = function (name, options, scene) {
  18817. var torus = new BABYLON.Mesh(name, scene);
  18818. var vertexData = BABYLON.VertexData.CreateTorus(options);
  18819. vertexData.applyToMesh(torus, options.updatable);
  18820. return torus;
  18821. };
  18822. /**
  18823. * Creates a torus knot mesh.
  18824. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  18825. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18826. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18827. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18828. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18832. */
  18833. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  18834. var torusKnot = new BABYLON.Mesh(name, scene);
  18835. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  18836. vertexData.applyToMesh(torusKnot, options.updatable);
  18837. return torusKnot;
  18838. };
  18839. /**
  18840. * Creates a line system mesh.
  18841. * A line system is a pool of many lines gathered in a single mesh.
  18842. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  18843. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  18844. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  18845. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  18846. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  18847. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18848. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  18849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18850. */
  18851. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  18852. var instance = options.instance;
  18853. var lines = options.lines;
  18854. if (instance) {
  18855. var positionFunction = function (positions) {
  18856. var i = 0;
  18857. for (var l = 0; l < lines.length; l++) {
  18858. var points = lines[l];
  18859. for (var p = 0; p < points.length; p++) {
  18860. positions[i] = points[p].x;
  18861. positions[i + 1] = points[p].y;
  18862. positions[i + 2] = points[p].z;
  18863. i += 3;
  18864. }
  18865. }
  18866. };
  18867. instance.updateMeshPositions(positionFunction, false);
  18868. return instance;
  18869. }
  18870. // line system creation
  18871. var lineSystem = new BABYLON.LinesMesh(name, scene);
  18872. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  18873. vertexData.applyToMesh(lineSystem, options.updatable);
  18874. return lineSystem;
  18875. };
  18876. /**
  18877. * Creates a line mesh.
  18878. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  18879. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18880. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18881. * The parameter `points` is an array successive Vector3.
  18882. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18883. * When updating an instance, remember that only point positions can change, not the number of points.
  18884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18885. */
  18886. MeshBuilder.CreateLines = function (name, options, scene) {
  18887. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  18888. return lines;
  18889. };
  18890. /**
  18891. * Creates a dashed line mesh.
  18892. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  18893. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18894. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18895. * The parameter `points` is an array successive Vector3.
  18896. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18897. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18898. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18899. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18900. * When updating an instance, remember that only point positions can change, not the number of points.
  18901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18902. */
  18903. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  18904. var points = options.points;
  18905. var instance = options.instance;
  18906. var gapSize = options.gapSize;
  18907. var dashNb = options.dashNb;
  18908. var dashSize = options.dashSize;
  18909. if (instance) {
  18910. var positionFunction = function (positions) {
  18911. var curvect = BABYLON.Vector3.Zero();
  18912. var nbSeg = positions.length / 6;
  18913. var lg = 0;
  18914. var nb = 0;
  18915. var shft = 0;
  18916. var dashshft = 0;
  18917. var curshft = 0;
  18918. var p = 0;
  18919. var i = 0;
  18920. var j = 0;
  18921. for (i = 0; i < points.length - 1; i++) {
  18922. points[i + 1].subtractToRef(points[i], curvect);
  18923. lg += curvect.length();
  18924. }
  18925. shft = lg / nbSeg;
  18926. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  18927. for (i = 0; i < points.length - 1; i++) {
  18928. points[i + 1].subtractToRef(points[i], curvect);
  18929. nb = Math.floor(curvect.length() / shft);
  18930. curvect.normalize();
  18931. j = 0;
  18932. while (j < nb && p < positions.length) {
  18933. curshft = shft * j;
  18934. positions[p] = points[i].x + curshft * curvect.x;
  18935. positions[p + 1] = points[i].y + curshft * curvect.y;
  18936. positions[p + 2] = points[i].z + curshft * curvect.z;
  18937. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  18938. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  18939. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  18940. p += 6;
  18941. j++;
  18942. }
  18943. }
  18944. while (p < positions.length) {
  18945. positions[p] = points[i].x;
  18946. positions[p + 1] = points[i].y;
  18947. positions[p + 2] = points[i].z;
  18948. p += 3;
  18949. }
  18950. };
  18951. instance.updateMeshPositions(positionFunction, false);
  18952. return instance;
  18953. }
  18954. // dashed lines creation
  18955. var dashedLines = new BABYLON.LinesMesh(name, scene);
  18956. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  18957. vertexData.applyToMesh(dashedLines, options.updatable);
  18958. dashedLines.dashSize = dashSize;
  18959. dashedLines.gapSize = gapSize;
  18960. return dashedLines;
  18961. };
  18962. /**
  18963. * Creates an extruded shape mesh.
  18964. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18965. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  18966. *
  18967. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18968. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18969. * extruded along the Z axis.
  18970. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18971. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18972. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18973. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18974. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18975. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18979. */
  18980. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  18981. var path = options.path;
  18982. var shape = options.shape;
  18983. var scale = options.scale || 1;
  18984. var rotation = options.rotation || 0;
  18985. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  18986. var updatable = options.updatable;
  18987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  18988. var instance = options.instance;
  18989. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  18990. };
  18991. /**
  18992. * Creates an custom extruded shape mesh.
  18993. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18994. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  18995. *
  18996. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18997. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18998. * extruded along the Z axis.
  18999. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19000. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19001. * and the distance of this point from the begining of the path :
  19002. * ```rotationFunction = function(i, distance) {
  19003. * // do things
  19004. * return rotationValue; }```
  19005. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19006. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19007. * and the distance of this point from the begining of the path :
  19008. * ````scaleFunction = function(i, distance) {
  19009. * // do things
  19010. * return scaleValue;}```
  19011. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19012. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19013. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19014. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19015. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19016. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19020. */
  19021. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19022. var path = options.path;
  19023. var shape = options.shape;
  19024. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19025. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19026. var ribbonCloseArray = options.ribbonCloseArray || false;
  19027. var ribbonClosePath = options.ribbonClosePath || false;
  19028. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19029. var updatable = options.updatable;
  19030. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19031. var instance = options.instance;
  19032. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19033. };
  19034. /**
  19035. * Creates lathe mesh.
  19036. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19037. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19038. *
  19039. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19040. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19041. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19042. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19043. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  19044. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19045. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19049. */
  19050. MeshBuilder.CreateLathe = function (name, options, scene) {
  19051. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19052. var closed = (options.closed === undefined) ? true : options.closed;
  19053. var shape = options.shape;
  19054. var radius = options.radius || 1;
  19055. var tessellation = options.tessellation || 64;
  19056. var updatable = options.updatable;
  19057. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19058. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19059. var pi2 = Math.PI * 2;
  19060. var paths = new Array();
  19061. var i = 0;
  19062. var p = 0;
  19063. var step = pi2 / tessellation * arc;
  19064. var rotated;
  19065. var path = new Array();
  19066. ;
  19067. for (i = 0; i <= tessellation; i++) {
  19068. var path = [];
  19069. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19070. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19071. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19072. }
  19073. for (p = 0; p < shape.length; p++) {
  19074. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19075. path.push(rotated);
  19076. }
  19077. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19078. 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));
  19079. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19080. }
  19081. paths.push(path);
  19082. }
  19083. // lathe ribbon
  19084. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19085. return lathe;
  19086. };
  19087. /**
  19088. * Creates a plane mesh.
  19089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19090. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19091. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19092. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19094. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19096. */
  19097. MeshBuilder.CreatePlane = function (name, options, scene) {
  19098. var plane = new BABYLON.Mesh(name, scene);
  19099. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19100. vertexData.applyToMesh(plane, options.updatable);
  19101. if (options.sourcePlane) {
  19102. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19103. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19104. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19105. plane.rotate(vectorProduct, product);
  19106. }
  19107. return plane;
  19108. };
  19109. /**
  19110. * Creates a ground mesh.
  19111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19112. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19113. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19115. */
  19116. MeshBuilder.CreateGround = function (name, options, scene) {
  19117. var ground = new BABYLON.GroundMesh(name, scene);
  19118. ground._setReady(false);
  19119. ground._subdivisions = options.subdivisions || 1;
  19120. ground._width = options.width || 1;
  19121. ground._height = options.height || 1;
  19122. ground._maxX = ground._width / 2;
  19123. ground._maxZ = ground._height / 2;
  19124. ground._minX = -ground._maxX;
  19125. ground._minZ = -ground._maxZ;
  19126. var vertexData = BABYLON.VertexData.CreateGround(options);
  19127. vertexData.applyToMesh(ground, options.updatable);
  19128. ground._setReady(true);
  19129. return ground;
  19130. };
  19131. /**
  19132. * Creates a tiled ground mesh.
  19133. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19134. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19135. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19136. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19137. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19138. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19139. * numbers of subdivisions on the ground width and height of each tile.
  19140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19141. */
  19142. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19143. var tiledGround = new BABYLON.Mesh(name, scene);
  19144. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19145. vertexData.applyToMesh(tiledGround, options.updatable);
  19146. return tiledGround;
  19147. };
  19148. /**
  19149. * Creates a ground mesh from a height map.
  19150. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19151. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19152. * The parameter `url` sets the URL of the height map image resource.
  19153. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19154. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19155. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19156. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19157. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19158. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19159. * return; }```
  19160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19161. */
  19162. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19163. var width = options.width || 10;
  19164. var height = options.height || 10;
  19165. var subdivisions = options.subdivisions || 1;
  19166. var minHeight = options.minHeight;
  19167. var maxHeight = options.maxHeight || 10;
  19168. var updatable = options.updatable;
  19169. var onReady = options.onReady;
  19170. var ground = new BABYLON.GroundMesh(name, scene);
  19171. ground._subdivisions = subdivisions;
  19172. ground._width = width;
  19173. ground._height = height;
  19174. ground._maxX = ground._width / 2;
  19175. ground._maxZ = ground._height / 2;
  19176. ground._minX = -ground._maxX;
  19177. ground._minZ = -ground._maxZ;
  19178. ground._setReady(false);
  19179. var onload = function (img) {
  19180. // Getting height map data
  19181. var canvas = document.createElement("canvas");
  19182. var context = canvas.getContext("2d");
  19183. var bufferWidth = img.width;
  19184. var bufferHeight = img.height;
  19185. canvas.width = bufferWidth;
  19186. canvas.height = bufferHeight;
  19187. context.drawImage(img, 0, 0);
  19188. // Create VertexData from map data
  19189. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19190. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19191. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19192. width: width, height: height,
  19193. subdivisions: subdivisions,
  19194. minHeight: minHeight, maxHeight: maxHeight,
  19195. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19196. });
  19197. vertexData.applyToMesh(ground, updatable);
  19198. ground._setReady(true);
  19199. //execute ready callback, if set
  19200. if (onReady) {
  19201. onReady(ground);
  19202. }
  19203. };
  19204. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19205. return ground;
  19206. };
  19207. /**
  19208. * Creates a tube mesh.
  19209. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19210. *
  19211. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19212. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19213. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19214. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19215. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19216. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19217. * It must return a radius value (positive float) :
  19218. * ```var radiusFunction = function(i, distance) {
  19219. * // do things
  19220. * return radius; }```
  19221. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19222. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19223. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19227. */
  19228. MeshBuilder.CreateTube = function (name, options, scene) {
  19229. var path = options.path;
  19230. var radius = options.radius || 1;
  19231. var tessellation = options.tessellation || 64;
  19232. var radiusFunction = options.radiusFunction;
  19233. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19234. var updatable = options.updatable;
  19235. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19236. var instance = options.instance;
  19237. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19238. // tube geometry
  19239. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19240. var tangents = path3D.getTangents();
  19241. var normals = path3D.getNormals();
  19242. var distances = path3D.getDistances();
  19243. var pi2 = Math.PI * 2;
  19244. var step = pi2 / tessellation * arc;
  19245. var returnRadius = function () { return radius; };
  19246. var radiusFunctionFinal = radiusFunction || returnRadius;
  19247. var circlePath;
  19248. var rad;
  19249. var normal;
  19250. var rotated;
  19251. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19252. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19253. for (var i = 0; i < path.length; i++) {
  19254. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19255. circlePath = Array(); // current circle array
  19256. normal = normals[i]; // current normal
  19257. for (var t = 0; t < tessellation; t++) {
  19258. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19259. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19260. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19261. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19262. circlePath[t] = rotated;
  19263. }
  19264. circlePaths[index] = circlePath;
  19265. index++;
  19266. }
  19267. // cap
  19268. var capPath = function (nbPoints, pathIndex) {
  19269. var pointCap = Array();
  19270. for (var i = 0; i < nbPoints; i++) {
  19271. pointCap.push(path[pathIndex]);
  19272. }
  19273. return pointCap;
  19274. };
  19275. switch (cap) {
  19276. case BABYLON.Mesh.NO_CAP:
  19277. break;
  19278. case BABYLON.Mesh.CAP_START:
  19279. circlePaths[0] = capPath(tessellation, 0);
  19280. circlePaths[1] = circlePaths[2].slice(0);
  19281. break;
  19282. case BABYLON.Mesh.CAP_END:
  19283. circlePaths[index] = circlePaths[index - 1].slice(0);
  19284. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19285. break;
  19286. case BABYLON.Mesh.CAP_ALL:
  19287. circlePaths[0] = capPath(tessellation, 0);
  19288. circlePaths[1] = circlePaths[2].slice(0);
  19289. circlePaths[index] = circlePaths[index - 1].slice(0);
  19290. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19291. break;
  19292. default:
  19293. break;
  19294. }
  19295. return circlePaths;
  19296. };
  19297. var path3D;
  19298. var pathArray;
  19299. if (instance) {
  19300. var arc = options.arc || instance.arc;
  19301. path3D = (instance.path3D).update(path);
  19302. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19303. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19304. instance.path3D = path3D;
  19305. instance.pathArray = pathArray;
  19306. instance.arc = arc;
  19307. return instance;
  19308. }
  19309. // tube creation
  19310. path3D = new BABYLON.Path3D(path);
  19311. var newPathArray = new Array();
  19312. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19313. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19314. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19315. tube.pathArray = pathArray;
  19316. tube.path3D = path3D;
  19317. tube.tessellation = tessellation;
  19318. tube.cap = cap;
  19319. tube.arc = options.arc;
  19320. return tube;
  19321. };
  19322. /**
  19323. * Creates a polyhedron mesh.
  19324. *
  19325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19326. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19327. * to choose the wanted type.
  19328. * The parameter `size` (positive float, default 1) sets the polygon size.
  19329. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19330. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19331. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19332. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  19333. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19334. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19338. */
  19339. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19340. var polyhedron = new BABYLON.Mesh(name, scene);
  19341. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19342. vertexData.applyToMesh(polyhedron, options.updatable);
  19343. return polyhedron;
  19344. };
  19345. /**
  19346. * Creates a decal mesh.
  19347. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19348. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19349. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19350. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19351. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19352. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19353. */
  19354. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19355. var indices = sourceMesh.getIndices();
  19356. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19357. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19358. var position = options.position || BABYLON.Vector3.Zero();
  19359. var normal = options.normal || BABYLON.Vector3.Up();
  19360. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19361. var angle = options.angle || 0;
  19362. // Getting correct rotation
  19363. if (!normal) {
  19364. var target = new BABYLON.Vector3(0, 0, 1);
  19365. var camera = sourceMesh.getScene().activeCamera;
  19366. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19367. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19368. }
  19369. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19370. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19371. var pitch = Math.atan2(normal.y, len);
  19372. // Matrix
  19373. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19374. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19375. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19376. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19377. var vertexData = new BABYLON.VertexData();
  19378. vertexData.indices = [];
  19379. vertexData.positions = [];
  19380. vertexData.normals = [];
  19381. vertexData.uvs = [];
  19382. var currentVertexDataIndex = 0;
  19383. var extractDecalVector3 = function (indexId) {
  19384. var vertexId = indices[indexId];
  19385. var result = new BABYLON.PositionNormalVertex();
  19386. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19387. // Send vector to decal local world
  19388. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19389. // Get normal
  19390. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19391. return result;
  19392. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19393. var clip = function (vertices, axis) {
  19394. if (vertices.length === 0) {
  19395. return vertices;
  19396. }
  19397. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19398. var clipVertices = function (v0, v1) {
  19399. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19400. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19401. };
  19402. var result = new Array();
  19403. for (var index = 0; index < vertices.length; index += 3) {
  19404. var v1Out;
  19405. var v2Out;
  19406. var v3Out;
  19407. var total = 0;
  19408. var nV1, nV2, nV3, nV4;
  19409. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19410. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19411. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19412. v1Out = d1 > 0;
  19413. v2Out = d2 > 0;
  19414. v3Out = d3 > 0;
  19415. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19416. switch (total) {
  19417. case 0:
  19418. result.push(vertices[index]);
  19419. result.push(vertices[index + 1]);
  19420. result.push(vertices[index + 2]);
  19421. break;
  19422. case 1:
  19423. if (v1Out) {
  19424. nV1 = vertices[index + 1];
  19425. nV2 = vertices[index + 2];
  19426. nV3 = clipVertices(vertices[index], nV1);
  19427. nV4 = clipVertices(vertices[index], nV2);
  19428. }
  19429. if (v2Out) {
  19430. nV1 = vertices[index];
  19431. nV2 = vertices[index + 2];
  19432. nV3 = clipVertices(vertices[index + 1], nV1);
  19433. nV4 = clipVertices(vertices[index + 1], nV2);
  19434. result.push(nV3);
  19435. result.push(nV2.clone());
  19436. result.push(nV1.clone());
  19437. result.push(nV2.clone());
  19438. result.push(nV3.clone());
  19439. result.push(nV4);
  19440. break;
  19441. }
  19442. if (v3Out) {
  19443. nV1 = vertices[index];
  19444. nV2 = vertices[index + 1];
  19445. nV3 = clipVertices(vertices[index + 2], nV1);
  19446. nV4 = clipVertices(vertices[index + 2], nV2);
  19447. }
  19448. result.push(nV1.clone());
  19449. result.push(nV2.clone());
  19450. result.push(nV3);
  19451. result.push(nV4);
  19452. result.push(nV3.clone());
  19453. result.push(nV2.clone());
  19454. break;
  19455. case 2:
  19456. if (!v1Out) {
  19457. nV1 = vertices[index].clone();
  19458. nV2 = clipVertices(nV1, vertices[index + 1]);
  19459. nV3 = clipVertices(nV1, vertices[index + 2]);
  19460. result.push(nV1);
  19461. result.push(nV2);
  19462. result.push(nV3);
  19463. }
  19464. if (!v2Out) {
  19465. nV1 = vertices[index + 1].clone();
  19466. nV2 = clipVertices(nV1, vertices[index + 2]);
  19467. nV3 = clipVertices(nV1, vertices[index]);
  19468. result.push(nV1);
  19469. result.push(nV2);
  19470. result.push(nV3);
  19471. }
  19472. if (!v3Out) {
  19473. nV1 = vertices[index + 2].clone();
  19474. nV2 = clipVertices(nV1, vertices[index]);
  19475. nV3 = clipVertices(nV1, vertices[index + 1]);
  19476. result.push(nV1);
  19477. result.push(nV2);
  19478. result.push(nV3);
  19479. }
  19480. break;
  19481. case 3:
  19482. break;
  19483. }
  19484. }
  19485. return result;
  19486. };
  19487. for (var index = 0; index < indices.length; index += 3) {
  19488. var faceVertices = new Array();
  19489. faceVertices.push(extractDecalVector3(index));
  19490. faceVertices.push(extractDecalVector3(index + 1));
  19491. faceVertices.push(extractDecalVector3(index + 2));
  19492. // Clip
  19493. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  19494. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  19495. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  19496. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  19497. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  19498. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  19499. if (faceVertices.length === 0) {
  19500. continue;
  19501. }
  19502. // Add UVs and get back to world
  19503. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  19504. var vertex = faceVertices[vIndex];
  19505. //TODO check for Int32Array
  19506. vertexData.indices.push(currentVertexDataIndex);
  19507. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  19508. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  19509. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  19510. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  19511. currentVertexDataIndex++;
  19512. }
  19513. }
  19514. // Return mesh
  19515. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  19516. vertexData.applyToMesh(decal);
  19517. decal.position = position.clone();
  19518. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  19519. return decal;
  19520. };
  19521. // Privates
  19522. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  19523. // extrusion geometry
  19524. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  19525. var tangents = path3D.getTangents();
  19526. var normals = path3D.getNormals();
  19527. var binormals = path3D.getBinormals();
  19528. var distances = path3D.getDistances();
  19529. var angle = 0;
  19530. var returnScale = function () { return scale; };
  19531. var returnRotation = function () { return rotation; };
  19532. var rotate = custom ? rotateFunction : returnRotation;
  19533. var scl = custom ? scaleFunction : returnScale;
  19534. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19535. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19536. for (var i = 0; i < curve.length; i++) {
  19537. var shapePath = new Array();
  19538. var angleStep = rotate(i, distances[i]);
  19539. var scaleRatio = scl(i, distances[i]);
  19540. for (var p = 0; p < shape.length; p++) {
  19541. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  19542. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  19543. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  19544. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  19545. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  19546. shapePath[p] = rotated;
  19547. }
  19548. shapePaths[index] = shapePath;
  19549. angle += angleStep;
  19550. index++;
  19551. }
  19552. // cap
  19553. var capPath = function (shapePath) {
  19554. var pointCap = Array();
  19555. var barycenter = BABYLON.Vector3.Zero();
  19556. var i;
  19557. for (i = 0; i < shapePath.length; i++) {
  19558. barycenter.addInPlace(shapePath[i]);
  19559. }
  19560. barycenter.scaleInPlace(1 / shapePath.length);
  19561. for (i = 0; i < shapePath.length; i++) {
  19562. pointCap.push(barycenter);
  19563. }
  19564. return pointCap;
  19565. };
  19566. switch (cap) {
  19567. case BABYLON.Mesh.NO_CAP:
  19568. break;
  19569. case BABYLON.Mesh.CAP_START:
  19570. shapePaths[0] = capPath(shapePaths[2]);
  19571. shapePaths[1] = shapePaths[2].slice(0);
  19572. break;
  19573. case BABYLON.Mesh.CAP_END:
  19574. shapePaths[index] = shapePaths[index - 1];
  19575. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19576. break;
  19577. case BABYLON.Mesh.CAP_ALL:
  19578. shapePaths[0] = capPath(shapePaths[2]);
  19579. shapePaths[1] = shapePaths[2].slice(0);
  19580. shapePaths[index] = shapePaths[index - 1];
  19581. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19582. break;
  19583. default:
  19584. break;
  19585. }
  19586. return shapePaths;
  19587. };
  19588. var path3D;
  19589. var pathArray;
  19590. if (instance) {
  19591. path3D = (instance.path3D).update(curve);
  19592. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  19593. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  19594. return instance;
  19595. }
  19596. // extruded shape creation
  19597. path3D = new BABYLON.Path3D(curve);
  19598. var newShapePaths = new Array();
  19599. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19600. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  19601. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  19602. extrudedGeneric.pathArray = pathArray;
  19603. extrudedGeneric.path3D = path3D;
  19604. extrudedGeneric.cap = cap;
  19605. return extrudedGeneric;
  19606. };
  19607. return MeshBuilder;
  19608. })();
  19609. BABYLON.MeshBuilder = MeshBuilder;
  19610. })(BABYLON || (BABYLON = {}));
  19611. var BABYLON;
  19612. (function (BABYLON) {
  19613. var BaseTexture = (function () {
  19614. function BaseTexture(scene) {
  19615. this.hasAlpha = false;
  19616. this.getAlphaFromRGB = false;
  19617. this.level = 1;
  19618. this.coordinatesIndex = 0;
  19619. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19620. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19621. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19622. this.anisotropicFilteringLevel = 4;
  19623. this.isCube = false;
  19624. this.isRenderTarget = false;
  19625. this.animations = new Array();
  19626. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19627. this._scene = scene;
  19628. this._scene.textures.push(this);
  19629. }
  19630. BaseTexture.prototype.getScene = function () {
  19631. return this._scene;
  19632. };
  19633. BaseTexture.prototype.getTextureMatrix = function () {
  19634. return null;
  19635. };
  19636. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19637. return null;
  19638. };
  19639. BaseTexture.prototype.getInternalTexture = function () {
  19640. return this._texture;
  19641. };
  19642. BaseTexture.prototype.isReady = function () {
  19643. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19644. return true;
  19645. }
  19646. if (this._texture) {
  19647. return this._texture.isReady;
  19648. }
  19649. return false;
  19650. };
  19651. BaseTexture.prototype.getSize = function () {
  19652. if (this._texture._width) {
  19653. return { width: this._texture._width, height: this._texture._height };
  19654. }
  19655. if (this._texture._size) {
  19656. return { width: this._texture._size, height: this._texture._size };
  19657. }
  19658. return { width: 0, height: 0 };
  19659. };
  19660. BaseTexture.prototype.getBaseSize = function () {
  19661. if (!this.isReady())
  19662. return { width: 0, height: 0 };
  19663. if (this._texture._size) {
  19664. return { width: this._texture._size, height: this._texture._size };
  19665. }
  19666. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  19667. };
  19668. BaseTexture.prototype.scale = function (ratio) {
  19669. };
  19670. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19671. get: function () {
  19672. return false;
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19678. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19679. for (var index = 0; index < texturesCache.length; index++) {
  19680. var texturesCacheEntry = texturesCache[index];
  19681. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19682. texturesCache.splice(index, 1);
  19683. return;
  19684. }
  19685. }
  19686. };
  19687. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19688. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19689. for (var index = 0; index < texturesCache.length; index++) {
  19690. var texturesCacheEntry = texturesCache[index];
  19691. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19692. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19693. texturesCacheEntry.references++;
  19694. return texturesCacheEntry;
  19695. }
  19696. }
  19697. }
  19698. return null;
  19699. };
  19700. BaseTexture.prototype.delayLoad = function () {
  19701. };
  19702. BaseTexture.prototype.clone = function () {
  19703. return null;
  19704. };
  19705. BaseTexture.prototype.releaseInternalTexture = function () {
  19706. if (this._texture) {
  19707. this._scene.getEngine().releaseInternalTexture(this._texture);
  19708. delete this._texture;
  19709. }
  19710. };
  19711. BaseTexture.prototype.dispose = function () {
  19712. // Animations
  19713. this.getScene().stopAnimation(this);
  19714. // Remove from scene
  19715. var index = this._scene.textures.indexOf(this);
  19716. if (index >= 0) {
  19717. this._scene.textures.splice(index, 1);
  19718. }
  19719. if (this._texture === undefined) {
  19720. return;
  19721. }
  19722. // Release
  19723. this.releaseInternalTexture();
  19724. // Callback
  19725. if (this.onDispose) {
  19726. this.onDispose();
  19727. }
  19728. };
  19729. BaseTexture.prototype.serialize = function () {
  19730. if (!this.name) {
  19731. return null;
  19732. }
  19733. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19734. // Animations
  19735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19736. return serializationObject;
  19737. };
  19738. __decorate([
  19739. BABYLON.serialize()
  19740. ], BaseTexture.prototype, "name", void 0);
  19741. __decorate([
  19742. BABYLON.serialize()
  19743. ], BaseTexture.prototype, "hasAlpha", void 0);
  19744. __decorate([
  19745. BABYLON.serialize()
  19746. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19747. __decorate([
  19748. BABYLON.serialize()
  19749. ], BaseTexture.prototype, "level", void 0);
  19750. __decorate([
  19751. BABYLON.serialize()
  19752. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19753. __decorate([
  19754. BABYLON.serialize()
  19755. ], BaseTexture.prototype, "coordinatesMode", void 0);
  19756. __decorate([
  19757. BABYLON.serialize()
  19758. ], BaseTexture.prototype, "wrapU", void 0);
  19759. __decorate([
  19760. BABYLON.serialize()
  19761. ], BaseTexture.prototype, "wrapV", void 0);
  19762. __decorate([
  19763. BABYLON.serialize()
  19764. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19765. __decorate([
  19766. BABYLON.serialize()
  19767. ], BaseTexture.prototype, "isCube", void 0);
  19768. __decorate([
  19769. BABYLON.serialize()
  19770. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19771. return BaseTexture;
  19772. })();
  19773. BABYLON.BaseTexture = BaseTexture;
  19774. })(BABYLON || (BABYLON = {}));
  19775. var BABYLON;
  19776. (function (BABYLON) {
  19777. var Texture = (function (_super) {
  19778. __extends(Texture, _super);
  19779. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  19780. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19781. if (onLoad === void 0) { onLoad = null; }
  19782. if (onError === void 0) { onError = null; }
  19783. if (buffer === void 0) { buffer = null; }
  19784. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19785. _super.call(this, scene);
  19786. this.uOffset = 0;
  19787. this.vOffset = 0;
  19788. this.uScale = 1.0;
  19789. this.vScale = 1.0;
  19790. this.uAng = 0;
  19791. this.vAng = 0;
  19792. this.wAng = 0;
  19793. this.name = url;
  19794. this.url = url;
  19795. this._noMipmap = noMipmap;
  19796. this._invertY = invertY;
  19797. this._samplingMode = samplingMode;
  19798. this._buffer = buffer;
  19799. this._deleteBuffer = deleteBuffer;
  19800. if (!url) {
  19801. return;
  19802. }
  19803. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  19804. if (!this._texture) {
  19805. if (!scene.useDelayedTextureLoading) {
  19806. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  19807. if (deleteBuffer) {
  19808. delete this._buffer;
  19809. }
  19810. }
  19811. else {
  19812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19813. this._delayedOnLoad = onLoad;
  19814. this._delayedOnError = onError;
  19815. }
  19816. }
  19817. else {
  19818. BABYLON.Tools.SetImmediate(function () {
  19819. if (onLoad) {
  19820. onLoad();
  19821. }
  19822. });
  19823. }
  19824. }
  19825. Texture.prototype.delayLoad = function () {
  19826. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19827. return;
  19828. }
  19829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19830. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19831. if (!this._texture) {
  19832. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  19833. if (this._deleteBuffer) {
  19834. delete this._buffer;
  19835. }
  19836. }
  19837. };
  19838. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19839. if (!this._texture) {
  19840. return;
  19841. }
  19842. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19843. };
  19844. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19845. x *= this.uScale;
  19846. y *= this.vScale;
  19847. x -= 0.5 * this.uScale;
  19848. y -= 0.5 * this.vScale;
  19849. z -= 0.5;
  19850. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19851. t.x += 0.5 * this.uScale + this.uOffset;
  19852. t.y += 0.5 * this.vScale + this.vOffset;
  19853. t.z += 0.5;
  19854. };
  19855. Texture.prototype.getTextureMatrix = function () {
  19856. if (this.uOffset === this._cachedUOffset &&
  19857. this.vOffset === this._cachedVOffset &&
  19858. this.uScale === this._cachedUScale &&
  19859. this.vScale === this._cachedVScale &&
  19860. this.uAng === this._cachedUAng &&
  19861. this.vAng === this._cachedVAng &&
  19862. this.wAng === this._cachedWAng) {
  19863. return this._cachedTextureMatrix;
  19864. }
  19865. this._cachedUOffset = this.uOffset;
  19866. this._cachedVOffset = this.vOffset;
  19867. this._cachedUScale = this.uScale;
  19868. this._cachedVScale = this.vScale;
  19869. this._cachedUAng = this.uAng;
  19870. this._cachedVAng = this.vAng;
  19871. this._cachedWAng = this.wAng;
  19872. if (!this._cachedTextureMatrix) {
  19873. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19874. this._rowGenerationMatrix = new BABYLON.Matrix();
  19875. this._t0 = BABYLON.Vector3.Zero();
  19876. this._t1 = BABYLON.Vector3.Zero();
  19877. this._t2 = BABYLON.Vector3.Zero();
  19878. }
  19879. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19880. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19881. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19882. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19883. this._t1.subtractInPlace(this._t0);
  19884. this._t2.subtractInPlace(this._t0);
  19885. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19886. this._cachedTextureMatrix.m[0] = this._t1.x;
  19887. this._cachedTextureMatrix.m[1] = this._t1.y;
  19888. this._cachedTextureMatrix.m[2] = this._t1.z;
  19889. this._cachedTextureMatrix.m[4] = this._t2.x;
  19890. this._cachedTextureMatrix.m[5] = this._t2.y;
  19891. this._cachedTextureMatrix.m[6] = this._t2.z;
  19892. this._cachedTextureMatrix.m[8] = this._t0.x;
  19893. this._cachedTextureMatrix.m[9] = this._t0.y;
  19894. this._cachedTextureMatrix.m[10] = this._t0.z;
  19895. return this._cachedTextureMatrix;
  19896. };
  19897. Texture.prototype.getReflectionTextureMatrix = function () {
  19898. if (this.uOffset === this._cachedUOffset &&
  19899. this.vOffset === this._cachedVOffset &&
  19900. this.uScale === this._cachedUScale &&
  19901. this.vScale === this._cachedVScale &&
  19902. this.coordinatesMode === this._cachedCoordinatesMode) {
  19903. return this._cachedTextureMatrix;
  19904. }
  19905. if (!this._cachedTextureMatrix) {
  19906. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19907. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19908. }
  19909. this._cachedCoordinatesMode = this.coordinatesMode;
  19910. switch (this.coordinatesMode) {
  19911. case Texture.PLANAR_MODE:
  19912. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19913. this._cachedTextureMatrix[0] = this.uScale;
  19914. this._cachedTextureMatrix[5] = this.vScale;
  19915. this._cachedTextureMatrix[12] = this.uOffset;
  19916. this._cachedTextureMatrix[13] = this.vOffset;
  19917. break;
  19918. case Texture.PROJECTION_MODE:
  19919. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19920. this._projectionModeMatrix.m[0] = 0.5;
  19921. this._projectionModeMatrix.m[5] = -0.5;
  19922. this._projectionModeMatrix.m[10] = 0.0;
  19923. this._projectionModeMatrix.m[12] = 0.5;
  19924. this._projectionModeMatrix.m[13] = 0.5;
  19925. this._projectionModeMatrix.m[14] = 1.0;
  19926. this._projectionModeMatrix.m[15] = 1.0;
  19927. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19928. break;
  19929. default:
  19930. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19931. break;
  19932. }
  19933. return this._cachedTextureMatrix;
  19934. };
  19935. Texture.prototype.clone = function () {
  19936. var _this = this;
  19937. return BABYLON.SerializationHelper.Clone(function () {
  19938. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19939. }, this);
  19940. };
  19941. // Statics
  19942. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  19943. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19944. if (onLoad === void 0) { onLoad = null; }
  19945. if (onError === void 0) { onError = null; }
  19946. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  19947. };
  19948. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19949. if (parsedTexture.isCube) {
  19950. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19951. }
  19952. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19953. return null;
  19954. }
  19955. var texture = BABYLON.SerializationHelper.Parse(function () {
  19956. if (parsedTexture.mirrorPlane) {
  19957. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19958. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19959. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19960. return mirrorTexture;
  19961. }
  19962. else if (parsedTexture.isRenderTarget) {
  19963. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19964. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19965. return renderTargetTexture;
  19966. }
  19967. else {
  19968. var texture;
  19969. if (parsedTexture.base64String) {
  19970. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19971. }
  19972. else {
  19973. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19974. }
  19975. return texture;
  19976. }
  19977. }, parsedTexture, scene);
  19978. // Animations
  19979. if (parsedTexture.animations) {
  19980. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19981. var parsedAnimation = parsedTexture.animations[animationIndex];
  19982. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19983. }
  19984. }
  19985. return texture;
  19986. };
  19987. // Constants
  19988. Texture.NEAREST_SAMPLINGMODE = 1;
  19989. Texture.BILINEAR_SAMPLINGMODE = 2;
  19990. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19991. Texture.EXPLICIT_MODE = 0;
  19992. Texture.SPHERICAL_MODE = 1;
  19993. Texture.PLANAR_MODE = 2;
  19994. Texture.CUBIC_MODE = 3;
  19995. Texture.PROJECTION_MODE = 4;
  19996. Texture.SKYBOX_MODE = 5;
  19997. Texture.INVCUBIC_MODE = 6;
  19998. Texture.EQUIRECTANGULAR_MODE = 7;
  19999. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20000. Texture.CLAMP_ADDRESSMODE = 0;
  20001. Texture.WRAP_ADDRESSMODE = 1;
  20002. Texture.MIRROR_ADDRESSMODE = 2;
  20003. __decorate([
  20004. BABYLON.serialize()
  20005. ], Texture.prototype, "url", void 0);
  20006. __decorate([
  20007. BABYLON.serialize()
  20008. ], Texture.prototype, "uOffset", void 0);
  20009. __decorate([
  20010. BABYLON.serialize()
  20011. ], Texture.prototype, "vOffset", void 0);
  20012. __decorate([
  20013. BABYLON.serialize()
  20014. ], Texture.prototype, "uScale", void 0);
  20015. __decorate([
  20016. BABYLON.serialize()
  20017. ], Texture.prototype, "vScale", void 0);
  20018. __decorate([
  20019. BABYLON.serialize()
  20020. ], Texture.prototype, "uAng", void 0);
  20021. __decorate([
  20022. BABYLON.serialize()
  20023. ], Texture.prototype, "vAng", void 0);
  20024. __decorate([
  20025. BABYLON.serialize()
  20026. ], Texture.prototype, "wAng", void 0);
  20027. return Texture;
  20028. })(BABYLON.BaseTexture);
  20029. BABYLON.Texture = Texture;
  20030. })(BABYLON || (BABYLON = {}));
  20031. var BABYLON;
  20032. (function (BABYLON) {
  20033. var CubeTexture = (function (_super) {
  20034. __extends(CubeTexture, _super);
  20035. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20036. _super.call(this, scene);
  20037. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20038. this.name = rootUrl;
  20039. this.url = rootUrl;
  20040. this._noMipmap = noMipmap;
  20041. this.hasAlpha = false;
  20042. if (!rootUrl && !files) {
  20043. return;
  20044. }
  20045. this._texture = this._getFromCache(rootUrl, noMipmap);
  20046. if (!files) {
  20047. if (!extensions) {
  20048. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20049. }
  20050. files = [];
  20051. for (var index = 0; index < extensions.length; index++) {
  20052. files.push(rootUrl + extensions[index]);
  20053. }
  20054. this._extensions = extensions;
  20055. }
  20056. this._files = files;
  20057. if (!this._texture) {
  20058. if (!scene.useDelayedTextureLoading) {
  20059. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20060. }
  20061. else {
  20062. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20063. }
  20064. }
  20065. this.isCube = true;
  20066. this._textureMatrix = BABYLON.Matrix.Identity();
  20067. }
  20068. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20069. return new CubeTexture("", scene, null, noMipmap, files);
  20070. };
  20071. // Methods
  20072. CubeTexture.prototype.delayLoad = function () {
  20073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20074. return;
  20075. }
  20076. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20077. this._texture = this._getFromCache(this.url, this._noMipmap);
  20078. if (!this._texture) {
  20079. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20080. }
  20081. };
  20082. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20083. return this._textureMatrix;
  20084. };
  20085. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20086. var texture = BABYLON.SerializationHelper.Parse(function () {
  20087. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20088. }, parsedTexture, scene);
  20089. // Animations
  20090. if (parsedTexture.animations) {
  20091. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20092. var parsedAnimation = parsedTexture.animations[animationIndex];
  20093. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20094. }
  20095. }
  20096. return texture;
  20097. };
  20098. CubeTexture.prototype.clone = function () {
  20099. var _this = this;
  20100. return BABYLON.SerializationHelper.Clone(function () {
  20101. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20102. }, this);
  20103. };
  20104. return CubeTexture;
  20105. })(BABYLON.BaseTexture);
  20106. BABYLON.CubeTexture = CubeTexture;
  20107. })(BABYLON || (BABYLON = {}));
  20108. var BABYLON;
  20109. (function (BABYLON) {
  20110. var RenderTargetTexture = (function (_super) {
  20111. __extends(RenderTargetTexture, _super);
  20112. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20113. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20114. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20115. if (isCube === void 0) { isCube = false; }
  20116. _super.call(this, null, scene, !generateMipMaps);
  20117. this.isCube = isCube;
  20118. this.renderList = new Array();
  20119. this.renderParticles = true;
  20120. this.renderSprites = false;
  20121. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20122. this._currentRefreshId = -1;
  20123. this._refreshRate = 1;
  20124. this.name = name;
  20125. this.isRenderTarget = true;
  20126. this._size = size;
  20127. this._generateMipMaps = generateMipMaps;
  20128. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20129. if (isCube) {
  20130. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20131. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20132. this._textureMatrix = BABYLON.Matrix.Identity();
  20133. }
  20134. else {
  20135. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20136. }
  20137. // Rendering groups
  20138. this._renderingManager = new BABYLON.RenderingManager(scene);
  20139. }
  20140. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20141. get: function () {
  20142. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20143. },
  20144. enumerable: true,
  20145. configurable: true
  20146. });
  20147. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20148. get: function () {
  20149. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20150. },
  20151. enumerable: true,
  20152. configurable: true
  20153. });
  20154. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20155. get: function () {
  20156. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20157. },
  20158. enumerable: true,
  20159. configurable: true
  20160. });
  20161. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20162. this._currentRefreshId = -1;
  20163. };
  20164. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20165. get: function () {
  20166. return this._refreshRate;
  20167. },
  20168. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20169. set: function (value) {
  20170. this._refreshRate = value;
  20171. this.resetRefreshCounter();
  20172. },
  20173. enumerable: true,
  20174. configurable: true
  20175. });
  20176. RenderTargetTexture.prototype._shouldRender = function () {
  20177. if (this._currentRefreshId === -1) {
  20178. this._currentRefreshId = 1;
  20179. return true;
  20180. }
  20181. if (this.refreshRate === this._currentRefreshId) {
  20182. this._currentRefreshId = 1;
  20183. return true;
  20184. }
  20185. this._currentRefreshId++;
  20186. return false;
  20187. };
  20188. RenderTargetTexture.prototype.isReady = function () {
  20189. if (!this.getScene().renderTargetsEnabled) {
  20190. return false;
  20191. }
  20192. return _super.prototype.isReady.call(this);
  20193. };
  20194. RenderTargetTexture.prototype.getRenderSize = function () {
  20195. return this._size;
  20196. };
  20197. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20198. get: function () {
  20199. return true;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. RenderTargetTexture.prototype.scale = function (ratio) {
  20205. var newSize = this._size * ratio;
  20206. this.resize(newSize, this._generateMipMaps);
  20207. };
  20208. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20209. if (this.isCube) {
  20210. return this._textureMatrix;
  20211. }
  20212. return _super.prototype.getReflectionTextureMatrix.call(this);
  20213. };
  20214. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20215. this.releaseInternalTexture();
  20216. if (this.isCube) {
  20217. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20218. }
  20219. else {
  20220. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20221. }
  20222. };
  20223. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20224. var scene = this.getScene();
  20225. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20226. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20227. }
  20228. if (this._waitingRenderList) {
  20229. this.renderList = [];
  20230. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20231. var id = this._waitingRenderList[index];
  20232. this.renderList.push(scene.getMeshByID(id));
  20233. }
  20234. delete this._waitingRenderList;
  20235. }
  20236. if (this.renderList && this.renderList.length === 0) {
  20237. return;
  20238. }
  20239. // Prepare renderingManager
  20240. this._renderingManager.reset();
  20241. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20242. var sceneRenderId = scene.getRenderId();
  20243. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20244. var mesh = currentRenderList[meshIndex];
  20245. if (mesh) {
  20246. if (!mesh.isReady()) {
  20247. // Reset _currentRefreshId
  20248. this.resetRefreshCounter();
  20249. continue;
  20250. }
  20251. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20252. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20253. mesh._activate(sceneRenderId);
  20254. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20255. var subMesh = mesh.subMeshes[subIndex];
  20256. scene._activeIndices += subMesh.indexCount;
  20257. this._renderingManager.dispatch(subMesh);
  20258. }
  20259. }
  20260. }
  20261. }
  20262. if (this.isCube) {
  20263. for (var face = 0; face < 6; face++) {
  20264. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20265. scene.incrementRenderId();
  20266. scene.resetCachedMaterial();
  20267. }
  20268. }
  20269. else {
  20270. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20271. }
  20272. if (this.onAfterUnbind) {
  20273. this.onAfterUnbind();
  20274. }
  20275. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20276. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20277. }
  20278. scene.resetCachedMaterial();
  20279. };
  20280. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20281. var scene = this.getScene();
  20282. var engine = scene.getEngine();
  20283. // Bind
  20284. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20285. if (this.isCube) {
  20286. engine.bindFramebuffer(this._texture, faceIndex);
  20287. }
  20288. else {
  20289. engine.bindFramebuffer(this._texture);
  20290. }
  20291. }
  20292. if (this.onBeforeRender) {
  20293. this.onBeforeRender(faceIndex);
  20294. }
  20295. // Clear
  20296. if (this.onClear) {
  20297. this.onClear(engine);
  20298. }
  20299. else {
  20300. engine.clear(scene.clearColor, true, true);
  20301. }
  20302. if (!this._doNotChangeAspectRatio) {
  20303. scene.updateTransformMatrix(true);
  20304. }
  20305. // Render
  20306. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20307. if (useCameraPostProcess) {
  20308. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20309. }
  20310. if (!this._doNotChangeAspectRatio) {
  20311. scene.updateTransformMatrix(true);
  20312. }
  20313. if (this.onAfterRender) {
  20314. this.onAfterRender(faceIndex);
  20315. }
  20316. // Dump ?
  20317. if (dumpForDebug) {
  20318. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20319. }
  20320. // Unbind
  20321. if (!this.isCube || faceIndex === 5) {
  20322. if (this.isCube) {
  20323. if (faceIndex === 5) {
  20324. engine.generateMipMapsForCubemap(this._texture);
  20325. }
  20326. }
  20327. engine.unBindFramebuffer(this._texture, this.isCube);
  20328. }
  20329. };
  20330. RenderTargetTexture.prototype.clone = function () {
  20331. var textureSize = this.getSize();
  20332. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20333. // Base texture
  20334. newTexture.hasAlpha = this.hasAlpha;
  20335. newTexture.level = this.level;
  20336. // RenderTarget Texture
  20337. newTexture.coordinatesMode = this.coordinatesMode;
  20338. newTexture.renderList = this.renderList.slice(0);
  20339. return newTexture;
  20340. };
  20341. RenderTargetTexture.prototype.serialize = function () {
  20342. if (!this.name) {
  20343. return null;
  20344. }
  20345. var serializationObject = _super.prototype.serialize.call(this);
  20346. serializationObject.renderTargetSize = this.getRenderSize();
  20347. serializationObject.renderList = [];
  20348. for (var index = 0; index < this.renderList.length; index++) {
  20349. serializationObject.renderList.push(this.renderList[index].id);
  20350. }
  20351. return serializationObject;
  20352. };
  20353. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20354. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20355. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20356. return RenderTargetTexture;
  20357. })(BABYLON.Texture);
  20358. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20359. })(BABYLON || (BABYLON = {}));
  20360. var BABYLON;
  20361. (function (BABYLON) {
  20362. var ProceduralTexture = (function (_super) {
  20363. __extends(ProceduralTexture, _super);
  20364. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20365. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20366. if (isCube === void 0) { isCube = false; }
  20367. _super.call(this, null, scene, !generateMipMaps);
  20368. this.isCube = isCube;
  20369. this.isEnabled = true;
  20370. this._currentRefreshId = -1;
  20371. this._refreshRate = 1;
  20372. this._vertexDeclaration = [2];
  20373. this._vertexStrideSize = 2 * 4;
  20374. this._uniforms = new Array();
  20375. this._samplers = new Array();
  20376. this._textures = new Array();
  20377. this._floats = new Array();
  20378. this._floatsArrays = {};
  20379. this._colors3 = new Array();
  20380. this._colors4 = new Array();
  20381. this._vectors2 = new Array();
  20382. this._vectors3 = new Array();
  20383. this._matrices = new Array();
  20384. this._fallbackTextureUsed = false;
  20385. scene._proceduralTextures.push(this);
  20386. this.name = name;
  20387. this.isRenderTarget = true;
  20388. this._size = size;
  20389. this._generateMipMaps = generateMipMaps;
  20390. this.setFragment(fragment);
  20391. this._fallbackTexture = fallbackTexture;
  20392. if (isCube) {
  20393. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20394. this.setFloat("face", 0);
  20395. }
  20396. else {
  20397. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20398. }
  20399. // VBO
  20400. var vertices = [];
  20401. vertices.push(1, 1);
  20402. vertices.push(-1, 1);
  20403. vertices.push(-1, -1);
  20404. vertices.push(1, -1);
  20405. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20406. // Indices
  20407. var indices = [];
  20408. indices.push(0);
  20409. indices.push(1);
  20410. indices.push(2);
  20411. indices.push(0);
  20412. indices.push(2);
  20413. indices.push(3);
  20414. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20415. }
  20416. ProceduralTexture.prototype.reset = function () {
  20417. if (this._effect === undefined) {
  20418. return;
  20419. }
  20420. var engine = this.getScene().getEngine();
  20421. engine._releaseEffect(this._effect);
  20422. };
  20423. ProceduralTexture.prototype.isReady = function () {
  20424. var _this = this;
  20425. var engine = this.getScene().getEngine();
  20426. var shaders;
  20427. if (!this._fragment) {
  20428. return false;
  20429. }
  20430. if (this._fallbackTextureUsed) {
  20431. return true;
  20432. }
  20433. if (this._fragment.fragmentElement !== undefined) {
  20434. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20435. }
  20436. else {
  20437. shaders = { vertex: "procedural", fragment: this._fragment };
  20438. }
  20439. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20440. _this.releaseInternalTexture();
  20441. if (_this._fallbackTexture) {
  20442. _this._texture = _this._fallbackTexture._texture;
  20443. _this._texture.references++;
  20444. }
  20445. _this._fallbackTextureUsed = true;
  20446. });
  20447. return this._effect.isReady();
  20448. };
  20449. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20450. this._currentRefreshId = -1;
  20451. };
  20452. ProceduralTexture.prototype.setFragment = function (fragment) {
  20453. this._fragment = fragment;
  20454. };
  20455. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20456. get: function () {
  20457. return this._refreshRate;
  20458. },
  20459. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20460. set: function (value) {
  20461. this._refreshRate = value;
  20462. this.resetRefreshCounter();
  20463. },
  20464. enumerable: true,
  20465. configurable: true
  20466. });
  20467. ProceduralTexture.prototype._shouldRender = function () {
  20468. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20469. return false;
  20470. }
  20471. if (this._fallbackTextureUsed) {
  20472. return false;
  20473. }
  20474. if (this._currentRefreshId === -1) {
  20475. this._currentRefreshId = 1;
  20476. return true;
  20477. }
  20478. if (this.refreshRate === this._currentRefreshId) {
  20479. this._currentRefreshId = 1;
  20480. return true;
  20481. }
  20482. this._currentRefreshId++;
  20483. return false;
  20484. };
  20485. ProceduralTexture.prototype.getRenderSize = function () {
  20486. return this._size;
  20487. };
  20488. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20489. if (this._fallbackTextureUsed) {
  20490. return;
  20491. }
  20492. this.releaseInternalTexture();
  20493. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20494. };
  20495. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  20496. if (this._uniforms.indexOf(uniformName) === -1) {
  20497. this._uniforms.push(uniformName);
  20498. }
  20499. };
  20500. ProceduralTexture.prototype.setTexture = function (name, texture) {
  20501. if (this._samplers.indexOf(name) === -1) {
  20502. this._samplers.push(name);
  20503. }
  20504. this._textures[name] = texture;
  20505. return this;
  20506. };
  20507. ProceduralTexture.prototype.setFloat = function (name, value) {
  20508. this._checkUniform(name);
  20509. this._floats[name] = value;
  20510. return this;
  20511. };
  20512. ProceduralTexture.prototype.setFloats = function (name, value) {
  20513. this._checkUniform(name);
  20514. this._floatsArrays[name] = value;
  20515. return this;
  20516. };
  20517. ProceduralTexture.prototype.setColor3 = function (name, value) {
  20518. this._checkUniform(name);
  20519. this._colors3[name] = value;
  20520. return this;
  20521. };
  20522. ProceduralTexture.prototype.setColor4 = function (name, value) {
  20523. this._checkUniform(name);
  20524. this._colors4[name] = value;
  20525. return this;
  20526. };
  20527. ProceduralTexture.prototype.setVector2 = function (name, value) {
  20528. this._checkUniform(name);
  20529. this._vectors2[name] = value;
  20530. return this;
  20531. };
  20532. ProceduralTexture.prototype.setVector3 = function (name, value) {
  20533. this._checkUniform(name);
  20534. this._vectors3[name] = value;
  20535. return this;
  20536. };
  20537. ProceduralTexture.prototype.setMatrix = function (name, value) {
  20538. this._checkUniform(name);
  20539. this._matrices[name] = value;
  20540. return this;
  20541. };
  20542. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20543. var scene = this.getScene();
  20544. var engine = scene.getEngine();
  20545. // Render
  20546. engine.enableEffect(this._effect);
  20547. engine.setState(false);
  20548. // Texture
  20549. for (var name in this._textures) {
  20550. this._effect.setTexture(name, this._textures[name]);
  20551. }
  20552. // Float
  20553. for (name in this._floats) {
  20554. this._effect.setFloat(name, this._floats[name]);
  20555. }
  20556. // Floats
  20557. for (name in this._floatsArrays) {
  20558. this._effect.setArray(name, this._floatsArrays[name]);
  20559. }
  20560. // Color3
  20561. for (name in this._colors3) {
  20562. this._effect.setColor3(name, this._colors3[name]);
  20563. }
  20564. // Color4
  20565. for (name in this._colors4) {
  20566. var color = this._colors4[name];
  20567. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20568. }
  20569. // Vector2
  20570. for (name in this._vectors2) {
  20571. this._effect.setVector2(name, this._vectors2[name]);
  20572. }
  20573. // Vector3
  20574. for (name in this._vectors3) {
  20575. this._effect.setVector3(name, this._vectors3[name]);
  20576. }
  20577. // Matrix
  20578. for (name in this._matrices) {
  20579. this._effect.setMatrix(name, this._matrices[name]);
  20580. }
  20581. // VBOs
  20582. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20583. if (this.isCube) {
  20584. for (var face = 0; face < 6; face++) {
  20585. engine.bindFramebuffer(this._texture, face);
  20586. this._effect.setFloat("face", face);
  20587. // Clear
  20588. engine.clear(scene.clearColor, true, true);
  20589. // Draw order
  20590. engine.draw(true, 0, 6);
  20591. // Mipmaps
  20592. if (face === 5) {
  20593. engine.generateMipMapsForCubemap(this._texture);
  20594. }
  20595. }
  20596. }
  20597. else {
  20598. engine.bindFramebuffer(this._texture);
  20599. // Clear
  20600. engine.clear(scene.clearColor, true, true);
  20601. // Draw order
  20602. engine.draw(true, 0, 6);
  20603. }
  20604. // Unbind
  20605. engine.unBindFramebuffer(this._texture, this.isCube);
  20606. if (this.onGenerated) {
  20607. this.onGenerated();
  20608. }
  20609. };
  20610. ProceduralTexture.prototype.clone = function () {
  20611. var textureSize = this.getSize();
  20612. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  20613. // Base texture
  20614. newTexture.hasAlpha = this.hasAlpha;
  20615. newTexture.level = this.level;
  20616. // RenderTarget Texture
  20617. newTexture.coordinatesMode = this.coordinatesMode;
  20618. return newTexture;
  20619. };
  20620. ProceduralTexture.prototype.dispose = function () {
  20621. var index = this.getScene()._proceduralTextures.indexOf(this);
  20622. if (index >= 0) {
  20623. this.getScene()._proceduralTextures.splice(index, 1);
  20624. }
  20625. _super.prototype.dispose.call(this);
  20626. };
  20627. return ProceduralTexture;
  20628. })(BABYLON.Texture);
  20629. BABYLON.ProceduralTexture = ProceduralTexture;
  20630. })(BABYLON || (BABYLON = {}));
  20631. var BABYLON;
  20632. (function (BABYLON) {
  20633. var MirrorTexture = (function (_super) {
  20634. __extends(MirrorTexture, _super);
  20635. function MirrorTexture(name, size, scene, generateMipMaps) {
  20636. var _this = this;
  20637. _super.call(this, name, size, scene, generateMipMaps, true);
  20638. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  20639. this._transformMatrix = BABYLON.Matrix.Zero();
  20640. this._mirrorMatrix = BABYLON.Matrix.Zero();
  20641. this.onBeforeRender = function () {
  20642. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  20643. _this._savedViewMatrix = scene.getViewMatrix();
  20644. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  20645. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  20646. scene.clipPlane = _this.mirrorPlane;
  20647. scene.getEngine().cullBackFaces = false;
  20648. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  20649. };
  20650. this.onAfterRender = function () {
  20651. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  20652. scene.getEngine().cullBackFaces = true;
  20653. scene._mirroredCameraPosition = null;
  20654. delete scene.clipPlane;
  20655. };
  20656. }
  20657. MirrorTexture.prototype.clone = function () {
  20658. var textureSize = this.getSize();
  20659. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20660. // Base texture
  20661. newTexture.hasAlpha = this.hasAlpha;
  20662. newTexture.level = this.level;
  20663. // Mirror Texture
  20664. newTexture.mirrorPlane = this.mirrorPlane.clone();
  20665. newTexture.renderList = this.renderList.slice(0);
  20666. return newTexture;
  20667. };
  20668. MirrorTexture.prototype.serialize = function () {
  20669. if (!this.name) {
  20670. return null;
  20671. }
  20672. var serializationObject = _super.prototype.serialize.call(this);
  20673. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  20674. return serializationObject;
  20675. };
  20676. return MirrorTexture;
  20677. })(BABYLON.RenderTargetTexture);
  20678. BABYLON.MirrorTexture = MirrorTexture;
  20679. })(BABYLON || (BABYLON = {}));
  20680. var BABYLON;
  20681. (function (BABYLON) {
  20682. /**
  20683. * Creates a refraction texture used by refraction channel of the standard material.
  20684. * @param name the texture name
  20685. * @param size size of the underlying texture
  20686. * @param scene root scene
  20687. */
  20688. var RefractionTexture = (function (_super) {
  20689. __extends(RefractionTexture, _super);
  20690. function RefractionTexture(name, size, scene, generateMipMaps) {
  20691. var _this = this;
  20692. _super.call(this, name, size, scene, generateMipMaps, true);
  20693. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  20694. this.depth = 2.0;
  20695. this.onBeforeRender = function () {
  20696. scene.clipPlane = _this.refractionPlane;
  20697. };
  20698. this.onAfterRender = function () {
  20699. delete scene.clipPlane;
  20700. };
  20701. }
  20702. RefractionTexture.prototype.clone = function () {
  20703. var textureSize = this.getSize();
  20704. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20705. // Base texture
  20706. newTexture.hasAlpha = this.hasAlpha;
  20707. newTexture.level = this.level;
  20708. // Refraction Texture
  20709. newTexture.refractionPlane = this.refractionPlane.clone();
  20710. newTexture.renderList = this.renderList.slice(0);
  20711. newTexture.depth = this.depth;
  20712. return newTexture;
  20713. };
  20714. RefractionTexture.prototype.serialize = function () {
  20715. if (!this.name) {
  20716. return null;
  20717. }
  20718. var serializationObject = _super.prototype.serialize.call(this);
  20719. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  20720. serializationObject.depth = this.depth;
  20721. return serializationObject;
  20722. };
  20723. return RefractionTexture;
  20724. })(BABYLON.RenderTargetTexture);
  20725. BABYLON.RefractionTexture = RefractionTexture;
  20726. })(BABYLON || (BABYLON = {}));
  20727. var BABYLON;
  20728. (function (BABYLON) {
  20729. var DynamicTexture = (function (_super) {
  20730. __extends(DynamicTexture, _super);
  20731. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  20732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20733. _super.call(this, null, scene, !generateMipMaps);
  20734. this.name = name;
  20735. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20736. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20737. this._generateMipMaps = generateMipMaps;
  20738. if (options.getContext) {
  20739. this._canvas = options;
  20740. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  20741. }
  20742. else {
  20743. this._canvas = document.createElement("canvas");
  20744. if (options.width) {
  20745. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  20746. }
  20747. else {
  20748. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  20749. }
  20750. }
  20751. var textureSize = this.getSize();
  20752. this._canvas.width = textureSize.width;
  20753. this._canvas.height = textureSize.height;
  20754. this._context = this._canvas.getContext("2d");
  20755. }
  20756. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  20757. get: function () {
  20758. return true;
  20759. },
  20760. enumerable: true,
  20761. configurable: true
  20762. });
  20763. DynamicTexture.prototype.scale = function (ratio) {
  20764. var textureSize = this.getSize();
  20765. textureSize.width *= ratio;
  20766. textureSize.height *= ratio;
  20767. this._canvas.width = textureSize.width;
  20768. this._canvas.height = textureSize.height;
  20769. this.releaseInternalTexture();
  20770. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  20771. };
  20772. DynamicTexture.prototype.getContext = function () {
  20773. return this._context;
  20774. };
  20775. DynamicTexture.prototype.clear = function () {
  20776. var size = this.getSize();
  20777. this._context.fillRect(0, 0, size.width, size.height);
  20778. };
  20779. DynamicTexture.prototype.update = function (invertY) {
  20780. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  20781. };
  20782. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  20783. if (update === void 0) { update = true; }
  20784. var size = this.getSize();
  20785. if (clearColor) {
  20786. this._context.fillStyle = clearColor;
  20787. this._context.fillRect(0, 0, size.width, size.height);
  20788. }
  20789. this._context.font = font;
  20790. if (x === null) {
  20791. var textSize = this._context.measureText(text);
  20792. x = (size.width - textSize.width) / 2;
  20793. }
  20794. this._context.fillStyle = color;
  20795. this._context.fillText(text, x, y);
  20796. if (update) {
  20797. this.update(invertY);
  20798. }
  20799. };
  20800. DynamicTexture.prototype.clone = function () {
  20801. var textureSize = this.getSize();
  20802. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20803. // Base texture
  20804. newTexture.hasAlpha = this.hasAlpha;
  20805. newTexture.level = this.level;
  20806. // Dynamic Texture
  20807. newTexture.wrapU = this.wrapU;
  20808. newTexture.wrapV = this.wrapV;
  20809. return newTexture;
  20810. };
  20811. return DynamicTexture;
  20812. })(BABYLON.Texture);
  20813. BABYLON.DynamicTexture = DynamicTexture;
  20814. })(BABYLON || (BABYLON = {}));
  20815. var BABYLON;
  20816. (function (BABYLON) {
  20817. var VideoTexture = (function (_super) {
  20818. __extends(VideoTexture, _super);
  20819. /**
  20820. * Creates a video texture.
  20821. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  20822. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  20823. * @param {BABYLON.Scene} scene is obviously the current scene.
  20824. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  20825. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  20826. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  20827. */
  20828. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  20829. var _this = this;
  20830. if (generateMipMaps === void 0) { generateMipMaps = false; }
  20831. if (invertY === void 0) { invertY = false; }
  20832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20833. _super.call(this, null, scene, !generateMipMaps, invertY);
  20834. this._autoLaunch = true;
  20835. var urls;
  20836. this.name = name;
  20837. if (urlsOrVideo instanceof HTMLVideoElement) {
  20838. this.video = urlsOrVideo;
  20839. }
  20840. else {
  20841. urls = urlsOrVideo;
  20842. this.video = document.createElement("video");
  20843. this.video.autoplay = false;
  20844. this.video.loop = true;
  20845. }
  20846. this._generateMipMaps = generateMipMaps;
  20847. this._samplingMode = samplingMode;
  20848. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  20849. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20850. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20851. }
  20852. else {
  20853. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20854. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20855. this._generateMipMaps = false;
  20856. }
  20857. if (urls) {
  20858. this.video.addEventListener("canplaythrough", function () {
  20859. _this._createTexture();
  20860. });
  20861. urls.forEach(function (url) {
  20862. var source = document.createElement("source");
  20863. source.src = url;
  20864. _this.video.appendChild(source);
  20865. });
  20866. }
  20867. else {
  20868. this._createTexture();
  20869. }
  20870. this._lastUpdate = BABYLON.Tools.Now;
  20871. }
  20872. VideoTexture.prototype._createTexture = function () {
  20873. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  20874. this._texture.isReady = true;
  20875. };
  20876. VideoTexture.prototype.update = function () {
  20877. if (this._autoLaunch) {
  20878. this._autoLaunch = false;
  20879. this.video.play();
  20880. }
  20881. var now = BABYLON.Tools.Now;
  20882. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  20883. return false;
  20884. }
  20885. this._lastUpdate = now;
  20886. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  20887. return true;
  20888. };
  20889. return VideoTexture;
  20890. })(BABYLON.Texture);
  20891. BABYLON.VideoTexture = VideoTexture;
  20892. })(BABYLON || (BABYLON = {}));
  20893. var BABYLON;
  20894. (function (BABYLON) {
  20895. var CustomProceduralTexture = (function (_super) {
  20896. __extends(CustomProceduralTexture, _super);
  20897. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  20898. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  20899. this._animate = true;
  20900. this._time = 0;
  20901. this._texturePath = texturePath;
  20902. //Try to load json
  20903. this.loadJson(texturePath);
  20904. this.refreshRate = 1;
  20905. }
  20906. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  20907. var _this = this;
  20908. var that = this;
  20909. function noConfigFile() {
  20910. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  20911. try {
  20912. that.setFragment(that._texturePath);
  20913. }
  20914. catch (ex) {
  20915. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  20916. }
  20917. }
  20918. var configFileUrl = jsonUrl + "/config.json";
  20919. var xhr = new XMLHttpRequest();
  20920. xhr.open("GET", configFileUrl, true);
  20921. xhr.addEventListener("load", function () {
  20922. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  20923. try {
  20924. _this._config = JSON.parse(xhr.response);
  20925. _this.updateShaderUniforms();
  20926. _this.updateTextures();
  20927. _this.setFragment(_this._texturePath + "/custom");
  20928. _this._animate = _this._config.animate;
  20929. _this.refreshRate = _this._config.refreshrate;
  20930. }
  20931. catch (ex) {
  20932. noConfigFile();
  20933. }
  20934. }
  20935. else {
  20936. noConfigFile();
  20937. }
  20938. }, false);
  20939. xhr.addEventListener("error", function () {
  20940. noConfigFile();
  20941. }, false);
  20942. try {
  20943. xhr.send();
  20944. }
  20945. catch (ex) {
  20946. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  20947. }
  20948. };
  20949. CustomProceduralTexture.prototype.isReady = function () {
  20950. if (!_super.prototype.isReady.call(this)) {
  20951. return false;
  20952. }
  20953. for (var name in this._textures) {
  20954. var texture = this._textures[name];
  20955. if (!texture.isReady()) {
  20956. return false;
  20957. }
  20958. }
  20959. return true;
  20960. };
  20961. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20962. if (this._animate) {
  20963. this._time += this.getScene().getAnimationRatio() * 0.03;
  20964. this.updateShaderUniforms();
  20965. }
  20966. _super.prototype.render.call(this, useCameraPostProcess);
  20967. };
  20968. CustomProceduralTexture.prototype.updateTextures = function () {
  20969. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  20970. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  20971. }
  20972. };
  20973. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  20974. if (this._config) {
  20975. for (var j = 0; j < this._config.uniforms.length; j++) {
  20976. var uniform = this._config.uniforms[j];
  20977. switch (uniform.type) {
  20978. case "float":
  20979. this.setFloat(uniform.name, uniform.value);
  20980. break;
  20981. case "color3":
  20982. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  20983. break;
  20984. case "color4":
  20985. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  20986. break;
  20987. case "vector2":
  20988. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  20989. break;
  20990. case "vector3":
  20991. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  20992. break;
  20993. }
  20994. }
  20995. }
  20996. this.setFloat("time", this._time);
  20997. };
  20998. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  20999. get: function () {
  21000. return this._animate;
  21001. },
  21002. set: function (value) {
  21003. this._animate = value;
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. return CustomProceduralTexture;
  21009. })(BABYLON.ProceduralTexture);
  21010. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21011. })(BABYLON || (BABYLON = {}));
  21012. var BABYLON;
  21013. (function (BABYLON) {
  21014. var EffectFallbacks = (function () {
  21015. function EffectFallbacks() {
  21016. this._defines = {};
  21017. this._currentRank = 32;
  21018. this._maxRank = -1;
  21019. }
  21020. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21021. if (!this._defines[rank]) {
  21022. if (rank < this._currentRank) {
  21023. this._currentRank = rank;
  21024. }
  21025. if (rank > this._maxRank) {
  21026. this._maxRank = rank;
  21027. }
  21028. this._defines[rank] = new Array();
  21029. }
  21030. this._defines[rank].push(define);
  21031. };
  21032. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21033. this._meshRank = rank;
  21034. this._mesh = mesh;
  21035. if (rank > this._maxRank) {
  21036. this._maxRank = rank;
  21037. }
  21038. };
  21039. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21040. get: function () {
  21041. return this._currentRank <= this._maxRank;
  21042. },
  21043. enumerable: true,
  21044. configurable: true
  21045. });
  21046. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21047. var currentFallbacks = this._defines[this._currentRank];
  21048. for (var index = 0; index < currentFallbacks.length; index++) {
  21049. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21050. }
  21051. if (this._mesh && this._currentRank === this._meshRank) {
  21052. this._mesh.computeBonesUsingShaders = false;
  21053. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21054. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21055. }
  21056. this._currentRank++;
  21057. return currentDefines;
  21058. };
  21059. return EffectFallbacks;
  21060. })();
  21061. BABYLON.EffectFallbacks = EffectFallbacks;
  21062. var Effect = (function () {
  21063. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21064. var _this = this;
  21065. this._isReady = false;
  21066. this._compilationError = "";
  21067. this._valueCache = [];
  21068. this._engine = engine;
  21069. this.name = baseName;
  21070. this.defines = defines;
  21071. this._uniformsNames = uniformsNames.concat(samplers);
  21072. this._samplers = samplers;
  21073. this._attributesNames = attributesNames;
  21074. this.onError = onError;
  21075. this.onCompiled = onCompiled;
  21076. var vertexSource;
  21077. var fragmentSource;
  21078. if (baseName.vertexElement) {
  21079. vertexSource = document.getElementById(baseName.vertexElement);
  21080. if (!vertexSource) {
  21081. vertexSource = baseName.vertexElement;
  21082. }
  21083. }
  21084. else {
  21085. vertexSource = baseName.vertex || baseName;
  21086. }
  21087. if (baseName.fragmentElement) {
  21088. fragmentSource = document.getElementById(baseName.fragmentElement);
  21089. if (!fragmentSource) {
  21090. fragmentSource = baseName.fragmentElement;
  21091. }
  21092. }
  21093. else {
  21094. fragmentSource = baseName.fragment || baseName;
  21095. }
  21096. this._loadVertexShader(vertexSource, function (vertexCode) {
  21097. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21098. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21099. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21100. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21101. });
  21102. });
  21103. });
  21104. });
  21105. }
  21106. // Properties
  21107. Effect.prototype.isReady = function () {
  21108. return this._isReady;
  21109. };
  21110. Effect.prototype.getProgram = function () {
  21111. return this._program;
  21112. };
  21113. Effect.prototype.getAttributesNames = function () {
  21114. return this._attributesNames;
  21115. };
  21116. Effect.prototype.getAttributeLocation = function (index) {
  21117. return this._attributes[index];
  21118. };
  21119. Effect.prototype.getAttributeLocationByName = function (name) {
  21120. var index = this._attributesNames.indexOf(name);
  21121. return this._attributes[index];
  21122. };
  21123. Effect.prototype.getAttributesCount = function () {
  21124. return this._attributes.length;
  21125. };
  21126. Effect.prototype.getUniformIndex = function (uniformName) {
  21127. return this._uniformsNames.indexOf(uniformName);
  21128. };
  21129. Effect.prototype.getUniform = function (uniformName) {
  21130. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21131. };
  21132. Effect.prototype.getSamplers = function () {
  21133. return this._samplers;
  21134. };
  21135. Effect.prototype.getCompilationError = function () {
  21136. return this._compilationError;
  21137. };
  21138. // Methods
  21139. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21140. // DOM element ?
  21141. if (vertex instanceof HTMLElement) {
  21142. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21143. callback(vertexCode);
  21144. return;
  21145. }
  21146. // Is in local store ?
  21147. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21148. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21149. return;
  21150. }
  21151. var vertexShaderUrl;
  21152. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21153. vertexShaderUrl = vertex;
  21154. }
  21155. else {
  21156. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21157. }
  21158. // Vertex shader
  21159. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21160. };
  21161. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21162. // DOM element ?
  21163. if (fragment instanceof HTMLElement) {
  21164. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21165. callback(fragmentCode);
  21166. return;
  21167. }
  21168. // Is in local store ?
  21169. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21170. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21171. return;
  21172. }
  21173. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21174. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21175. return;
  21176. }
  21177. var fragmentShaderUrl;
  21178. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21179. fragmentShaderUrl = fragment;
  21180. }
  21181. else {
  21182. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21183. }
  21184. // Fragment shader
  21185. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21186. };
  21187. Effect.prototype._dumpShadersName = function () {
  21188. if (this.name.vertexElement) {
  21189. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21190. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21191. }
  21192. else if (this.name.vertex) {
  21193. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21194. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21195. }
  21196. else {
  21197. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21198. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21199. }
  21200. };
  21201. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21202. var _this = this;
  21203. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21204. var match = regex.exec(sourceCode);
  21205. var returnValue = new String(sourceCode);
  21206. while (match != null) {
  21207. var includeFile = match[1];
  21208. if (Effect.IncludesShadersStore[includeFile]) {
  21209. // Substitution
  21210. var includeContent = Effect.IncludesShadersStore[includeFile];
  21211. if (match[2]) {
  21212. var splits = match[3].split(",");
  21213. for (var index = 0; index < splits.length; index += 2) {
  21214. var source = new RegExp(splits[index], "g");
  21215. var dest = splits[index + 1];
  21216. includeContent = includeContent.replace(source, dest);
  21217. }
  21218. }
  21219. if (match[4]) {
  21220. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21221. }
  21222. // Replace
  21223. returnValue = returnValue.replace(match[0], includeContent);
  21224. }
  21225. else {
  21226. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21227. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21228. Effect.IncludesShadersStore[includeFile] = fileContent;
  21229. _this._processIncludes(returnValue, callback);
  21230. });
  21231. return;
  21232. }
  21233. match = regex.exec(sourceCode);
  21234. }
  21235. callback(returnValue);
  21236. };
  21237. Effect.prototype._processPrecision = function (source) {
  21238. if (source.indexOf("precision highp float") === -1) {
  21239. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21240. source = "precision mediump float;\n" + source;
  21241. }
  21242. else {
  21243. source = "precision highp float;\n" + source;
  21244. }
  21245. }
  21246. else {
  21247. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21248. source = source.replace("precision highp float", "precision mediump float");
  21249. }
  21250. }
  21251. return source;
  21252. };
  21253. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21254. try {
  21255. var engine = this._engine;
  21256. // Precision
  21257. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21258. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21259. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21260. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21261. this._attributes = engine.getAttributes(this._program, attributesNames);
  21262. for (var index = 0; index < this._samplers.length; index++) {
  21263. var sampler = this.getUniform(this._samplers[index]);
  21264. if (sampler == null) {
  21265. this._samplers.splice(index, 1);
  21266. index--;
  21267. }
  21268. }
  21269. engine.bindSamplers(this);
  21270. this._isReady = true;
  21271. if (this.onCompiled) {
  21272. this.onCompiled(this);
  21273. }
  21274. }
  21275. catch (e) {
  21276. // Is it a problem with precision?
  21277. if (e.message.indexOf("highp") !== -1) {
  21278. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21279. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21280. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21281. return;
  21282. }
  21283. // Let's go through fallbacks then
  21284. if (fallbacks && fallbacks.isMoreFallbacks) {
  21285. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21286. this._dumpShadersName();
  21287. defines = fallbacks.reduce(defines);
  21288. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21289. }
  21290. else {
  21291. BABYLON.Tools.Error("Unable to compile effect: ");
  21292. this._dumpShadersName();
  21293. BABYLON.Tools.Error("Defines: " + defines);
  21294. BABYLON.Tools.Error("Error: " + e.message);
  21295. this._compilationError = e.message;
  21296. if (this.onError) {
  21297. this.onError(this, this._compilationError);
  21298. }
  21299. }
  21300. }
  21301. };
  21302. Object.defineProperty(Effect.prototype, "isSupported", {
  21303. get: function () {
  21304. return this._compilationError === "";
  21305. },
  21306. enumerable: true,
  21307. configurable: true
  21308. });
  21309. Effect.prototype._bindTexture = function (channel, texture) {
  21310. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21311. };
  21312. Effect.prototype.setTexture = function (channel, texture) {
  21313. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21314. };
  21315. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21316. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21317. };
  21318. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21319. if (!this._valueCache[uniformName]) {
  21320. this._valueCache[uniformName] = new BABYLON.Matrix();
  21321. }
  21322. for (var index = 0; index < 16; index++) {
  21323. this._valueCache[uniformName].m[index] = matrix.m[index];
  21324. }
  21325. };
  21326. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21327. if (!this._valueCache[uniformName]) {
  21328. this._valueCache[uniformName] = [x, y];
  21329. return;
  21330. }
  21331. this._valueCache[uniformName][0] = x;
  21332. this._valueCache[uniformName][1] = y;
  21333. };
  21334. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21335. if (!this._valueCache[uniformName]) {
  21336. this._valueCache[uniformName] = [x, y, z];
  21337. return;
  21338. }
  21339. this._valueCache[uniformName][0] = x;
  21340. this._valueCache[uniformName][1] = y;
  21341. this._valueCache[uniformName][2] = z;
  21342. };
  21343. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21344. if (!this._valueCache[uniformName]) {
  21345. this._valueCache[uniformName] = [x, y, z, w];
  21346. return;
  21347. }
  21348. this._valueCache[uniformName][0] = x;
  21349. this._valueCache[uniformName][1] = y;
  21350. this._valueCache[uniformName][2] = z;
  21351. this._valueCache[uniformName][3] = w;
  21352. };
  21353. Effect.prototype.setArray = function (uniformName, array) {
  21354. this._engine.setArray(this.getUniform(uniformName), array);
  21355. return this;
  21356. };
  21357. Effect.prototype.setArray2 = function (uniformName, array) {
  21358. this._engine.setArray2(this.getUniform(uniformName), array);
  21359. return this;
  21360. };
  21361. Effect.prototype.setArray3 = function (uniformName, array) {
  21362. this._engine.setArray3(this.getUniform(uniformName), array);
  21363. return this;
  21364. };
  21365. Effect.prototype.setArray4 = function (uniformName, array) {
  21366. this._engine.setArray4(this.getUniform(uniformName), array);
  21367. return this;
  21368. };
  21369. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21370. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21371. return this;
  21372. };
  21373. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21374. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21375. // return this;
  21376. // this._cacheMatrix(uniformName, matrix);
  21377. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21378. return this;
  21379. };
  21380. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21381. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21382. return this;
  21383. };
  21384. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21385. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21386. return this;
  21387. };
  21388. Effect.prototype.setFloat = function (uniformName, value) {
  21389. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21390. return this;
  21391. this._valueCache[uniformName] = value;
  21392. this._engine.setFloat(this.getUniform(uniformName), value);
  21393. return this;
  21394. };
  21395. Effect.prototype.setBool = function (uniformName, bool) {
  21396. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21397. return this;
  21398. this._valueCache[uniformName] = bool;
  21399. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21400. return this;
  21401. };
  21402. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21403. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21404. return this;
  21405. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21406. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21407. return this;
  21408. };
  21409. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21410. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21411. return this;
  21412. this._cacheFloat2(uniformName, x, y);
  21413. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21414. return this;
  21415. };
  21416. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21417. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21418. return this;
  21419. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21420. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21421. return this;
  21422. };
  21423. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21424. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21425. return this;
  21426. this._cacheFloat3(uniformName, x, y, z);
  21427. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21428. return this;
  21429. };
  21430. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21431. 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)
  21432. return this;
  21433. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21434. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21435. return this;
  21436. };
  21437. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21438. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21439. return this;
  21440. this._cacheFloat4(uniformName, x, y, z, w);
  21441. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21442. return this;
  21443. };
  21444. Effect.prototype.setColor3 = function (uniformName, color3) {
  21445. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21446. return this;
  21447. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21448. this._engine.setColor3(this.getUniform(uniformName), color3);
  21449. return this;
  21450. };
  21451. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21452. 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)
  21453. return this;
  21454. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21455. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21456. return this;
  21457. };
  21458. // Statics
  21459. Effect.ShadersStore = {};
  21460. Effect.IncludesShadersStore = {};
  21461. return Effect;
  21462. })();
  21463. BABYLON.Effect = Effect;
  21464. })(BABYLON || (BABYLON = {}));
  21465. var BABYLON;
  21466. (function (BABYLON) {
  21467. var maxSimultaneousLights = 4;
  21468. var MaterialHelper = (function () {
  21469. function MaterialHelper() {
  21470. }
  21471. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21472. var lightIndex = 0;
  21473. var needNormals = false;
  21474. for (var index = 0; index < scene.lights.length; index++) {
  21475. var light = scene.lights[index];
  21476. if (!light.isEnabled()) {
  21477. continue;
  21478. }
  21479. // Excluded check
  21480. if (light._excludedMeshesIds.length > 0) {
  21481. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21482. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21483. if (excludedMesh) {
  21484. light.excludedMeshes.push(excludedMesh);
  21485. }
  21486. }
  21487. light._excludedMeshesIds = [];
  21488. }
  21489. // Included check
  21490. if (light._includedOnlyMeshesIds.length > 0) {
  21491. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21492. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  21493. if (includedOnlyMesh) {
  21494. light.includedOnlyMeshes.push(includedOnlyMesh);
  21495. }
  21496. }
  21497. light._includedOnlyMeshesIds = [];
  21498. }
  21499. if (!light.canAffectMesh(mesh)) {
  21500. continue;
  21501. }
  21502. needNormals = true;
  21503. defines["LIGHT" + lightIndex] = true;
  21504. var type;
  21505. if (light instanceof BABYLON.SpotLight) {
  21506. type = "SPOTLIGHT" + lightIndex;
  21507. }
  21508. else if (light instanceof BABYLON.HemisphericLight) {
  21509. type = "HEMILIGHT" + lightIndex;
  21510. }
  21511. else if (light instanceof BABYLON.PointLight) {
  21512. type = "POINTLIGHT" + lightIndex;
  21513. }
  21514. else {
  21515. type = "DIRLIGHT" + lightIndex;
  21516. }
  21517. defines[type] = true;
  21518. // Specular
  21519. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  21520. defines["SPECULARTERM"] = true;
  21521. }
  21522. // Shadows
  21523. if (scene.shadowsEnabled) {
  21524. var shadowGenerator = light.getShadowGenerator();
  21525. if (mesh && mesh.receiveShadows && shadowGenerator) {
  21526. defines["SHADOW" + lightIndex] = true;
  21527. defines["SHADOWS"] = true;
  21528. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  21529. defines["SHADOWVSM" + lightIndex] = true;
  21530. }
  21531. if (shadowGenerator.usePoissonSampling) {
  21532. defines["SHADOWPCF" + lightIndex] = true;
  21533. }
  21534. }
  21535. }
  21536. lightIndex++;
  21537. if (lightIndex === maxSimultaneousLights)
  21538. break;
  21539. }
  21540. return needNormals;
  21541. };
  21542. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  21543. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  21544. if (!defines["LIGHT" + lightIndex]) {
  21545. continue;
  21546. }
  21547. if (lightIndex > 0) {
  21548. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  21549. }
  21550. if (defines["SHADOW" + lightIndex]) {
  21551. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  21552. }
  21553. if (defines["SHADOWPCF" + lightIndex]) {
  21554. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  21555. }
  21556. if (defines["SHADOWVSM" + lightIndex]) {
  21557. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  21558. }
  21559. }
  21560. };
  21561. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  21562. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  21563. fallbacks.addCPUSkinningFallback(0, mesh);
  21564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21566. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  21567. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  21568. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  21569. }
  21570. }
  21571. };
  21572. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  21573. if (defines["INSTANCES"]) {
  21574. attribs.push("world0");
  21575. attribs.push("world1");
  21576. attribs.push("world2");
  21577. attribs.push("world3");
  21578. }
  21579. };
  21580. // Bindings
  21581. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  21582. var shadowGenerator = light.getShadowGenerator();
  21583. if (mesh.receiveShadows && shadowGenerator) {
  21584. if (!light.needCube()) {
  21585. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  21586. }
  21587. else {
  21588. if (!depthValuesAlreadySet) {
  21589. depthValuesAlreadySet = true;
  21590. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  21591. }
  21592. }
  21593. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  21594. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  21595. }
  21596. return depthValuesAlreadySet;
  21597. };
  21598. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  21599. if (light instanceof BABYLON.PointLight) {
  21600. // Point Light
  21601. light.transferToEffect(effect, "vLightData" + lightIndex);
  21602. }
  21603. else if (light instanceof BABYLON.DirectionalLight) {
  21604. // Directional Light
  21605. light.transferToEffect(effect, "vLightData" + lightIndex);
  21606. }
  21607. else if (light instanceof BABYLON.SpotLight) {
  21608. // Spot Light
  21609. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  21610. }
  21611. else if (light instanceof BABYLON.HemisphericLight) {
  21612. // Hemispheric Light
  21613. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  21614. }
  21615. };
  21616. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  21617. var lightIndex = 0;
  21618. var depthValuesAlreadySet = false;
  21619. for (var index = 0; index < scene.lights.length; index++) {
  21620. var light = scene.lights[index];
  21621. if (!light.isEnabled()) {
  21622. continue;
  21623. }
  21624. if (!light.canAffectMesh(mesh)) {
  21625. continue;
  21626. }
  21627. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  21628. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  21629. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  21630. if (defines["SPECULARTERM"]) {
  21631. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  21632. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  21633. }
  21634. // Shadows
  21635. if (scene.shadowsEnabled) {
  21636. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  21637. }
  21638. lightIndex++;
  21639. if (lightIndex === maxSimultaneousLights)
  21640. break;
  21641. }
  21642. };
  21643. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  21644. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  21645. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  21646. effect.setColor3("vFogColor", scene.fogColor);
  21647. }
  21648. };
  21649. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  21650. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  21651. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  21652. }
  21653. };
  21654. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  21655. if (defines["LOGARITHMICDEPTH"]) {
  21656. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  21657. }
  21658. };
  21659. MaterialHelper.BindClipPlane = function (effect, scene) {
  21660. if (scene.clipPlane) {
  21661. var clipPlane = scene.clipPlane;
  21662. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21663. }
  21664. };
  21665. return MaterialHelper;
  21666. })();
  21667. BABYLON.MaterialHelper = MaterialHelper;
  21668. })(BABYLON || (BABYLON = {}));
  21669. var BABYLON;
  21670. (function (BABYLON) {
  21671. var FresnelParameters = (function () {
  21672. function FresnelParameters() {
  21673. this.isEnabled = true;
  21674. this.leftColor = BABYLON.Color3.White();
  21675. this.rightColor = BABYLON.Color3.Black();
  21676. this.bias = 0;
  21677. this.power = 1;
  21678. }
  21679. FresnelParameters.prototype.clone = function () {
  21680. var newFresnelParameters = new FresnelParameters();
  21681. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  21682. return new FresnelParameters;
  21683. };
  21684. FresnelParameters.prototype.serialize = function () {
  21685. var serializationObject = {};
  21686. serializationObject.isEnabled = this.isEnabled;
  21687. serializationObject.leftColor = this.leftColor;
  21688. serializationObject.rightColor = this.rightColor;
  21689. serializationObject.bias = this.bias;
  21690. serializationObject.power = this.power;
  21691. return serializationObject;
  21692. };
  21693. FresnelParameters.Parse = function (parsedFresnelParameters) {
  21694. var fresnelParameters = new FresnelParameters();
  21695. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  21696. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  21697. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  21698. fresnelParameters.bias = parsedFresnelParameters.bias;
  21699. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  21700. return fresnelParameters;
  21701. };
  21702. return FresnelParameters;
  21703. })();
  21704. BABYLON.FresnelParameters = FresnelParameters;
  21705. })(BABYLON || (BABYLON = {}));
  21706. var BABYLON;
  21707. (function (BABYLON) {
  21708. var MaterialDefines = (function () {
  21709. function MaterialDefines() {
  21710. }
  21711. MaterialDefines.prototype.isEqual = function (other) {
  21712. for (var index = 0; index < this._keys.length; index++) {
  21713. var prop = this._keys[index];
  21714. if (this[prop] !== other[prop]) {
  21715. return false;
  21716. }
  21717. }
  21718. return true;
  21719. };
  21720. MaterialDefines.prototype.cloneTo = function (other) {
  21721. for (var index = 0; index < this._keys.length; index++) {
  21722. var prop = this._keys[index];
  21723. other[prop] = this[prop];
  21724. }
  21725. };
  21726. MaterialDefines.prototype.reset = function () {
  21727. for (var index = 0; index < this._keys.length; index++) {
  21728. var prop = this._keys[index];
  21729. if (typeof (this[prop]) === "number") {
  21730. this[prop] = 0;
  21731. }
  21732. else {
  21733. this[prop] = false;
  21734. }
  21735. }
  21736. };
  21737. MaterialDefines.prototype.toString = function () {
  21738. var result = "";
  21739. for (var index = 0; index < this._keys.length; index++) {
  21740. var prop = this._keys[index];
  21741. if (typeof (this[prop]) === "number") {
  21742. result += "#define " + prop + " " + this[prop] + "\n";
  21743. }
  21744. else if (this[prop]) {
  21745. result += "#define " + prop + "\n";
  21746. }
  21747. }
  21748. return result;
  21749. };
  21750. return MaterialDefines;
  21751. })();
  21752. BABYLON.MaterialDefines = MaterialDefines;
  21753. var Material = (function () {
  21754. function Material(name, scene, doNotAdd) {
  21755. this.name = name;
  21756. this.checkReadyOnEveryCall = false;
  21757. this.checkReadyOnlyOnce = false;
  21758. this.state = "";
  21759. this.alpha = 1.0;
  21760. this.backFaceCulling = true;
  21761. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  21762. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  21763. this.disableDepthWrite = false;
  21764. this.fogEnabled = true;
  21765. this.pointSize = 1.0;
  21766. this.zOffset = 0;
  21767. this._wasPreviouslyReady = false;
  21768. this._fillMode = Material.TriangleFillMode;
  21769. this.id = name;
  21770. this._scene = scene;
  21771. if (!doNotAdd) {
  21772. scene.materials.push(this);
  21773. }
  21774. }
  21775. Object.defineProperty(Material, "TriangleFillMode", {
  21776. get: function () {
  21777. return Material._TriangleFillMode;
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Material, "WireFrameFillMode", {
  21783. get: function () {
  21784. return Material._WireFrameFillMode;
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Material, "PointFillMode", {
  21790. get: function () {
  21791. return Material._PointFillMode;
  21792. },
  21793. enumerable: true,
  21794. configurable: true
  21795. });
  21796. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  21797. get: function () {
  21798. return Material._ClockWiseSideOrientation;
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  21804. get: function () {
  21805. return Material._CounterClockWiseSideOrientation;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(Material.prototype, "wireframe", {
  21811. get: function () {
  21812. return this._fillMode === Material.WireFrameFillMode;
  21813. },
  21814. set: function (value) {
  21815. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Object.defineProperty(Material.prototype, "pointsCloud", {
  21821. get: function () {
  21822. return this._fillMode === Material.PointFillMode;
  21823. },
  21824. set: function (value) {
  21825. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Material.prototype, "fillMode", {
  21831. get: function () {
  21832. return this._fillMode;
  21833. },
  21834. set: function (value) {
  21835. this._fillMode = value;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. /**
  21841. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21842. * subclasses should override adding information pertainent to themselves
  21843. */
  21844. Material.prototype.toString = function (fullDetails) {
  21845. var ret = "Name: " + this.name;
  21846. if (fullDetails) {
  21847. }
  21848. return ret;
  21849. };
  21850. Object.defineProperty(Material.prototype, "isFrozen", {
  21851. get: function () {
  21852. return this.checkReadyOnlyOnce;
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. Material.prototype.freeze = function () {
  21858. this.checkReadyOnlyOnce = true;
  21859. };
  21860. Material.prototype.unfreeze = function () {
  21861. this.checkReadyOnlyOnce = false;
  21862. };
  21863. Material.prototype.isReady = function (mesh, useInstances) {
  21864. return true;
  21865. };
  21866. Material.prototype.getEffect = function () {
  21867. return this._effect;
  21868. };
  21869. Material.prototype.getScene = function () {
  21870. return this._scene;
  21871. };
  21872. Material.prototype.needAlphaBlending = function () {
  21873. return (this.alpha < 1.0);
  21874. };
  21875. Material.prototype.needAlphaTesting = function () {
  21876. return false;
  21877. };
  21878. Material.prototype.getAlphaTestTexture = function () {
  21879. return null;
  21880. };
  21881. Material.prototype.trackCreation = function (onCompiled, onError) {
  21882. };
  21883. Material.prototype.markDirty = function () {
  21884. this._wasPreviouslyReady = false;
  21885. };
  21886. Material.prototype._preBind = function () {
  21887. var engine = this._scene.getEngine();
  21888. engine.enableEffect(this._effect);
  21889. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  21890. };
  21891. Material.prototype.bind = function (world, mesh) {
  21892. this._scene._cachedMaterial = this;
  21893. if (this.onBind) {
  21894. this.onBind(this, mesh);
  21895. }
  21896. if (this.disableDepthWrite) {
  21897. var engine = this._scene.getEngine();
  21898. this._cachedDepthWriteState = engine.getDepthWrite();
  21899. engine.setDepthWrite(false);
  21900. }
  21901. };
  21902. Material.prototype.bindOnlyWorldMatrix = function (world) {
  21903. };
  21904. Material.prototype.unbind = function () {
  21905. if (this.disableDepthWrite) {
  21906. var engine = this._scene.getEngine();
  21907. engine.setDepthWrite(this._cachedDepthWriteState);
  21908. }
  21909. };
  21910. Material.prototype.clone = function (name) {
  21911. return null;
  21912. };
  21913. Material.prototype.getBindedMeshes = function () {
  21914. var result = new Array();
  21915. for (var index = 0; index < this._scene.meshes.length; index++) {
  21916. var mesh = this._scene.meshes[index];
  21917. if (mesh.material === this) {
  21918. result.push(mesh);
  21919. }
  21920. }
  21921. return result;
  21922. };
  21923. Material.prototype.dispose = function (forceDisposeEffect) {
  21924. // Animations
  21925. this.getScene().stopAnimation(this);
  21926. // Remove from scene
  21927. var index = this._scene.materials.indexOf(this);
  21928. if (index >= 0) {
  21929. this._scene.materials.splice(index, 1);
  21930. }
  21931. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  21932. if (forceDisposeEffect && this._effect) {
  21933. this._scene.getEngine()._releaseEffect(this._effect);
  21934. this._effect = null;
  21935. }
  21936. // Remove from meshes
  21937. for (index = 0; index < this._scene.meshes.length; index++) {
  21938. var mesh = this._scene.meshes[index];
  21939. if (mesh.material === this) {
  21940. mesh.material = null;
  21941. }
  21942. }
  21943. // Callback
  21944. if (this.onDispose) {
  21945. this.onDispose();
  21946. }
  21947. };
  21948. Material.prototype.serialize = function () {
  21949. return BABYLON.SerializationHelper.Serialize(this);
  21950. };
  21951. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  21952. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  21953. multiMaterial.id = parsedMultiMaterial.id;
  21954. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  21955. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21956. var subMatId = parsedMultiMaterial.materials[matIndex];
  21957. if (subMatId) {
  21958. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  21959. }
  21960. else {
  21961. multiMaterial.subMaterials.push(null);
  21962. }
  21963. }
  21964. return multiMaterial;
  21965. };
  21966. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  21967. if (!parsedMaterial.customType) {
  21968. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  21969. }
  21970. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  21971. return materialType.Parse(parsedMaterial, scene, rootUrl);
  21972. ;
  21973. };
  21974. Material._TriangleFillMode = 0;
  21975. Material._WireFrameFillMode = 1;
  21976. Material._PointFillMode = 2;
  21977. Material._ClockWiseSideOrientation = 0;
  21978. Material._CounterClockWiseSideOrientation = 1;
  21979. __decorate([
  21980. BABYLON.serialize()
  21981. ], Material.prototype, "id", void 0);
  21982. __decorate([
  21983. BABYLON.serialize()
  21984. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  21985. __decorate([
  21986. BABYLON.serialize()
  21987. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  21988. __decorate([
  21989. BABYLON.serialize()
  21990. ], Material.prototype, "state", void 0);
  21991. __decorate([
  21992. BABYLON.serialize()
  21993. ], Material.prototype, "alpha", void 0);
  21994. __decorate([
  21995. BABYLON.serialize()
  21996. ], Material.prototype, "backFaceCulling", void 0);
  21997. __decorate([
  21998. BABYLON.serialize()
  21999. ], Material.prototype, "sideOrientation", void 0);
  22000. __decorate([
  22001. BABYLON.serialize()
  22002. ], Material.prototype, "alphaMode", void 0);
  22003. __decorate([
  22004. BABYLON.serialize()
  22005. ], Material.prototype, "disableDepthWrite", void 0);
  22006. __decorate([
  22007. BABYLON.serialize()
  22008. ], Material.prototype, "fogEnabled", void 0);
  22009. __decorate([
  22010. BABYLON.serialize()
  22011. ], Material.prototype, "pointSize", void 0);
  22012. __decorate([
  22013. BABYLON.serialize()
  22014. ], Material.prototype, "zOffset", void 0);
  22015. __decorate([
  22016. BABYLON.serialize()
  22017. ], Material.prototype, "wireframe", null);
  22018. __decorate([
  22019. BABYLON.serialize()
  22020. ], Material.prototype, "pointsCloud", null);
  22021. __decorate([
  22022. BABYLON.serialize()
  22023. ], Material.prototype, "fillMode", null);
  22024. return Material;
  22025. })();
  22026. BABYLON.Material = Material;
  22027. })(BABYLON || (BABYLON = {}));
  22028. var BABYLON;
  22029. (function (BABYLON) {
  22030. var StandardMaterialDefines = (function (_super) {
  22031. __extends(StandardMaterialDefines, _super);
  22032. function StandardMaterialDefines() {
  22033. _super.call(this);
  22034. this.DIFFUSE = false;
  22035. this.AMBIENT = false;
  22036. this.OPACITY = false;
  22037. this.OPACITYRGB = false;
  22038. this.REFLECTION = false;
  22039. this.EMISSIVE = false;
  22040. this.SPECULAR = false;
  22041. this.BUMP = false;
  22042. this.PARALLAX = false;
  22043. this.PARALLAXOCCLUSION = false;
  22044. this.SPECULAROVERALPHA = false;
  22045. this.CLIPPLANE = false;
  22046. this.ALPHATEST = false;
  22047. this.ALPHAFROMDIFFUSE = false;
  22048. this.POINTSIZE = false;
  22049. this.FOG = false;
  22050. this.LIGHT0 = false;
  22051. this.LIGHT1 = false;
  22052. this.LIGHT2 = false;
  22053. this.LIGHT3 = false;
  22054. this.SPOTLIGHT0 = false;
  22055. this.SPOTLIGHT1 = false;
  22056. this.SPOTLIGHT2 = false;
  22057. this.SPOTLIGHT3 = false;
  22058. this.HEMILIGHT0 = false;
  22059. this.HEMILIGHT1 = false;
  22060. this.HEMILIGHT2 = false;
  22061. this.HEMILIGHT3 = false;
  22062. this.POINTLIGHT0 = false;
  22063. this.POINTLIGHT1 = false;
  22064. this.POINTLIGHT2 = false;
  22065. this.POINTLIGHT3 = false;
  22066. this.DIRLIGHT0 = false;
  22067. this.DIRLIGHT1 = false;
  22068. this.DIRLIGHT2 = false;
  22069. this.DIRLIGHT3 = false;
  22070. this.SPECULARTERM = false;
  22071. this.SHADOW0 = false;
  22072. this.SHADOW1 = false;
  22073. this.SHADOW2 = false;
  22074. this.SHADOW3 = false;
  22075. this.SHADOWS = false;
  22076. this.SHADOWVSM0 = false;
  22077. this.SHADOWVSM1 = false;
  22078. this.SHADOWVSM2 = false;
  22079. this.SHADOWVSM3 = false;
  22080. this.SHADOWPCF0 = false;
  22081. this.SHADOWPCF1 = false;
  22082. this.SHADOWPCF2 = false;
  22083. this.SHADOWPCF3 = false;
  22084. this.DIFFUSEFRESNEL = false;
  22085. this.OPACITYFRESNEL = false;
  22086. this.REFLECTIONFRESNEL = false;
  22087. this.REFRACTIONFRESNEL = false;
  22088. this.EMISSIVEFRESNEL = false;
  22089. this.FRESNEL = false;
  22090. this.NORMAL = false;
  22091. this.UV1 = false;
  22092. this.UV2 = false;
  22093. this.VERTEXCOLOR = false;
  22094. this.VERTEXALPHA = false;
  22095. this.NUM_BONE_INFLUENCERS = 0;
  22096. this.BonesPerMesh = 0;
  22097. this.INSTANCES = false;
  22098. this.GLOSSINESS = false;
  22099. this.ROUGHNESS = false;
  22100. this.EMISSIVEASILLUMINATION = false;
  22101. this.LINKEMISSIVEWITHDIFFUSE = false;
  22102. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22103. this.LIGHTMAP = false;
  22104. this.USELIGHTMAPASSHADOWMAP = false;
  22105. this.REFLECTIONMAP_3D = false;
  22106. this.REFLECTIONMAP_SPHERICAL = false;
  22107. this.REFLECTIONMAP_PLANAR = false;
  22108. this.REFLECTIONMAP_CUBIC = false;
  22109. this.REFLECTIONMAP_PROJECTION = false;
  22110. this.REFLECTIONMAP_SKYBOX = false;
  22111. this.REFLECTIONMAP_EXPLICIT = false;
  22112. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22113. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22114. this.INVERTCUBICMAP = false;
  22115. this.LOGARITHMICDEPTH = false;
  22116. this.REFRACTION = false;
  22117. this.REFRACTIONMAP_3D = false;
  22118. this.REFLECTIONOVERALPHA = false;
  22119. this._keys = Object.keys(this);
  22120. }
  22121. return StandardMaterialDefines;
  22122. })(BABYLON.MaterialDefines);
  22123. var StandardMaterial = (function (_super) {
  22124. __extends(StandardMaterial, _super);
  22125. function StandardMaterial(name, scene) {
  22126. var _this = this;
  22127. _super.call(this, name, scene);
  22128. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22129. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22130. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22131. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22132. this.specularPower = 64;
  22133. this.useAlphaFromDiffuseTexture = false;
  22134. this.useEmissiveAsIllumination = false;
  22135. this.linkEmissiveWithDiffuse = false;
  22136. this.useReflectionFresnelFromSpecular = false;
  22137. this.useSpecularOverAlpha = false;
  22138. this.useReflectionOverAlpha = false;
  22139. this.disableLighting = false;
  22140. this.useParallax = false;
  22141. this.useParallaxOcclusion = false;
  22142. this.parallaxScaleBias = 0.05;
  22143. this.roughness = 0;
  22144. this.indexOfRefraction = 0.98;
  22145. this.invertRefractionY = true;
  22146. this.useLightmapAsShadowmap = false;
  22147. this.useGlossinessFromSpecularMapAlpha = false;
  22148. this._renderTargets = new BABYLON.SmartArray(16);
  22149. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22150. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22151. this._defines = new StandardMaterialDefines();
  22152. this._cachedDefines = new StandardMaterialDefines();
  22153. this._cachedDefines.BonesPerMesh = -1;
  22154. this.getRenderTargetTextures = function () {
  22155. _this._renderTargets.reset();
  22156. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22157. _this._renderTargets.push(_this.reflectionTexture);
  22158. }
  22159. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22160. _this._renderTargets.push(_this.refractionTexture);
  22161. }
  22162. return _this._renderTargets;
  22163. };
  22164. }
  22165. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22166. get: function () {
  22167. return this._useLogarithmicDepth;
  22168. },
  22169. set: function (value) {
  22170. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22171. },
  22172. enumerable: true,
  22173. configurable: true
  22174. });
  22175. StandardMaterial.prototype.needAlphaBlending = function () {
  22176. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22177. };
  22178. StandardMaterial.prototype.needAlphaTesting = function () {
  22179. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22180. };
  22181. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22182. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22183. };
  22184. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22185. return this.diffuseTexture;
  22186. };
  22187. // Methods
  22188. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22189. if (!mesh) {
  22190. return true;
  22191. }
  22192. if (this._defines.INSTANCES !== useInstances) {
  22193. return false;
  22194. }
  22195. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22196. return true;
  22197. }
  22198. return false;
  22199. };
  22200. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22201. if (this.isFrozen) {
  22202. if (this._wasPreviouslyReady) {
  22203. return true;
  22204. }
  22205. }
  22206. var scene = this.getScene();
  22207. if (!this.checkReadyOnEveryCall) {
  22208. if (this._renderId === scene.getRenderId()) {
  22209. if (this._checkCache(scene, mesh, useInstances)) {
  22210. return true;
  22211. }
  22212. }
  22213. }
  22214. var engine = scene.getEngine();
  22215. var needNormals = false;
  22216. var needUVs = false;
  22217. this._defines.reset();
  22218. // Textures
  22219. if (scene.texturesEnabled) {
  22220. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22221. if (!this.diffuseTexture.isReady()) {
  22222. return false;
  22223. }
  22224. else {
  22225. needUVs = true;
  22226. this._defines.DIFFUSE = true;
  22227. }
  22228. }
  22229. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22230. if (!this.ambientTexture.isReady()) {
  22231. return false;
  22232. }
  22233. else {
  22234. needUVs = true;
  22235. this._defines.AMBIENT = true;
  22236. }
  22237. }
  22238. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22239. if (!this.opacityTexture.isReady()) {
  22240. return false;
  22241. }
  22242. else {
  22243. needUVs = true;
  22244. this._defines.OPACITY = true;
  22245. if (this.opacityTexture.getAlphaFromRGB) {
  22246. this._defines.OPACITYRGB = true;
  22247. }
  22248. }
  22249. }
  22250. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22251. if (!this.reflectionTexture.isReady()) {
  22252. return false;
  22253. }
  22254. else {
  22255. needNormals = true;
  22256. this._defines.REFLECTION = true;
  22257. if (this.roughness > 0) {
  22258. this._defines.ROUGHNESS = true;
  22259. }
  22260. if (this.useReflectionOverAlpha) {
  22261. this._defines.REFLECTIONOVERALPHA = true;
  22262. }
  22263. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22264. this._defines.INVERTCUBICMAP = true;
  22265. }
  22266. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22267. switch (this.reflectionTexture.coordinatesMode) {
  22268. case BABYLON.Texture.CUBIC_MODE:
  22269. case BABYLON.Texture.INVCUBIC_MODE:
  22270. this._defines.REFLECTIONMAP_CUBIC = true;
  22271. break;
  22272. case BABYLON.Texture.EXPLICIT_MODE:
  22273. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22274. break;
  22275. case BABYLON.Texture.PLANAR_MODE:
  22276. this._defines.REFLECTIONMAP_PLANAR = true;
  22277. break;
  22278. case BABYLON.Texture.PROJECTION_MODE:
  22279. this._defines.REFLECTIONMAP_PROJECTION = true;
  22280. break;
  22281. case BABYLON.Texture.SKYBOX_MODE:
  22282. this._defines.REFLECTIONMAP_SKYBOX = true;
  22283. break;
  22284. case BABYLON.Texture.SPHERICAL_MODE:
  22285. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22286. break;
  22287. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22288. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22289. break;
  22290. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22291. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22292. break;
  22293. }
  22294. }
  22295. }
  22296. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22297. if (!this.emissiveTexture.isReady()) {
  22298. return false;
  22299. }
  22300. else {
  22301. needUVs = true;
  22302. this._defines.EMISSIVE = true;
  22303. }
  22304. }
  22305. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22306. if (!this.lightmapTexture.isReady()) {
  22307. return false;
  22308. }
  22309. else {
  22310. needUVs = true;
  22311. this._defines.LIGHTMAP = true;
  22312. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22313. }
  22314. }
  22315. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22316. if (!this.specularTexture.isReady()) {
  22317. return false;
  22318. }
  22319. else {
  22320. needUVs = true;
  22321. this._defines.SPECULAR = true;
  22322. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22323. }
  22324. }
  22325. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22326. if (!this.bumpTexture.isReady()) {
  22327. return false;
  22328. }
  22329. else {
  22330. needUVs = true;
  22331. this._defines.BUMP = true;
  22332. if (this.useParallax) {
  22333. this._defines.PARALLAX = true;
  22334. if (this.useParallaxOcclusion) {
  22335. this._defines.PARALLAXOCCLUSION = true;
  22336. }
  22337. }
  22338. }
  22339. }
  22340. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22341. if (!this.refractionTexture.isReady()) {
  22342. return false;
  22343. }
  22344. else {
  22345. needUVs = true;
  22346. this._defines.REFRACTION = true;
  22347. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22348. }
  22349. }
  22350. }
  22351. // Effect
  22352. if (scene.clipPlane) {
  22353. this._defines.CLIPPLANE = true;
  22354. }
  22355. if (engine.getAlphaTesting()) {
  22356. this._defines.ALPHATEST = true;
  22357. }
  22358. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22359. this._defines.ALPHAFROMDIFFUSE = true;
  22360. }
  22361. if (this.useEmissiveAsIllumination) {
  22362. this._defines.EMISSIVEASILLUMINATION = true;
  22363. }
  22364. if (this.linkEmissiveWithDiffuse) {
  22365. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22366. }
  22367. if (this.useLogarithmicDepth) {
  22368. this._defines.LOGARITHMICDEPTH = true;
  22369. }
  22370. // Point size
  22371. if (this.pointsCloud || scene.forcePointsCloud) {
  22372. this._defines.POINTSIZE = true;
  22373. }
  22374. // Fog
  22375. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22376. this._defines.FOG = true;
  22377. }
  22378. if (scene.lightsEnabled && !this.disableLighting) {
  22379. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22380. }
  22381. if (StandardMaterial.FresnelEnabled) {
  22382. // Fresnel
  22383. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22384. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22385. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22386. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22387. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22388. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22389. this._defines.DIFFUSEFRESNEL = true;
  22390. }
  22391. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22392. this._defines.OPACITYFRESNEL = true;
  22393. }
  22394. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22395. this._defines.REFLECTIONFRESNEL = true;
  22396. if (this.useReflectionFresnelFromSpecular) {
  22397. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22398. }
  22399. }
  22400. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22401. this._defines.REFRACTIONFRESNEL = true;
  22402. }
  22403. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22404. this._defines.EMISSIVEFRESNEL = true;
  22405. }
  22406. needNormals = true;
  22407. this._defines.FRESNEL = true;
  22408. }
  22409. }
  22410. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22411. this._defines.SPECULAROVERALPHA = true;
  22412. }
  22413. // Attribs
  22414. if (mesh) {
  22415. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22416. this._defines.NORMAL = true;
  22417. }
  22418. if (needUVs) {
  22419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22420. this._defines.UV1 = true;
  22421. }
  22422. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22423. this._defines.UV2 = true;
  22424. }
  22425. }
  22426. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22427. this._defines.VERTEXCOLOR = true;
  22428. if (mesh.hasVertexAlpha) {
  22429. this._defines.VERTEXALPHA = true;
  22430. }
  22431. }
  22432. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22433. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22434. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22435. }
  22436. // Instances
  22437. if (useInstances) {
  22438. this._defines.INSTANCES = true;
  22439. }
  22440. }
  22441. // Get correct effect
  22442. if (!this._defines.isEqual(this._cachedDefines)) {
  22443. this._defines.cloneTo(this._cachedDefines);
  22444. scene.resetCachedMaterial();
  22445. // Fallbacks
  22446. var fallbacks = new BABYLON.EffectFallbacks();
  22447. if (this._defines.REFLECTION) {
  22448. fallbacks.addFallback(0, "REFLECTION");
  22449. }
  22450. if (this._defines.SPECULAR) {
  22451. fallbacks.addFallback(0, "SPECULAR");
  22452. }
  22453. if (this._defines.BUMP) {
  22454. fallbacks.addFallback(0, "BUMP");
  22455. }
  22456. if (this._defines.PARALLAX) {
  22457. fallbacks.addFallback(1, "PARALLAX");
  22458. }
  22459. if (this._defines.PARALLAXOCCLUSION) {
  22460. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22461. }
  22462. if (this._defines.SPECULAROVERALPHA) {
  22463. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22464. }
  22465. if (this._defines.FOG) {
  22466. fallbacks.addFallback(1, "FOG");
  22467. }
  22468. if (this._defines.POINTSIZE) {
  22469. fallbacks.addFallback(0, "POINTSIZE");
  22470. }
  22471. if (this._defines.LOGARITHMICDEPTH) {
  22472. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22473. }
  22474. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22475. if (this._defines.SPECULARTERM) {
  22476. fallbacks.addFallback(0, "SPECULARTERM");
  22477. }
  22478. if (this._defines.DIFFUSEFRESNEL) {
  22479. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22480. }
  22481. if (this._defines.OPACITYFRESNEL) {
  22482. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22483. }
  22484. if (this._defines.REFLECTIONFRESNEL) {
  22485. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22486. }
  22487. if (this._defines.EMISSIVEFRESNEL) {
  22488. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22489. }
  22490. if (this._defines.FRESNEL) {
  22491. fallbacks.addFallback(4, "FRESNEL");
  22492. }
  22493. //Attributes
  22494. var attribs = [BABYLON.VertexBuffer.PositionKind];
  22495. if (this._defines.NORMAL) {
  22496. attribs.push(BABYLON.VertexBuffer.NormalKind);
  22497. }
  22498. if (this._defines.UV1) {
  22499. attribs.push(BABYLON.VertexBuffer.UVKind);
  22500. }
  22501. if (this._defines.UV2) {
  22502. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22503. }
  22504. if (this._defines.VERTEXCOLOR) {
  22505. attribs.push(BABYLON.VertexBuffer.ColorKind);
  22506. }
  22507. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  22508. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  22509. // Legacy browser patch
  22510. var shaderName = "default";
  22511. if (!scene.getEngine().getCaps().standardDerivatives) {
  22512. shaderName = "legacydefault";
  22513. }
  22514. var join = this._defines.toString();
  22515. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  22516. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  22517. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  22518. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  22519. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  22520. "vFogInfos", "vFogColor", "pointSize",
  22521. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  22522. "mBones",
  22523. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  22524. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  22525. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  22526. "logarithmicDepthConstant"
  22527. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  22528. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  22529. ], join, fallbacks, this.onCompiled, this.onError);
  22530. }
  22531. if (!this._effect.isReady()) {
  22532. return false;
  22533. }
  22534. this._renderId = scene.getRenderId();
  22535. this._wasPreviouslyReady = true;
  22536. if (mesh) {
  22537. if (!mesh._materialDefines) {
  22538. mesh._materialDefines = new StandardMaterialDefines();
  22539. }
  22540. this._defines.cloneTo(mesh._materialDefines);
  22541. }
  22542. return true;
  22543. };
  22544. StandardMaterial.prototype.unbind = function () {
  22545. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  22546. this._effect.setTexture("reflection2DSampler", null);
  22547. }
  22548. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  22549. this._effect.setTexture("refraction2DSampler", null);
  22550. }
  22551. _super.prototype.unbind.call(this);
  22552. };
  22553. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22554. this._effect.setMatrix("world", world);
  22555. };
  22556. StandardMaterial.prototype.bind = function (world, mesh) {
  22557. var scene = this.getScene();
  22558. // Matrices
  22559. this.bindOnlyWorldMatrix(world);
  22560. // Bones
  22561. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  22562. if (scene.getCachedMaterial() !== this) {
  22563. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22564. if (StandardMaterial.FresnelEnabled) {
  22565. // Fresnel
  22566. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22567. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  22568. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  22569. }
  22570. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22571. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  22572. }
  22573. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22574. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  22575. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  22576. }
  22577. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22578. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  22579. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  22580. }
  22581. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22582. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  22583. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  22584. }
  22585. }
  22586. // Textures
  22587. if (scene.texturesEnabled) {
  22588. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22589. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  22590. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  22591. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  22592. }
  22593. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22594. this._effect.setTexture("ambientSampler", this.ambientTexture);
  22595. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  22596. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  22597. }
  22598. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22599. this._effect.setTexture("opacitySampler", this.opacityTexture);
  22600. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  22601. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  22602. }
  22603. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22604. if (this.reflectionTexture.isCube) {
  22605. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  22606. }
  22607. else {
  22608. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  22609. }
  22610. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  22611. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  22612. }
  22613. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22614. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  22615. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  22616. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  22617. }
  22618. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22619. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  22620. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  22621. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  22622. }
  22623. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22624. this._effect.setTexture("specularSampler", this.specularTexture);
  22625. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  22626. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  22627. }
  22628. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  22629. this._effect.setTexture("bumpSampler", this.bumpTexture);
  22630. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  22631. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  22632. }
  22633. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22634. var depth = 1.0;
  22635. if (this.refractionTexture.isCube) {
  22636. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  22637. }
  22638. else {
  22639. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  22640. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  22641. if (this.refractionTexture.depth) {
  22642. depth = this.refractionTexture.depth;
  22643. }
  22644. }
  22645. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  22646. }
  22647. }
  22648. // Clip plane
  22649. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  22650. // Point size
  22651. if (this.pointsCloud) {
  22652. this._effect.setFloat("pointSize", this.pointSize);
  22653. }
  22654. // Colors
  22655. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  22656. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  22657. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  22658. if (this._defines.SPECULARTERM) {
  22659. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  22660. }
  22661. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  22662. }
  22663. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  22664. // Diffuse
  22665. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  22666. // Lights
  22667. if (scene.lightsEnabled && !this.disableLighting) {
  22668. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  22669. }
  22670. // View
  22671. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  22672. this._effect.setMatrix("view", scene.getViewMatrix());
  22673. }
  22674. // Fog
  22675. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  22676. // Log. depth
  22677. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  22678. }
  22679. _super.prototype.bind.call(this, world, mesh);
  22680. };
  22681. StandardMaterial.prototype.getAnimatables = function () {
  22682. var results = [];
  22683. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  22684. results.push(this.diffuseTexture);
  22685. }
  22686. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  22687. results.push(this.ambientTexture);
  22688. }
  22689. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  22690. results.push(this.opacityTexture);
  22691. }
  22692. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  22693. results.push(this.reflectionTexture);
  22694. }
  22695. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  22696. results.push(this.emissiveTexture);
  22697. }
  22698. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  22699. results.push(this.specularTexture);
  22700. }
  22701. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  22702. results.push(this.bumpTexture);
  22703. }
  22704. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  22705. results.push(this.lightmapTexture);
  22706. }
  22707. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  22708. results.push(this.refractionTexture);
  22709. }
  22710. return results;
  22711. };
  22712. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  22713. if (this.diffuseTexture) {
  22714. this.diffuseTexture.dispose();
  22715. }
  22716. if (this.ambientTexture) {
  22717. this.ambientTexture.dispose();
  22718. }
  22719. if (this.opacityTexture) {
  22720. this.opacityTexture.dispose();
  22721. }
  22722. if (this.reflectionTexture) {
  22723. this.reflectionTexture.dispose();
  22724. }
  22725. if (this.emissiveTexture) {
  22726. this.emissiveTexture.dispose();
  22727. }
  22728. if (this.specularTexture) {
  22729. this.specularTexture.dispose();
  22730. }
  22731. if (this.bumpTexture) {
  22732. this.bumpTexture.dispose();
  22733. }
  22734. if (this.lightmapTexture) {
  22735. this.lightmapTexture.dispose();
  22736. }
  22737. if (this.refractionTexture) {
  22738. this.refractionTexture.dispose();
  22739. }
  22740. _super.prototype.dispose.call(this, forceDisposeEffect);
  22741. };
  22742. StandardMaterial.prototype.clone = function (name) {
  22743. var _this = this;
  22744. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  22745. };
  22746. StandardMaterial.prototype.serialize = function () {
  22747. return BABYLON.SerializationHelper.Serialize(this);
  22748. };
  22749. // Statics
  22750. StandardMaterial.Parse = function (source, scene, rootUrl) {
  22751. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  22752. };
  22753. // Flags used to enable or disable a type of texture for all Standard Materials
  22754. StandardMaterial.DiffuseTextureEnabled = true;
  22755. StandardMaterial.AmbientTextureEnabled = true;
  22756. StandardMaterial.OpacityTextureEnabled = true;
  22757. StandardMaterial.ReflectionTextureEnabled = true;
  22758. StandardMaterial.EmissiveTextureEnabled = true;
  22759. StandardMaterial.SpecularTextureEnabled = true;
  22760. StandardMaterial.BumpTextureEnabled = true;
  22761. StandardMaterial.FresnelEnabled = true;
  22762. StandardMaterial.LightmapTextureEnabled = true;
  22763. StandardMaterial.RefractionTextureEnabled = true;
  22764. __decorate([
  22765. BABYLON.serializeAsTexture()
  22766. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  22767. __decorate([
  22768. BABYLON.serializeAsTexture()
  22769. ], StandardMaterial.prototype, "ambientTexture", void 0);
  22770. __decorate([
  22771. BABYLON.serializeAsTexture()
  22772. ], StandardMaterial.prototype, "opacityTexture", void 0);
  22773. __decorate([
  22774. BABYLON.serializeAsTexture()
  22775. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  22776. __decorate([
  22777. BABYLON.serializeAsTexture()
  22778. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  22779. __decorate([
  22780. BABYLON.serializeAsTexture()
  22781. ], StandardMaterial.prototype, "specularTexture", void 0);
  22782. __decorate([
  22783. BABYLON.serializeAsTexture()
  22784. ], StandardMaterial.prototype, "bumpTexture", void 0);
  22785. __decorate([
  22786. BABYLON.serializeAsTexture()
  22787. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  22788. __decorate([
  22789. BABYLON.serializeAsTexture()
  22790. ], StandardMaterial.prototype, "refractionTexture", void 0);
  22791. __decorate([
  22792. BABYLON.serializeAsColor3("ambient")
  22793. ], StandardMaterial.prototype, "ambientColor", void 0);
  22794. __decorate([
  22795. BABYLON.serializeAsColor3("diffuse")
  22796. ], StandardMaterial.prototype, "diffuseColor", void 0);
  22797. __decorate([
  22798. BABYLON.serializeAsColor3("specular")
  22799. ], StandardMaterial.prototype, "specularColor", void 0);
  22800. __decorate([
  22801. BABYLON.serializeAsColor3("emissive")
  22802. ], StandardMaterial.prototype, "emissiveColor", void 0);
  22803. __decorate([
  22804. BABYLON.serialize()
  22805. ], StandardMaterial.prototype, "specularPower", void 0);
  22806. __decorate([
  22807. BABYLON.serialize()
  22808. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  22809. __decorate([
  22810. BABYLON.serialize()
  22811. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  22812. __decorate([
  22813. BABYLON.serialize()
  22814. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  22815. __decorate([
  22816. BABYLON.serialize()
  22817. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  22818. __decorate([
  22819. BABYLON.serialize()
  22820. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  22821. __decorate([
  22822. BABYLON.serialize()
  22823. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  22824. __decorate([
  22825. BABYLON.serialize()
  22826. ], StandardMaterial.prototype, "disableLighting", void 0);
  22827. __decorate([
  22828. BABYLON.serialize()
  22829. ], StandardMaterial.prototype, "useParallax", void 0);
  22830. __decorate([
  22831. BABYLON.serialize()
  22832. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  22833. __decorate([
  22834. BABYLON.serialize()
  22835. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  22836. __decorate([
  22837. BABYLON.serialize()
  22838. ], StandardMaterial.prototype, "roughness", void 0);
  22839. __decorate([
  22840. BABYLON.serialize()
  22841. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  22842. __decorate([
  22843. BABYLON.serialize()
  22844. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  22845. __decorate([
  22846. BABYLON.serialize()
  22847. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  22848. __decorate([
  22849. BABYLON.serializeAsFresnelParameters()
  22850. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  22851. __decorate([
  22852. BABYLON.serializeAsFresnelParameters()
  22853. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  22854. __decorate([
  22855. BABYLON.serializeAsFresnelParameters()
  22856. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  22857. __decorate([
  22858. BABYLON.serializeAsFresnelParameters()
  22859. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  22860. __decorate([
  22861. BABYLON.serializeAsFresnelParameters()
  22862. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  22863. __decorate([
  22864. BABYLON.serialize()
  22865. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  22866. __decorate([
  22867. BABYLON.serialize()
  22868. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  22869. return StandardMaterial;
  22870. })(BABYLON.Material);
  22871. BABYLON.StandardMaterial = StandardMaterial;
  22872. })(BABYLON || (BABYLON = {}));
  22873. var BABYLON;
  22874. (function (BABYLON) {
  22875. var MultiMaterial = (function (_super) {
  22876. __extends(MultiMaterial, _super);
  22877. function MultiMaterial(name, scene) {
  22878. _super.call(this, name, scene, true);
  22879. this.subMaterials = new Array();
  22880. scene.multiMaterials.push(this);
  22881. }
  22882. // Properties
  22883. MultiMaterial.prototype.getSubMaterial = function (index) {
  22884. if (index < 0 || index >= this.subMaterials.length) {
  22885. return this.getScene().defaultMaterial;
  22886. }
  22887. return this.subMaterials[index];
  22888. };
  22889. // Methods
  22890. MultiMaterial.prototype.isReady = function (mesh) {
  22891. for (var index = 0; index < this.subMaterials.length; index++) {
  22892. var subMaterial = this.subMaterials[index];
  22893. if (subMaterial) {
  22894. if (!this.subMaterials[index].isReady(mesh)) {
  22895. return false;
  22896. }
  22897. }
  22898. }
  22899. return true;
  22900. };
  22901. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  22902. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  22903. for (var index = 0; index < this.subMaterials.length; index++) {
  22904. var subMaterial = null;
  22905. if (cloneChildren) {
  22906. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  22907. }
  22908. else {
  22909. subMaterial = this.subMaterials[index];
  22910. }
  22911. newMultiMaterial.subMaterials.push(subMaterial);
  22912. }
  22913. return newMultiMaterial;
  22914. };
  22915. MultiMaterial.prototype.serialize = function () {
  22916. var serializationObject = {};
  22917. serializationObject.name = this.name;
  22918. serializationObject.id = this.id;
  22919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22920. serializationObject.materials = [];
  22921. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  22922. var subMat = this.subMaterials[matIndex];
  22923. if (subMat) {
  22924. serializationObject.materials.push(subMat.id);
  22925. }
  22926. else {
  22927. serializationObject.materials.push(null);
  22928. }
  22929. }
  22930. return serializationObject;
  22931. };
  22932. return MultiMaterial;
  22933. })(BABYLON.Material);
  22934. BABYLON.MultiMaterial = MultiMaterial;
  22935. })(BABYLON || (BABYLON = {}));
  22936. var BABYLON;
  22937. (function (BABYLON) {
  22938. var SceneLoader = (function () {
  22939. function SceneLoader() {
  22940. }
  22941. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  22942. get: function () {
  22943. return 0;
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  22949. get: function () {
  22950. return 1;
  22951. },
  22952. enumerable: true,
  22953. configurable: true
  22954. });
  22955. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  22956. get: function () {
  22957. return 2;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  22963. get: function () {
  22964. return 3;
  22965. },
  22966. enumerable: true,
  22967. configurable: true
  22968. });
  22969. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  22970. get: function () {
  22971. return SceneLoader._ForceFullSceneLoadingForIncremental;
  22972. },
  22973. set: function (value) {
  22974. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  22975. },
  22976. enumerable: true,
  22977. configurable: true
  22978. });
  22979. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  22980. get: function () {
  22981. return SceneLoader._ShowLoadingScreen;
  22982. },
  22983. set: function (value) {
  22984. SceneLoader._ShowLoadingScreen = value;
  22985. },
  22986. enumerable: true,
  22987. configurable: true
  22988. });
  22989. Object.defineProperty(SceneLoader, "loggingLevel", {
  22990. get: function () {
  22991. return SceneLoader._loggingLevel;
  22992. },
  22993. set: function (value) {
  22994. SceneLoader._loggingLevel = value;
  22995. },
  22996. enumerable: true,
  22997. configurable: true
  22998. });
  22999. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23000. var dotPosition = sceneFilename.lastIndexOf(".");
  23001. var queryStringPosition = sceneFilename.indexOf("?");
  23002. if (queryStringPosition === -1) {
  23003. queryStringPosition = sceneFilename.length;
  23004. }
  23005. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23006. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23007. var plugin = this._registeredPlugins[index];
  23008. if (plugin.extensions.indexOf(extension) !== -1) {
  23009. return plugin;
  23010. }
  23011. }
  23012. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23013. };
  23014. // Public functions
  23015. SceneLoader.GetPluginForExtension = function (extension) {
  23016. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23017. var plugin = this._registeredPlugins[index];
  23018. if (plugin.extensions.indexOf(extension) !== -1) {
  23019. return plugin;
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. SceneLoader.RegisterPlugin = function (plugin) {
  23025. plugin.extensions = plugin.extensions.toLowerCase();
  23026. SceneLoader._registeredPlugins.push(plugin);
  23027. };
  23028. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23029. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23030. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23031. return;
  23032. }
  23033. var loadingToken = {};
  23034. scene._addPendingData(loadingToken);
  23035. var manifestChecked = function (success) {
  23036. scene.database = database;
  23037. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23038. var importMeshFromData = function (data) {
  23039. var meshes = [];
  23040. var particleSystems = [];
  23041. var skeletons = [];
  23042. try {
  23043. if (plugin.importMesh) {
  23044. var syncedPlugin = plugin;
  23045. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23046. if (onerror) {
  23047. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23048. }
  23049. scene._removePendingData(loadingToken);
  23050. return;
  23051. }
  23052. if (onsuccess) {
  23053. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23054. onsuccess(meshes, particleSystems, skeletons);
  23055. scene._removePendingData(loadingToken);
  23056. }
  23057. }
  23058. else {
  23059. var asyncedPlugin = plugin;
  23060. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23061. if (onsuccess) {
  23062. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23063. onsuccess(meshes, particleSystems, skeletons);
  23064. scene._removePendingData(loadingToken);
  23065. }
  23066. }, function () {
  23067. if (onerror) {
  23068. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23069. }
  23070. scene._removePendingData(loadingToken);
  23071. });
  23072. }
  23073. }
  23074. catch (e) {
  23075. if (onerror) {
  23076. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23077. }
  23078. scene._removePendingData(loadingToken);
  23079. }
  23080. };
  23081. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23082. // Direct load
  23083. importMeshFromData(sceneFilename.substr(5));
  23084. return;
  23085. }
  23086. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23087. importMeshFromData(data);
  23088. }, progressCallBack, database);
  23089. };
  23090. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23091. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23092. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23093. }
  23094. else {
  23095. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23096. manifestChecked(true);
  23097. }
  23098. };
  23099. /**
  23100. * Load a scene
  23101. * @param rootUrl a string that defines the root url for scene and resources
  23102. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23103. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23104. */
  23105. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23106. if (!SceneLoader._warned) {
  23107. BABYLON.Tools.Warn("SceneLoader.Load deprecated since 2.4. Use SceneLoader.Append.");
  23108. SceneLoader._warned = true;
  23109. }
  23110. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23111. };
  23112. /**
  23113. * Append a scene
  23114. * @param rootUrl a string that defines the root url for scene and resources
  23115. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23116. * @param scene is the instance of BABYLON.Scene to append to
  23117. */
  23118. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23119. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23120. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23121. return;
  23122. }
  23123. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23124. var database;
  23125. var loadingToken = {};
  23126. scene._addPendingData(loadingToken);
  23127. if (SceneLoader.ShowLoadingScreen) {
  23128. scene.getEngine().displayLoadingUI();
  23129. }
  23130. var loadSceneFromData = function (data) {
  23131. scene.database = database;
  23132. if (plugin.load) {
  23133. var syncedPlugin = plugin;
  23134. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23135. if (onerror) {
  23136. onerror(scene);
  23137. }
  23138. scene._removePendingData(loadingToken);
  23139. scene.getEngine().hideLoadingUI();
  23140. return;
  23141. }
  23142. if (onsuccess) {
  23143. onsuccess(scene);
  23144. }
  23145. scene._removePendingData(loadingToken);
  23146. }
  23147. else {
  23148. var asyncedPlugin = plugin;
  23149. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23150. if (onsuccess) {
  23151. onsuccess(scene);
  23152. }
  23153. }, function () {
  23154. if (onerror) {
  23155. onerror(scene);
  23156. }
  23157. scene._removePendingData(loadingToken);
  23158. scene.getEngine().hideLoadingUI();
  23159. });
  23160. }
  23161. if (SceneLoader.ShowLoadingScreen) {
  23162. scene.executeWhenReady(function () {
  23163. scene.getEngine().hideLoadingUI();
  23164. });
  23165. }
  23166. };
  23167. var manifestChecked = function (success) {
  23168. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23169. };
  23170. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23171. // Direct load
  23172. loadSceneFromData(sceneFilename.substr(5));
  23173. return;
  23174. }
  23175. if (rootUrl.indexOf("file:") === -1) {
  23176. if (scene.getEngine().enableOfflineSupport) {
  23177. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23178. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23179. }
  23180. else {
  23181. manifestChecked(true);
  23182. }
  23183. }
  23184. else {
  23185. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23186. }
  23187. };
  23188. // Flags
  23189. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23190. SceneLoader._ShowLoadingScreen = true;
  23191. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23192. // Members
  23193. SceneLoader._registeredPlugins = new Array();
  23194. return SceneLoader;
  23195. })();
  23196. BABYLON.SceneLoader = SceneLoader;
  23197. ;
  23198. })(BABYLON || (BABYLON = {}));
  23199. var BABYLON;
  23200. (function (BABYLON) {
  23201. var Internals;
  23202. (function (Internals) {
  23203. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23204. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23205. var parsedMaterial = parsedData.materials[index];
  23206. if (parsedMaterial.id === id) {
  23207. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23208. }
  23209. }
  23210. return null;
  23211. };
  23212. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23213. names = (names instanceof Array) ? names : [names];
  23214. for (var i in names) {
  23215. if (mesh.name === names[i]) {
  23216. hierarchyIds.push(mesh.id);
  23217. return true;
  23218. }
  23219. }
  23220. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23221. hierarchyIds.push(mesh.id);
  23222. return true;
  23223. }
  23224. return false;
  23225. };
  23226. var logOperation = function (operation, producer) {
  23227. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23228. };
  23229. BABYLON.SceneLoader.RegisterPlugin({
  23230. extensions: ".babylon",
  23231. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23232. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23233. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23234. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23235. // and avoid problems with multiple concurrent .babylon loads.
  23236. var log = "importMesh has failed JSON parse";
  23237. try {
  23238. var parsedData = JSON.parse(data);
  23239. log = "";
  23240. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23241. var loadedSkeletonsIds = [];
  23242. var loadedMaterialsIds = [];
  23243. var hierarchyIds = [];
  23244. var index;
  23245. var cache;
  23246. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23247. var parsedMesh = parsedData.meshes[index];
  23248. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23249. if (meshesNames instanceof Array) {
  23250. // Remove found mesh name from list.
  23251. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23252. }
  23253. //Geometry?
  23254. if (parsedMesh.geometryId) {
  23255. //does the file contain geometries?
  23256. if (parsedData.geometries) {
  23257. //find the correct geometry and add it to the scene
  23258. var found = false;
  23259. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23260. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23261. return;
  23262. }
  23263. else {
  23264. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23265. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23266. switch (geometryType) {
  23267. case "boxes":
  23268. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23269. break;
  23270. case "spheres":
  23271. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23272. break;
  23273. case "cylinders":
  23274. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23275. break;
  23276. case "toruses":
  23277. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23278. break;
  23279. case "grounds":
  23280. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23281. break;
  23282. case "planes":
  23283. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23284. break;
  23285. case "torusKnots":
  23286. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23287. break;
  23288. case "vertexData":
  23289. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23290. break;
  23291. }
  23292. found = true;
  23293. }
  23294. });
  23295. }
  23296. });
  23297. if (!found) {
  23298. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23299. }
  23300. }
  23301. }
  23302. // Material ?
  23303. if (parsedMesh.materialId) {
  23304. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23305. if (!materialFound && parsedData.multiMaterials) {
  23306. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23307. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23308. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23309. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23310. var subMatId = parsedMultiMaterial.materials[matIndex];
  23311. loadedMaterialsIds.push(subMatId);
  23312. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23313. log += "\n\tMaterial " + mat.toString(fullDetails);
  23314. }
  23315. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23316. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23317. materialFound = true;
  23318. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23319. break;
  23320. }
  23321. }
  23322. }
  23323. if (!materialFound) {
  23324. loadedMaterialsIds.push(parsedMesh.materialId);
  23325. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23326. if (!mat) {
  23327. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23328. }
  23329. else {
  23330. log += "\n\tMaterial " + mat.toString(fullDetails);
  23331. }
  23332. }
  23333. }
  23334. // Skeleton ?
  23335. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23336. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23337. if (!skeletonAlreadyLoaded) {
  23338. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23339. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23340. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23341. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23342. skeletons.push(skeleton);
  23343. loadedSkeletonsIds.push(parsedSkeleton.id);
  23344. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23345. }
  23346. }
  23347. }
  23348. }
  23349. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23350. meshes.push(mesh);
  23351. log += "\n\tMesh " + mesh.toString(fullDetails);
  23352. }
  23353. }
  23354. // Connecting parents
  23355. var currentMesh;
  23356. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23357. currentMesh = scene.meshes[index];
  23358. if (currentMesh._waitingParentId) {
  23359. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23360. currentMesh._waitingParentId = undefined;
  23361. }
  23362. }
  23363. // freeze and compute world matrix application
  23364. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23365. currentMesh = scene.meshes[index];
  23366. if (currentMesh._waitingFreezeWorldMatrix) {
  23367. currentMesh.freezeWorldMatrix();
  23368. currentMesh._waitingFreezeWorldMatrix = undefined;
  23369. }
  23370. else {
  23371. currentMesh.computeWorldMatrix(true);
  23372. }
  23373. }
  23374. // Particles
  23375. if (parsedData.particleSystems) {
  23376. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23377. var parsedParticleSystem = parsedData.particleSystems[index];
  23378. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23379. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23380. }
  23381. }
  23382. }
  23383. return true;
  23384. }
  23385. catch (err) {
  23386. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23387. log = null;
  23388. throw err;
  23389. }
  23390. finally {
  23391. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23392. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23393. }
  23394. }
  23395. },
  23396. load: function (scene, data, rootUrl) {
  23397. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23398. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23399. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23400. // and avoid problems with multiple concurrent .babylon loads.
  23401. var log = "importScene has failed JSON parse";
  23402. try {
  23403. var parsedData = JSON.parse(data);
  23404. log = "";
  23405. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23406. // Scene
  23407. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23408. scene.autoClear = parsedData.autoClear;
  23409. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23410. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23411. if (parsedData.gravity) {
  23412. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23413. }
  23414. // Fog
  23415. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23416. scene.fogMode = parsedData.fogMode;
  23417. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23418. scene.fogStart = parsedData.fogStart;
  23419. scene.fogEnd = parsedData.fogEnd;
  23420. scene.fogDensity = parsedData.fogDensity;
  23421. log += "\tFog mode for scene: ";
  23422. switch (scene.fogMode) {
  23423. // getters not compiling, so using hardcoded
  23424. case 1:
  23425. log += "exp\n";
  23426. break;
  23427. case 2:
  23428. log += "exp2\n";
  23429. break;
  23430. case 3:
  23431. log += "linear\n";
  23432. break;
  23433. }
  23434. }
  23435. //Physics
  23436. if (parsedData.physicsEnabled) {
  23437. var physicsPlugin;
  23438. if (parsedData.physicsEngine === "cannon") {
  23439. physicsPlugin = new BABYLON.CannonJSPlugin();
  23440. }
  23441. else if (parsedData.physicsEngine === "oimo") {
  23442. physicsPlugin = new BABYLON.OimoJSPlugin();
  23443. }
  23444. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23445. //else - default engine, which is currently oimo
  23446. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23447. scene.enablePhysics(physicsGravity, physicsPlugin);
  23448. }
  23449. //collisions, if defined. otherwise, default is true
  23450. if (parsedData.collisionsEnabled != undefined) {
  23451. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23452. }
  23453. scene.workerCollisions = !!parsedData.workerCollisions;
  23454. var index;
  23455. var cache;
  23456. // Lights
  23457. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23458. var parsedLight = parsedData.lights[index];
  23459. var light = BABYLON.Light.Parse(parsedLight, scene);
  23460. log += (index === 0 ? "\n\tLights:" : "");
  23461. log += "\n\t\t" + light.toString(fullDetails);
  23462. }
  23463. // Animations
  23464. if (parsedData.animations) {
  23465. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23466. var parsedAnimation = parsedData.animations[index];
  23467. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23468. scene.animations.push(animation);
  23469. log += (index === 0 ? "\n\tAnimations:" : "");
  23470. log += "\n\t\t" + animation.toString(fullDetails);
  23471. }
  23472. }
  23473. // Materials
  23474. if (parsedData.materials) {
  23475. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23476. var parsedMaterial = parsedData.materials[index];
  23477. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23478. log += (index === 0 ? "\n\tMaterials:" : "");
  23479. log += "\n\t\t" + mat.toString(fullDetails);
  23480. }
  23481. }
  23482. if (parsedData.multiMaterials) {
  23483. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23484. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23485. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23486. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23487. log += "\n\t\t" + mmat.toString(fullDetails);
  23488. }
  23489. }
  23490. // Skeletons
  23491. if (parsedData.skeletons) {
  23492. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23493. var parsedSkeleton = parsedData.skeletons[index];
  23494. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23495. log += (index === 0 ? "\n\tSkeletons:" : "");
  23496. log += "\n\t\t" + skeleton.toString(fullDetails);
  23497. }
  23498. }
  23499. // Geometries
  23500. var geometries = parsedData.geometries;
  23501. if (geometries) {
  23502. // Boxes
  23503. var boxes = geometries.boxes;
  23504. if (boxes) {
  23505. for (index = 0, cache = boxes.length; index < cache; index++) {
  23506. var parsedBox = boxes[index];
  23507. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  23508. }
  23509. }
  23510. // Spheres
  23511. var spheres = geometries.spheres;
  23512. if (spheres) {
  23513. for (index = 0, cache = spheres.length; index < cache; index++) {
  23514. var parsedSphere = spheres[index];
  23515. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  23516. }
  23517. }
  23518. // Cylinders
  23519. var cylinders = geometries.cylinders;
  23520. if (cylinders) {
  23521. for (index = 0, cache = cylinders.length; index < cache; index++) {
  23522. var parsedCylinder = cylinders[index];
  23523. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  23524. }
  23525. }
  23526. // Toruses
  23527. var toruses = geometries.toruses;
  23528. if (toruses) {
  23529. for (index = 0, cache = toruses.length; index < cache; index++) {
  23530. var parsedTorus = toruses[index];
  23531. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  23532. }
  23533. }
  23534. // Grounds
  23535. var grounds = geometries.grounds;
  23536. if (grounds) {
  23537. for (index = 0, cache = grounds.length; index < cache; index++) {
  23538. var parsedGround = grounds[index];
  23539. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  23540. }
  23541. }
  23542. // Planes
  23543. var planes = geometries.planes;
  23544. if (planes) {
  23545. for (index = 0, cache = planes.length; index < cache; index++) {
  23546. var parsedPlane = planes[index];
  23547. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  23548. }
  23549. }
  23550. // TorusKnots
  23551. var torusKnots = geometries.torusKnots;
  23552. if (torusKnots) {
  23553. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  23554. var parsedTorusKnot = torusKnots[index];
  23555. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  23556. }
  23557. }
  23558. // VertexData
  23559. var vertexData = geometries.vertexData;
  23560. if (vertexData) {
  23561. for (index = 0, cache = vertexData.length; index < cache; index++) {
  23562. var parsedVertexData = vertexData[index];
  23563. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  23564. }
  23565. }
  23566. }
  23567. // Meshes
  23568. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23569. var parsedMesh = parsedData.meshes[index];
  23570. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23571. log += (index === 0 ? "\n\tMeshes:" : "");
  23572. log += "\n\t\t" + mesh.toString(fullDetails);
  23573. }
  23574. // Cameras
  23575. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  23576. var parsedCamera = parsedData.cameras[index];
  23577. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  23578. log += (index === 0 ? "\n\tCameras:" : "");
  23579. log += "\n\t\t" + camera.toString(fullDetails);
  23580. }
  23581. if (parsedData.activeCameraID) {
  23582. scene.setActiveCameraByID(parsedData.activeCameraID);
  23583. }
  23584. // Browsing all the graph to connect the dots
  23585. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  23586. var camera = scene.cameras[index];
  23587. if (camera._waitingParentId) {
  23588. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  23589. camera._waitingParentId = undefined;
  23590. }
  23591. }
  23592. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  23593. var light = scene.lights[index];
  23594. if (light._waitingParentId) {
  23595. light.parent = scene.getLastEntryByID(light._waitingParentId);
  23596. light._waitingParentId = undefined;
  23597. }
  23598. }
  23599. // Sounds
  23600. var loadedSounds = [];
  23601. var loadedSound;
  23602. if (BABYLON.AudioEngine && parsedData.sounds) {
  23603. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  23604. var parsedSound = parsedData.sounds[index];
  23605. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  23606. if (!parsedSound.url)
  23607. parsedSound.url = parsedSound.name;
  23608. if (!loadedSounds[parsedSound.url]) {
  23609. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  23610. loadedSounds[parsedSound.url] = loadedSound;
  23611. }
  23612. else {
  23613. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  23614. }
  23615. }
  23616. else {
  23617. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  23618. }
  23619. }
  23620. log += (index === 0 ? "\n\tSounds:" : "");
  23621. log += "\n\t\t" + mat.toString(fullDetails);
  23622. }
  23623. loadedSounds = [];
  23624. // Connect parents & children and parse actions
  23625. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23626. var mesh = scene.meshes[index];
  23627. if (mesh._waitingParentId) {
  23628. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  23629. mesh._waitingParentId = undefined;
  23630. }
  23631. if (mesh._waitingActions) {
  23632. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  23633. mesh._waitingActions = undefined;
  23634. }
  23635. }
  23636. // freeze world matrix application
  23637. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23638. var currentMesh = scene.meshes[index];
  23639. if (currentMesh._waitingFreezeWorldMatrix) {
  23640. currentMesh.freezeWorldMatrix();
  23641. currentMesh._waitingFreezeWorldMatrix = undefined;
  23642. }
  23643. else {
  23644. currentMesh.computeWorldMatrix(true);
  23645. }
  23646. }
  23647. // Particles Systems
  23648. if (parsedData.particleSystems) {
  23649. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23650. var parsedParticleSystem = parsedData.particleSystems[index];
  23651. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  23652. }
  23653. }
  23654. // Lens flares
  23655. if (parsedData.lensFlareSystems) {
  23656. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  23657. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  23658. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  23659. }
  23660. }
  23661. // Shadows
  23662. if (parsedData.shadowGenerators) {
  23663. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  23664. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  23665. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  23666. }
  23667. }
  23668. // Actions (scene)
  23669. if (parsedData.actions) {
  23670. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  23671. }
  23672. // Finish
  23673. return true;
  23674. }
  23675. catch (err) {
  23676. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  23677. log = null;
  23678. throw err;
  23679. }
  23680. finally {
  23681. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23682. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23683. }
  23684. }
  23685. }
  23686. });
  23687. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23688. })(BABYLON || (BABYLON = {}));
  23689. var BABYLON;
  23690. (function (BABYLON) {
  23691. var SpriteManager = (function () {
  23692. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  23693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23694. this.name = name;
  23695. this.cellSize = cellSize;
  23696. this.sprites = new Array();
  23697. this.renderingGroupId = 0;
  23698. this.layerMask = 0x0FFFFFFF;
  23699. this.fogEnabled = true;
  23700. this.isPickable = false;
  23701. this._vertexDeclaration = [4, 4, 4, 4];
  23702. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  23703. this._capacity = capacity;
  23704. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  23705. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23706. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23707. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  23708. this._scene = scene;
  23709. this._scene.spriteManagers.push(this);
  23710. // VBO
  23711. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  23712. var indices = [];
  23713. var index = 0;
  23714. for (var count = 0; count < capacity; count++) {
  23715. indices.push(index);
  23716. indices.push(index + 1);
  23717. indices.push(index + 2);
  23718. indices.push(index);
  23719. indices.push(index + 2);
  23720. indices.push(index + 3);
  23721. index += 4;
  23722. }
  23723. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23724. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  23725. // Effects
  23726. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  23727. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  23728. }
  23729. Object.defineProperty(SpriteManager.prototype, "texture", {
  23730. get: function () {
  23731. return this._spriteTexture;
  23732. },
  23733. set: function (value) {
  23734. this._spriteTexture = value;
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  23740. var arrayOffset = index * 16;
  23741. if (offsetX === 0)
  23742. offsetX = this._epsilon;
  23743. else if (offsetX === 1)
  23744. offsetX = 1 - this._epsilon;
  23745. if (offsetY === 0)
  23746. offsetY = this._epsilon;
  23747. else if (offsetY === 1)
  23748. offsetY = 1 - this._epsilon;
  23749. this._vertices[arrayOffset] = sprite.position.x;
  23750. this._vertices[arrayOffset + 1] = sprite.position.y;
  23751. this._vertices[arrayOffset + 2] = sprite.position.z;
  23752. this._vertices[arrayOffset + 3] = sprite.angle;
  23753. this._vertices[arrayOffset + 4] = sprite.width;
  23754. this._vertices[arrayOffset + 5] = sprite.height;
  23755. this._vertices[arrayOffset + 6] = offsetX;
  23756. this._vertices[arrayOffset + 7] = offsetY;
  23757. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  23758. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  23759. var offset = (sprite.cellIndex / rowSize) >> 0;
  23760. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  23761. this._vertices[arrayOffset + 11] = offset;
  23762. // Color
  23763. this._vertices[arrayOffset + 12] = sprite.color.r;
  23764. this._vertices[arrayOffset + 13] = sprite.color.g;
  23765. this._vertices[arrayOffset + 14] = sprite.color.b;
  23766. this._vertices[arrayOffset + 15] = sprite.color.a;
  23767. };
  23768. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  23769. var count = Math.min(this._capacity, this.sprites.length);
  23770. var min = BABYLON.Vector3.Zero();
  23771. var max = BABYLON.Vector3.Zero();
  23772. var distance = Number.MAX_VALUE;
  23773. var currentSprite;
  23774. var cameraSpacePosition = BABYLON.Vector3.Zero();
  23775. var cameraView = camera.getViewMatrix();
  23776. for (var index = 0; index < count; index++) {
  23777. var sprite = this.sprites[index];
  23778. if (!sprite) {
  23779. continue;
  23780. }
  23781. if (predicate) {
  23782. if (!predicate(sprite)) {
  23783. continue;
  23784. }
  23785. }
  23786. else if (!sprite.isPickable) {
  23787. continue;
  23788. }
  23789. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  23790. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  23791. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  23792. if (ray.intersectsBoxMinMax(min, max)) {
  23793. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  23794. if (distance > currentDistance) {
  23795. distance = currentDistance;
  23796. currentSprite = sprite;
  23797. if (fastCheck) {
  23798. break;
  23799. }
  23800. }
  23801. }
  23802. }
  23803. if (currentSprite) {
  23804. var result = new BABYLON.PickingInfo();
  23805. result.hit = true;
  23806. result.pickedSprite = currentSprite;
  23807. result.distance = distance;
  23808. return result;
  23809. }
  23810. return null;
  23811. };
  23812. SpriteManager.prototype.render = function () {
  23813. // Check
  23814. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  23815. return;
  23816. var engine = this._scene.getEngine();
  23817. var baseSize = this._spriteTexture.getBaseSize();
  23818. // Sprites
  23819. var deltaTime = engine.getDeltaTime();
  23820. var max = Math.min(this._capacity, this.sprites.length);
  23821. var rowSize = baseSize.width / this.cellSize;
  23822. var offset = 0;
  23823. for (var index = 0; index < max; index++) {
  23824. var sprite = this.sprites[index];
  23825. if (!sprite) {
  23826. continue;
  23827. }
  23828. sprite._animate(deltaTime);
  23829. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  23830. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  23831. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  23832. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  23833. }
  23834. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  23835. // Render
  23836. var effect = this._effectBase;
  23837. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23838. effect = this._effectFog;
  23839. }
  23840. engine.enableEffect(effect);
  23841. var viewMatrix = this._scene.getViewMatrix();
  23842. effect.setTexture("diffuseSampler", this._spriteTexture);
  23843. effect.setMatrix("view", viewMatrix);
  23844. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  23845. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  23846. // Fog
  23847. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23848. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  23849. effect.setColor3("vFogColor", this._scene.fogColor);
  23850. }
  23851. // VBOs
  23852. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23853. // Draw order
  23854. engine.setDepthFunctionToLessOrEqual();
  23855. effect.setBool("alphaTest", true);
  23856. engine.setColorWrite(false);
  23857. engine.draw(true, 0, max * 6);
  23858. engine.setColorWrite(true);
  23859. effect.setBool("alphaTest", false);
  23860. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23861. engine.draw(true, 0, max * 6);
  23862. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23863. };
  23864. SpriteManager.prototype.dispose = function () {
  23865. if (this._vertexBuffer) {
  23866. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23867. this._vertexBuffer = null;
  23868. }
  23869. if (this._indexBuffer) {
  23870. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23871. this._indexBuffer = null;
  23872. }
  23873. if (this._spriteTexture) {
  23874. this._spriteTexture.dispose();
  23875. this._spriteTexture = null;
  23876. }
  23877. // Remove from scene
  23878. var index = this._scene.spriteManagers.indexOf(this);
  23879. this._scene.spriteManagers.splice(index, 1);
  23880. // Callback
  23881. if (this.onDispose) {
  23882. this.onDispose();
  23883. }
  23884. };
  23885. return SpriteManager;
  23886. })();
  23887. BABYLON.SpriteManager = SpriteManager;
  23888. })(BABYLON || (BABYLON = {}));
  23889. var BABYLON;
  23890. (function (BABYLON) {
  23891. var Sprite = (function () {
  23892. function Sprite(name, manager) {
  23893. this.name = name;
  23894. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  23895. this.width = 1.0;
  23896. this.height = 1.0;
  23897. this.angle = 0;
  23898. this.cellIndex = 0;
  23899. this.invertU = 0;
  23900. this.invertV = 0;
  23901. this.animations = new Array();
  23902. this.isPickable = false;
  23903. this._animationStarted = false;
  23904. this._loopAnimation = false;
  23905. this._fromIndex = 0;
  23906. this._toIndex = 0;
  23907. this._delay = 0;
  23908. this._direction = 1;
  23909. this._frameCount = 0;
  23910. this._time = 0;
  23911. this._manager = manager;
  23912. this._manager.sprites.push(this);
  23913. this.position = BABYLON.Vector3.Zero();
  23914. }
  23915. Object.defineProperty(Sprite.prototype, "size", {
  23916. get: function () {
  23917. return this.width;
  23918. },
  23919. set: function (value) {
  23920. this.width = value;
  23921. this.height = value;
  23922. },
  23923. enumerable: true,
  23924. configurable: true
  23925. });
  23926. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  23927. this._fromIndex = from;
  23928. this._toIndex = to;
  23929. this._loopAnimation = loop;
  23930. this._delay = delay;
  23931. this._animationStarted = true;
  23932. this._direction = from < to ? 1 : -1;
  23933. this.cellIndex = from;
  23934. this._time = 0;
  23935. };
  23936. Sprite.prototype.stopAnimation = function () {
  23937. this._animationStarted = false;
  23938. };
  23939. Sprite.prototype._animate = function (deltaTime) {
  23940. if (!this._animationStarted)
  23941. return;
  23942. this._time += deltaTime;
  23943. if (this._time > this._delay) {
  23944. this._time = this._time % this._delay;
  23945. this.cellIndex += this._direction;
  23946. if (this.cellIndex == this._toIndex) {
  23947. if (this._loopAnimation) {
  23948. this.cellIndex = this._fromIndex;
  23949. }
  23950. else {
  23951. this._animationStarted = false;
  23952. if (this.disposeWhenFinishedAnimating) {
  23953. this.dispose();
  23954. }
  23955. }
  23956. }
  23957. }
  23958. };
  23959. Sprite.prototype.dispose = function () {
  23960. for (var i = 0; i < this._manager.sprites.length; i++) {
  23961. if (this._manager.sprites[i] == this) {
  23962. this._manager.sprites.splice(i, 1);
  23963. }
  23964. }
  23965. };
  23966. return Sprite;
  23967. })();
  23968. BABYLON.Sprite = Sprite;
  23969. })(BABYLON || (BABYLON = {}));
  23970. var BABYLON;
  23971. (function (BABYLON) {
  23972. var Layer = (function () {
  23973. function Layer(name, imgUrl, scene, isBackground, color) {
  23974. this.name = name;
  23975. this.scale = new BABYLON.Vector2(1, 1);
  23976. this.offset = new BABYLON.Vector2(0, 0);
  23977. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  23978. this._vertexDeclaration = [2];
  23979. this._vertexStrideSize = 2 * 4;
  23980. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  23981. this.isBackground = isBackground === undefined ? true : isBackground;
  23982. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  23983. this._scene = scene;
  23984. this._scene.layers.push(this);
  23985. // VBO
  23986. var vertices = [];
  23987. vertices.push(1, 1);
  23988. vertices.push(-1, 1);
  23989. vertices.push(-1, -1);
  23990. vertices.push(1, -1);
  23991. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23992. // Indices
  23993. var indices = [];
  23994. indices.push(0);
  23995. indices.push(1);
  23996. indices.push(2);
  23997. indices.push(0);
  23998. indices.push(2);
  23999. indices.push(3);
  24000. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24001. // Effects
  24002. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24003. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24004. }
  24005. Layer.prototype.render = function () {
  24006. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24007. // Check
  24008. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24009. return;
  24010. var engine = this._scene.getEngine();
  24011. if (this.onBeforeRender) {
  24012. this.onBeforeRender();
  24013. }
  24014. // Render
  24015. engine.enableEffect(currentEffect);
  24016. engine.setState(false);
  24017. // Texture
  24018. currentEffect.setTexture("textureSampler", this.texture);
  24019. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24020. // Color
  24021. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24022. // Scale / offset
  24023. currentEffect.setVector2("offset", this.offset);
  24024. currentEffect.setVector2("scale", this.scale);
  24025. // VBOs
  24026. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24027. // Draw order
  24028. if (!this._alphaTestEffect) {
  24029. engine.setAlphaMode(this.alphaBlendingMode);
  24030. engine.draw(true, 0, 6);
  24031. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24032. }
  24033. else {
  24034. engine.draw(true, 0, 6);
  24035. }
  24036. if (this.onAfterRender) {
  24037. this.onAfterRender();
  24038. }
  24039. };
  24040. Layer.prototype.dispose = function () {
  24041. if (this._vertexBuffer) {
  24042. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24043. this._vertexBuffer = null;
  24044. }
  24045. if (this._indexBuffer) {
  24046. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24047. this._indexBuffer = null;
  24048. }
  24049. if (this.texture) {
  24050. this.texture.dispose();
  24051. this.texture = null;
  24052. }
  24053. // Remove from scene
  24054. var index = this._scene.layers.indexOf(this);
  24055. this._scene.layers.splice(index, 1);
  24056. // Callback
  24057. if (this.onDispose) {
  24058. this.onDispose();
  24059. }
  24060. };
  24061. return Layer;
  24062. })();
  24063. BABYLON.Layer = Layer;
  24064. })(BABYLON || (BABYLON = {}));
  24065. var BABYLON;
  24066. (function (BABYLON) {
  24067. var Particle = (function () {
  24068. function Particle() {
  24069. this.position = BABYLON.Vector3.Zero();
  24070. this.direction = BABYLON.Vector3.Zero();
  24071. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24072. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24073. this.lifeTime = 1.0;
  24074. this.age = 0;
  24075. this.size = 0;
  24076. this.angle = 0;
  24077. this.angularSpeed = 0;
  24078. }
  24079. Particle.prototype.copyTo = function (other) {
  24080. other.position.copyFrom(this.position);
  24081. other.direction.copyFrom(this.direction);
  24082. other.color.copyFrom(this.color);
  24083. other.colorStep.copyFrom(this.colorStep);
  24084. other.lifeTime = this.lifeTime;
  24085. other.age = this.age;
  24086. other.size = this.size;
  24087. other.angle = this.angle;
  24088. other.angularSpeed = this.angularSpeed;
  24089. };
  24090. return Particle;
  24091. })();
  24092. BABYLON.Particle = Particle;
  24093. })(BABYLON || (BABYLON = {}));
  24094. var BABYLON;
  24095. (function (BABYLON) {
  24096. var randomNumber = function (min, max) {
  24097. if (min === max) {
  24098. return (min);
  24099. }
  24100. var random = Math.random();
  24101. return ((random * (max - min)) + min);
  24102. };
  24103. var ParticleSystem = (function () {
  24104. function ParticleSystem(name, capacity, scene, customEffect) {
  24105. var _this = this;
  24106. this.name = name;
  24107. // Members
  24108. this.animations = [];
  24109. this.renderingGroupId = 0;
  24110. this.emitter = null;
  24111. this.emitRate = 10;
  24112. this.manualEmitCount = -1;
  24113. this.updateSpeed = 0.01;
  24114. this.targetStopDuration = 0;
  24115. this.disposeOnStop = false;
  24116. this.minEmitPower = 1;
  24117. this.maxEmitPower = 1;
  24118. this.minLifeTime = 1;
  24119. this.maxLifeTime = 1;
  24120. this.minSize = 1;
  24121. this.maxSize = 1;
  24122. this.minAngularSpeed = 0;
  24123. this.maxAngularSpeed = 0;
  24124. this.layerMask = 0x0FFFFFFF;
  24125. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24126. this.forceDepthWrite = false;
  24127. this.gravity = BABYLON.Vector3.Zero();
  24128. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24129. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24130. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24131. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24132. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24133. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24134. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24135. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24136. this.particles = new Array();
  24137. this._vertexDeclaration = [3, 4, 4];
  24138. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24139. this._stockParticles = new Array();
  24140. this._newPartsExcess = 0;
  24141. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24142. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24143. this._scaledDirection = BABYLON.Vector3.Zero();
  24144. this._scaledGravity = BABYLON.Vector3.Zero();
  24145. this._currentRenderId = -1;
  24146. this._started = false;
  24147. this._stopped = false;
  24148. this._actualFrame = 0;
  24149. this.id = name;
  24150. this._capacity = capacity;
  24151. this._scene = scene;
  24152. this._customEffect = customEffect;
  24153. scene.particleSystems.push(this);
  24154. // VBO
  24155. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24156. var indices = [];
  24157. var index = 0;
  24158. for (var count = 0; count < capacity; count++) {
  24159. indices.push(index);
  24160. indices.push(index + 1);
  24161. indices.push(index + 2);
  24162. indices.push(index);
  24163. indices.push(index + 2);
  24164. indices.push(index + 3);
  24165. index += 4;
  24166. }
  24167. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24168. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24169. // Default behaviors
  24170. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24171. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24172. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24173. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24174. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24175. };
  24176. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24177. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24178. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24179. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24181. };
  24182. this.updateFunction = function (particles) {
  24183. for (var index = 0; index < particles.length; index++) {
  24184. var particle = particles[index];
  24185. particle.age += _this._scaledUpdateSpeed;
  24186. if (particle.age >= particle.lifeTime) {
  24187. _this.recycleParticle(particle);
  24188. index--;
  24189. continue;
  24190. }
  24191. else {
  24192. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24193. particle.color.addInPlace(_this._scaledColorStep);
  24194. if (particle.color.a < 0)
  24195. particle.color.a = 0;
  24196. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24197. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24198. particle.position.addInPlace(_this._scaledDirection);
  24199. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24200. particle.direction.addInPlace(_this._scaledGravity);
  24201. }
  24202. }
  24203. };
  24204. }
  24205. ParticleSystem.prototype.recycleParticle = function (particle) {
  24206. var lastParticle = this.particles.pop();
  24207. if (lastParticle !== particle) {
  24208. lastParticle.copyTo(particle);
  24209. this._stockParticles.push(lastParticle);
  24210. }
  24211. };
  24212. ParticleSystem.prototype.getCapacity = function () {
  24213. return this._capacity;
  24214. };
  24215. ParticleSystem.prototype.isAlive = function () {
  24216. return this._alive;
  24217. };
  24218. ParticleSystem.prototype.isStarted = function () {
  24219. return this._started;
  24220. };
  24221. ParticleSystem.prototype.start = function () {
  24222. this._started = true;
  24223. this._stopped = false;
  24224. this._actualFrame = 0;
  24225. };
  24226. ParticleSystem.prototype.stop = function () {
  24227. this._stopped = true;
  24228. };
  24229. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24230. var offset = index * 11;
  24231. this._vertices[offset] = particle.position.x;
  24232. this._vertices[offset + 1] = particle.position.y;
  24233. this._vertices[offset + 2] = particle.position.z;
  24234. this._vertices[offset + 3] = particle.color.r;
  24235. this._vertices[offset + 4] = particle.color.g;
  24236. this._vertices[offset + 5] = particle.color.b;
  24237. this._vertices[offset + 6] = particle.color.a;
  24238. this._vertices[offset + 7] = particle.angle;
  24239. this._vertices[offset + 8] = particle.size;
  24240. this._vertices[offset + 9] = offsetX;
  24241. this._vertices[offset + 10] = offsetY;
  24242. };
  24243. ParticleSystem.prototype._update = function (newParticles) {
  24244. // Update current
  24245. this._alive = this.particles.length > 0;
  24246. this.updateFunction(this.particles);
  24247. // Add new ones
  24248. var worldMatrix;
  24249. if (this.emitter.position) {
  24250. worldMatrix = this.emitter.getWorldMatrix();
  24251. }
  24252. else {
  24253. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24254. }
  24255. var particle;
  24256. for (var index = 0; index < newParticles; index++) {
  24257. if (this.particles.length === this._capacity) {
  24258. break;
  24259. }
  24260. if (this._stockParticles.length !== 0) {
  24261. particle = this._stockParticles.pop();
  24262. particle.age = 0;
  24263. }
  24264. else {
  24265. particle = new BABYLON.Particle();
  24266. }
  24267. this.particles.push(particle);
  24268. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24269. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24270. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24271. particle.size = randomNumber(this.minSize, this.maxSize);
  24272. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24273. this.startPositionFunction(worldMatrix, particle.position, particle);
  24274. var step = randomNumber(0, 1.0);
  24275. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24276. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24277. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24278. }
  24279. };
  24280. ParticleSystem.prototype._getEffect = function () {
  24281. if (this._customEffect) {
  24282. return this._customEffect;
  24283. }
  24284. ;
  24285. var defines = [];
  24286. if (this._scene.clipPlane) {
  24287. defines.push("#define CLIPPLANE");
  24288. }
  24289. // Effect
  24290. var join = defines.join("\n");
  24291. if (this._cachedDefines !== join) {
  24292. this._cachedDefines = join;
  24293. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24294. }
  24295. return this._effect;
  24296. };
  24297. ParticleSystem.prototype.animate = function () {
  24298. if (!this._started)
  24299. return;
  24300. var effect = this._getEffect();
  24301. // Check
  24302. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24303. return;
  24304. if (this._currentRenderId === this._scene.getRenderId()) {
  24305. return;
  24306. }
  24307. this._currentRenderId = this._scene.getRenderId();
  24308. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24309. // determine the number of particles we need to create
  24310. var newParticles;
  24311. if (this.manualEmitCount > -1) {
  24312. newParticles = this.manualEmitCount;
  24313. this._newPartsExcess = 0;
  24314. this.manualEmitCount = 0;
  24315. }
  24316. else {
  24317. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24318. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24319. }
  24320. if (this._newPartsExcess > 1.0) {
  24321. newParticles += this._newPartsExcess >> 0;
  24322. this._newPartsExcess -= this._newPartsExcess >> 0;
  24323. }
  24324. this._alive = false;
  24325. if (!this._stopped) {
  24326. this._actualFrame += this._scaledUpdateSpeed;
  24327. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24328. this.stop();
  24329. }
  24330. else {
  24331. newParticles = 0;
  24332. }
  24333. this._update(newParticles);
  24334. // Stopped?
  24335. if (this._stopped) {
  24336. if (!this._alive) {
  24337. this._started = false;
  24338. if (this.disposeOnStop) {
  24339. this._scene._toBeDisposed.push(this);
  24340. }
  24341. }
  24342. }
  24343. // Update VBO
  24344. var offset = 0;
  24345. for (var index = 0; index < this.particles.length; index++) {
  24346. var particle = this.particles[index];
  24347. this._appendParticleVertex(offset++, particle, 0, 0);
  24348. this._appendParticleVertex(offset++, particle, 1, 0);
  24349. this._appendParticleVertex(offset++, particle, 1, 1);
  24350. this._appendParticleVertex(offset++, particle, 0, 1);
  24351. }
  24352. var engine = this._scene.getEngine();
  24353. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24354. };
  24355. ParticleSystem.prototype.render = function () {
  24356. var effect = this._getEffect();
  24357. // Check
  24358. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24359. return 0;
  24360. var engine = this._scene.getEngine();
  24361. // Render
  24362. engine.enableEffect(effect);
  24363. engine.setState(false);
  24364. var viewMatrix = this._scene.getViewMatrix();
  24365. effect.setTexture("diffuseSampler", this.particleTexture);
  24366. effect.setMatrix("view", viewMatrix);
  24367. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24368. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24369. if (this._scene.clipPlane) {
  24370. var clipPlane = this._scene.clipPlane;
  24371. var invView = viewMatrix.clone();
  24372. invView.invert();
  24373. effect.setMatrix("invView", invView);
  24374. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24375. }
  24376. // VBOs
  24377. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24378. // Draw order
  24379. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24380. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24381. }
  24382. else {
  24383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24384. }
  24385. if (this.forceDepthWrite) {
  24386. engine.setDepthWrite(true);
  24387. }
  24388. engine.draw(true, 0, this.particles.length * 6);
  24389. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24390. return this.particles.length;
  24391. };
  24392. ParticleSystem.prototype.dispose = function () {
  24393. if (this._vertexBuffer) {
  24394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24395. this._vertexBuffer = null;
  24396. }
  24397. if (this._indexBuffer) {
  24398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24399. this._indexBuffer = null;
  24400. }
  24401. if (this.particleTexture) {
  24402. this.particleTexture.dispose();
  24403. this.particleTexture = null;
  24404. }
  24405. // Remove from scene
  24406. var index = this._scene.particleSystems.indexOf(this);
  24407. this._scene.particleSystems.splice(index, 1);
  24408. // Callback
  24409. if (this.onDispose) {
  24410. this.onDispose();
  24411. }
  24412. };
  24413. // Clone
  24414. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24415. var result = new ParticleSystem(name, this._capacity, this._scene);
  24416. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24417. if (newEmitter === undefined) {
  24418. newEmitter = this.emitter;
  24419. }
  24420. result.emitter = newEmitter;
  24421. if (this.particleTexture) {
  24422. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24423. }
  24424. result.start();
  24425. return result;
  24426. };
  24427. ParticleSystem.prototype.serialize = function () {
  24428. var serializationObject = {};
  24429. serializationObject.name = this.name;
  24430. serializationObject.id = this.id;
  24431. // Emitter
  24432. if (this.emitter.position) {
  24433. serializationObject.emitterId = this.emitter.id;
  24434. }
  24435. else {
  24436. serializationObject.emitter = this.emitter.asArray();
  24437. }
  24438. serializationObject.capacity = this.getCapacity();
  24439. if (this.particleTexture) {
  24440. serializationObject.textureName = this.particleTexture.name;
  24441. }
  24442. // Animations
  24443. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24444. // Particle system
  24445. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24446. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24447. serializationObject.minSize = this.minSize;
  24448. serializationObject.maxSize = this.maxSize;
  24449. serializationObject.minEmitPower = this.minEmitPower;
  24450. serializationObject.maxEmitPower = this.maxEmitPower;
  24451. serializationObject.minLifeTime = this.minLifeTime;
  24452. serializationObject.maxLifeTime = this.maxLifeTime;
  24453. serializationObject.emitRate = this.emitRate;
  24454. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24455. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24456. serializationObject.gravity = this.gravity.asArray();
  24457. serializationObject.direction1 = this.direction1.asArray();
  24458. serializationObject.direction2 = this.direction2.asArray();
  24459. serializationObject.color1 = this.color1.asArray();
  24460. serializationObject.color2 = this.color2.asArray();
  24461. serializationObject.colorDead = this.colorDead.asArray();
  24462. serializationObject.updateSpeed = this.updateSpeed;
  24463. serializationObject.targetStopDuration = this.targetStopDuration;
  24464. serializationObject.textureMask = this.textureMask.asArray();
  24465. serializationObject.blendMode = this.blendMode;
  24466. return serializationObject;
  24467. };
  24468. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24469. var name = parsedParticleSystem.name;
  24470. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24471. if (parsedParticleSystem.id) {
  24472. particleSystem.id = parsedParticleSystem.id;
  24473. }
  24474. // Texture
  24475. if (parsedParticleSystem.textureName) {
  24476. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24477. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24478. }
  24479. // Emitter
  24480. if (parsedParticleSystem.emitterId) {
  24481. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24482. }
  24483. else {
  24484. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24485. }
  24486. // Animations
  24487. if (parsedParticleSystem.animations) {
  24488. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24489. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24490. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24491. }
  24492. }
  24493. if (parsedParticleSystem.autoAnimate) {
  24494. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24495. }
  24496. // Particle system
  24497. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  24498. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  24499. particleSystem.minSize = parsedParticleSystem.minSize;
  24500. particleSystem.maxSize = parsedParticleSystem.maxSize;
  24501. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  24502. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  24503. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  24504. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  24505. particleSystem.emitRate = parsedParticleSystem.emitRate;
  24506. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  24507. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  24508. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  24509. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  24510. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  24511. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  24512. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  24513. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  24514. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  24515. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  24516. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  24517. particleSystem.blendMode = parsedParticleSystem.blendMode;
  24518. particleSystem.start();
  24519. return particleSystem;
  24520. };
  24521. // Statics
  24522. ParticleSystem.BLENDMODE_ONEONE = 0;
  24523. ParticleSystem.BLENDMODE_STANDARD = 1;
  24524. return ParticleSystem;
  24525. })();
  24526. BABYLON.ParticleSystem = ParticleSystem;
  24527. })(BABYLON || (BABYLON = {}));
  24528. var BABYLON;
  24529. (function (BABYLON) {
  24530. var AnimationRange = (function () {
  24531. function AnimationRange(name, from, to) {
  24532. this.name = name;
  24533. this.from = from;
  24534. this.to = to;
  24535. }
  24536. AnimationRange.prototype.clone = function () {
  24537. return new AnimationRange(this.name, this.from, this.to);
  24538. };
  24539. return AnimationRange;
  24540. })();
  24541. BABYLON.AnimationRange = AnimationRange;
  24542. /**
  24543. * Composed of a frame, and an action function
  24544. */
  24545. var AnimationEvent = (function () {
  24546. function AnimationEvent(frame, action, onlyOnce) {
  24547. this.frame = frame;
  24548. this.action = action;
  24549. this.onlyOnce = onlyOnce;
  24550. this.isDone = false;
  24551. }
  24552. return AnimationEvent;
  24553. })();
  24554. BABYLON.AnimationEvent = AnimationEvent;
  24555. var PathCursor = (function () {
  24556. function PathCursor(path) {
  24557. this.path = path;
  24558. this._onchange = new Array();
  24559. this.value = 0;
  24560. this.animations = new Array();
  24561. }
  24562. PathCursor.prototype.getPoint = function () {
  24563. var point = this.path.getPointAtLengthPosition(this.value);
  24564. return new BABYLON.Vector3(point.x, 0, point.y);
  24565. };
  24566. PathCursor.prototype.moveAhead = function (step) {
  24567. if (step === void 0) { step = 0.002; }
  24568. this.move(step);
  24569. return this;
  24570. };
  24571. PathCursor.prototype.moveBack = function (step) {
  24572. if (step === void 0) { step = 0.002; }
  24573. this.move(-step);
  24574. return this;
  24575. };
  24576. PathCursor.prototype.move = function (step) {
  24577. if (Math.abs(step) > 1) {
  24578. throw "step size should be less than 1.";
  24579. }
  24580. this.value += step;
  24581. this.ensureLimits();
  24582. this.raiseOnChange();
  24583. return this;
  24584. };
  24585. PathCursor.prototype.ensureLimits = function () {
  24586. while (this.value > 1) {
  24587. this.value -= 1;
  24588. }
  24589. while (this.value < 0) {
  24590. this.value += 1;
  24591. }
  24592. return this;
  24593. };
  24594. // used by animation engine
  24595. PathCursor.prototype.markAsDirty = function (propertyName) {
  24596. this.ensureLimits();
  24597. this.raiseOnChange();
  24598. return this;
  24599. };
  24600. PathCursor.prototype.raiseOnChange = function () {
  24601. var _this = this;
  24602. this._onchange.forEach(function (f) { return f(_this); });
  24603. return this;
  24604. };
  24605. PathCursor.prototype.onchange = function (f) {
  24606. this._onchange.push(f);
  24607. return this;
  24608. };
  24609. return PathCursor;
  24610. })();
  24611. BABYLON.PathCursor = PathCursor;
  24612. var Animation = (function () {
  24613. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  24614. this.name = name;
  24615. this.targetProperty = targetProperty;
  24616. this.framePerSecond = framePerSecond;
  24617. this.dataType = dataType;
  24618. this.loopMode = loopMode;
  24619. this.enableBlending = enableBlending;
  24620. this._offsetsCache = {};
  24621. this._highLimitsCache = {};
  24622. this._stopped = false;
  24623. this._blendingFactor = 0;
  24624. // The set of event that will be linked to this animation
  24625. this._events = new Array();
  24626. this.allowMatricesInterpolation = false;
  24627. this.blendingSpeed = 0.01;
  24628. this._ranges = {};
  24629. this.targetPropertyPath = targetProperty.split(".");
  24630. this.dataType = dataType;
  24631. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  24632. }
  24633. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  24634. var dataType = undefined;
  24635. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  24636. dataType = Animation.ANIMATIONTYPE_FLOAT;
  24637. }
  24638. else if (from instanceof BABYLON.Quaternion) {
  24639. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  24640. }
  24641. else if (from instanceof BABYLON.Vector3) {
  24642. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  24643. }
  24644. else if (from instanceof BABYLON.Vector2) {
  24645. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  24646. }
  24647. else if (from instanceof BABYLON.Color3) {
  24648. dataType = Animation.ANIMATIONTYPE_COLOR3;
  24649. }
  24650. if (dataType == undefined) {
  24651. return null;
  24652. }
  24653. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  24654. var keys = [];
  24655. keys.push({ frame: 0, value: from });
  24656. keys.push({ frame: totalFrame, value: to });
  24657. animation.setKeys(keys);
  24658. if (easingFunction !== undefined) {
  24659. animation.setEasingFunction(easingFunction);
  24660. }
  24661. return animation;
  24662. };
  24663. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  24664. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  24665. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  24666. };
  24667. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  24668. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  24669. node.animations.push(animation);
  24670. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  24671. };
  24672. // Methods
  24673. /**
  24674. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24675. */
  24676. Animation.prototype.toString = function (fullDetails) {
  24677. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  24678. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  24679. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  24680. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  24681. if (fullDetails) {
  24682. ret += ", Ranges: {";
  24683. var first = true;
  24684. for (var name in this._ranges) {
  24685. if (!first) {
  24686. ret + ", ";
  24687. first = false;
  24688. }
  24689. ret += name;
  24690. }
  24691. ret += "}";
  24692. }
  24693. return ret;
  24694. };
  24695. /**
  24696. * Add an event to this animation.
  24697. */
  24698. Animation.prototype.addEvent = function (event) {
  24699. this._events.push(event);
  24700. };
  24701. /**
  24702. * Remove all events found at the given frame
  24703. * @param frame
  24704. */
  24705. Animation.prototype.removeEvents = function (frame) {
  24706. for (var index = 0; index < this._events.length; index++) {
  24707. if (this._events[index].frame === frame) {
  24708. this._events.splice(index, 1);
  24709. index--;
  24710. }
  24711. }
  24712. };
  24713. Animation.prototype.createRange = function (name, from, to) {
  24714. // check name not already in use; could happen for bones after serialized
  24715. if (!this._ranges[name]) {
  24716. this._ranges[name] = new AnimationRange(name, from, to);
  24717. }
  24718. };
  24719. Animation.prototype.deleteRange = function (name, deleteFrames) {
  24720. if (deleteFrames === void 0) { deleteFrames = true; }
  24721. if (this._ranges[name]) {
  24722. if (deleteFrames) {
  24723. var from = this._ranges[name].from;
  24724. var to = this._ranges[name].to;
  24725. // this loop MUST go high to low for multiple splices to work
  24726. for (var key = this._keys.length - 1; key >= 0; key--) {
  24727. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  24728. this._keys.splice(key, 1);
  24729. }
  24730. }
  24731. }
  24732. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  24733. }
  24734. };
  24735. Animation.prototype.getRange = function (name) {
  24736. return this._ranges[name];
  24737. };
  24738. Animation.prototype.reset = function () {
  24739. this._offsetsCache = {};
  24740. this._highLimitsCache = {};
  24741. this.currentFrame = 0;
  24742. this._blendingFactor = 0;
  24743. this._originalBlendValue = null;
  24744. };
  24745. Animation.prototype.isStopped = function () {
  24746. return this._stopped;
  24747. };
  24748. Animation.prototype.getKeys = function () {
  24749. return this._keys;
  24750. };
  24751. Animation.prototype.getHighestFrame = function () {
  24752. var ret = 0;
  24753. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  24754. if (ret < this._keys[key].frame) {
  24755. ret = this._keys[key].frame;
  24756. }
  24757. }
  24758. return ret;
  24759. };
  24760. Animation.prototype.getEasingFunction = function () {
  24761. return this._easingFunction;
  24762. };
  24763. Animation.prototype.setEasingFunction = function (easingFunction) {
  24764. this._easingFunction = easingFunction;
  24765. };
  24766. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  24767. return startValue + (endValue - startValue) * gradient;
  24768. };
  24769. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  24770. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  24771. };
  24772. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  24773. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  24774. };
  24775. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  24776. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  24777. };
  24778. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  24779. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  24780. };
  24781. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  24782. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  24783. };
  24784. Animation.prototype.clone = function () {
  24785. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  24786. if (this._keys) {
  24787. clone.setKeys(this._keys);
  24788. }
  24789. if (this._ranges) {
  24790. clone._ranges = {};
  24791. for (var name in this._ranges) {
  24792. clone._ranges[name] = this._ranges[name].clone();
  24793. }
  24794. }
  24795. return clone;
  24796. };
  24797. Animation.prototype.setKeys = function (values) {
  24798. this._keys = values.slice(0);
  24799. this._offsetsCache = {};
  24800. this._highLimitsCache = {};
  24801. };
  24802. Animation.prototype._getKeyValue = function (value) {
  24803. if (typeof value === "function") {
  24804. return value();
  24805. }
  24806. return value;
  24807. };
  24808. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  24809. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  24810. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  24811. }
  24812. this.currentFrame = currentFrame;
  24813. // Try to get a hash to find the right key
  24814. 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));
  24815. if (this._keys[startKey].frame >= currentFrame) {
  24816. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  24817. startKey--;
  24818. }
  24819. }
  24820. for (var key = startKey; key < this._keys.length; key++) {
  24821. if (this._keys[key + 1].frame >= currentFrame) {
  24822. var startValue = this._getKeyValue(this._keys[key].value);
  24823. var endValue = this._getKeyValue(this._keys[key + 1].value);
  24824. // gradient : percent of currentFrame between the frame inf and the frame sup
  24825. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  24826. // check for easingFunction and correction of gradient
  24827. if (this._easingFunction != null) {
  24828. gradient = this._easingFunction.ease(gradient);
  24829. }
  24830. switch (this.dataType) {
  24831. // Float
  24832. case Animation.ANIMATIONTYPE_FLOAT:
  24833. switch (loopMode) {
  24834. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24835. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24836. return this.floatInterpolateFunction(startValue, endValue, gradient);
  24837. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24838. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  24839. }
  24840. break;
  24841. // Quaternion
  24842. case Animation.ANIMATIONTYPE_QUATERNION:
  24843. var quaternion = null;
  24844. switch (loopMode) {
  24845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24847. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  24848. break;
  24849. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24850. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24851. break;
  24852. }
  24853. return quaternion;
  24854. // Vector3
  24855. case Animation.ANIMATIONTYPE_VECTOR3:
  24856. switch (loopMode) {
  24857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24859. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  24860. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24861. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24862. }
  24863. // Vector2
  24864. case Animation.ANIMATIONTYPE_VECTOR2:
  24865. switch (loopMode) {
  24866. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24867. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24868. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  24869. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24870. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24871. }
  24872. // Color3
  24873. case Animation.ANIMATIONTYPE_COLOR3:
  24874. switch (loopMode) {
  24875. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24876. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24877. return this.color3InterpolateFunction(startValue, endValue, gradient);
  24878. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24879. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  24880. }
  24881. // Matrix
  24882. case Animation.ANIMATIONTYPE_MATRIX:
  24883. switch (loopMode) {
  24884. case Animation.ANIMATIONLOOPMODE_CYCLE:
  24885. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  24886. if (this.allowMatricesInterpolation) {
  24887. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  24888. }
  24889. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  24890. return startValue;
  24891. }
  24892. default:
  24893. break;
  24894. }
  24895. break;
  24896. }
  24897. }
  24898. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  24899. };
  24900. Animation.prototype.setValue = function (currentValue, blend) {
  24901. if (blend === void 0) { blend = false; }
  24902. // Set value
  24903. var path;
  24904. var destination;
  24905. if (this.targetPropertyPath.length > 1) {
  24906. var property = this._target[this.targetPropertyPath[0]];
  24907. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  24908. property = property[this.targetPropertyPath[index]];
  24909. }
  24910. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  24911. destination = property;
  24912. }
  24913. else {
  24914. path = this.targetPropertyPath[0];
  24915. destination = this._target;
  24916. }
  24917. // Blending
  24918. if (this.enableBlending && this._blendingFactor <= 1.0) {
  24919. if (!this._originalBlendValue) {
  24920. this._originalBlendValue = destination[path];
  24921. }
  24922. if (this._originalBlendValue.prototype) {
  24923. if (this._originalBlendValue.prototype.Lerp) {
  24924. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  24925. }
  24926. else {
  24927. destination[path] = currentValue;
  24928. }
  24929. }
  24930. else {
  24931. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  24932. }
  24933. this._blendingFactor += this.blendingSpeed;
  24934. }
  24935. else {
  24936. destination[path] = currentValue;
  24937. }
  24938. if (this._target.markAsDirty) {
  24939. this._target.markAsDirty(this.targetProperty);
  24940. }
  24941. };
  24942. Animation.prototype.goToFrame = function (frame) {
  24943. if (frame < this._keys[0].frame) {
  24944. frame = this._keys[0].frame;
  24945. }
  24946. else if (frame > this._keys[this._keys.length - 1].frame) {
  24947. frame = this._keys[this._keys.length - 1].frame;
  24948. }
  24949. var currentValue = this._interpolate(frame, 0, this.loopMode);
  24950. this.setValue(currentValue);
  24951. };
  24952. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  24953. if (blend === void 0) { blend = false; }
  24954. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  24955. this._stopped = true;
  24956. return false;
  24957. }
  24958. var returnValue = true;
  24959. // Adding a start key at frame 0 if missing
  24960. if (this._keys[0].frame !== 0) {
  24961. var newKey = { frame: 0, value: this._keys[0].value };
  24962. this._keys.splice(0, 0, newKey);
  24963. }
  24964. // Check limits
  24965. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  24966. from = this._keys[0].frame;
  24967. }
  24968. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  24969. to = this._keys[this._keys.length - 1].frame;
  24970. }
  24971. // Compute ratio
  24972. var range = to - from;
  24973. var offsetValue;
  24974. // ratio represents the frame delta between from and to
  24975. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  24976. var highLimitValue = 0;
  24977. if (ratio > range && !loop) {
  24978. returnValue = false;
  24979. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  24980. }
  24981. else {
  24982. // Get max value if required
  24983. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  24984. var keyOffset = to.toString() + from.toString();
  24985. if (!this._offsetsCache[keyOffset]) {
  24986. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24987. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  24988. switch (this.dataType) {
  24989. // Float
  24990. case Animation.ANIMATIONTYPE_FLOAT:
  24991. this._offsetsCache[keyOffset] = toValue - fromValue;
  24992. break;
  24993. // Quaternion
  24994. case Animation.ANIMATIONTYPE_QUATERNION:
  24995. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  24996. break;
  24997. // Vector3
  24998. case Animation.ANIMATIONTYPE_VECTOR3:
  24999. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25000. // Vector2
  25001. case Animation.ANIMATIONTYPE_VECTOR2:
  25002. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25003. // Color3
  25004. case Animation.ANIMATIONTYPE_COLOR3:
  25005. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25006. default:
  25007. break;
  25008. }
  25009. this._highLimitsCache[keyOffset] = toValue;
  25010. }
  25011. highLimitValue = this._highLimitsCache[keyOffset];
  25012. offsetValue = this._offsetsCache[keyOffset];
  25013. }
  25014. }
  25015. if (offsetValue === undefined) {
  25016. switch (this.dataType) {
  25017. // Float
  25018. case Animation.ANIMATIONTYPE_FLOAT:
  25019. offsetValue = 0;
  25020. break;
  25021. // Quaternion
  25022. case Animation.ANIMATIONTYPE_QUATERNION:
  25023. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25024. break;
  25025. // Vector3
  25026. case Animation.ANIMATIONTYPE_VECTOR3:
  25027. offsetValue = BABYLON.Vector3.Zero();
  25028. break;
  25029. // Vector2
  25030. case Animation.ANIMATIONTYPE_VECTOR2:
  25031. offsetValue = BABYLON.Vector2.Zero();
  25032. break;
  25033. // Color3
  25034. case Animation.ANIMATIONTYPE_COLOR3:
  25035. offsetValue = BABYLON.Color3.Black();
  25036. }
  25037. }
  25038. // Compute value
  25039. var repeatCount = (ratio / range) >> 0;
  25040. var currentFrame = returnValue ? from + ratio % range : to;
  25041. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25042. // Set value
  25043. this.setValue(currentValue);
  25044. // Check events
  25045. for (var index = 0; index < this._events.length; index++) {
  25046. if (currentFrame >= this._events[index].frame) {
  25047. var event = this._events[index];
  25048. if (!event.isDone) {
  25049. // If event should be done only once, remove it.
  25050. if (event.onlyOnce) {
  25051. this._events.splice(index, 1);
  25052. index--;
  25053. }
  25054. event.isDone = true;
  25055. event.action();
  25056. } // Don't do anything if the event has already be done.
  25057. }
  25058. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25059. // reset event, the animation is looping
  25060. this._events[index].isDone = false;
  25061. }
  25062. }
  25063. if (!returnValue) {
  25064. this._stopped = true;
  25065. }
  25066. return returnValue;
  25067. };
  25068. Animation.prototype.serialize = function () {
  25069. var serializationObject = {};
  25070. serializationObject.name = this.name;
  25071. serializationObject.property = this.targetProperty;
  25072. serializationObject.framePerSecond = this.framePerSecond;
  25073. serializationObject.dataType = this.dataType;
  25074. serializationObject.loopBehavior = this.loopMode;
  25075. var dataType = this.dataType;
  25076. serializationObject.keys = [];
  25077. var keys = this.getKeys();
  25078. for (var index = 0; index < keys.length; index++) {
  25079. var animationKey = keys[index];
  25080. var key = {};
  25081. key.frame = animationKey.frame;
  25082. switch (dataType) {
  25083. case Animation.ANIMATIONTYPE_FLOAT:
  25084. key.values = [animationKey.value];
  25085. break;
  25086. case Animation.ANIMATIONTYPE_QUATERNION:
  25087. case Animation.ANIMATIONTYPE_MATRIX:
  25088. case Animation.ANIMATIONTYPE_VECTOR3:
  25089. case Animation.ANIMATIONTYPE_COLOR3:
  25090. key.values = animationKey.value.asArray();
  25091. break;
  25092. }
  25093. serializationObject.keys.push(key);
  25094. }
  25095. serializationObject.ranges = [];
  25096. for (var name in this._ranges) {
  25097. var range = {};
  25098. range.name = name;
  25099. range.from = this._ranges[name].from;
  25100. range.to = this._ranges[name].to;
  25101. serializationObject.ranges.push(range);
  25102. }
  25103. return serializationObject;
  25104. };
  25105. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25106. get: function () {
  25107. return Animation._ANIMATIONTYPE_FLOAT;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25113. get: function () {
  25114. return Animation._ANIMATIONTYPE_VECTOR3;
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25120. get: function () {
  25121. return Animation._ANIMATIONTYPE_VECTOR2;
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25127. get: function () {
  25128. return Animation._ANIMATIONTYPE_QUATERNION;
  25129. },
  25130. enumerable: true,
  25131. configurable: true
  25132. });
  25133. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25134. get: function () {
  25135. return Animation._ANIMATIONTYPE_MATRIX;
  25136. },
  25137. enumerable: true,
  25138. configurable: true
  25139. });
  25140. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25141. get: function () {
  25142. return Animation._ANIMATIONTYPE_COLOR3;
  25143. },
  25144. enumerable: true,
  25145. configurable: true
  25146. });
  25147. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25148. get: function () {
  25149. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25155. get: function () {
  25156. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25157. },
  25158. enumerable: true,
  25159. configurable: true
  25160. });
  25161. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25162. get: function () {
  25163. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25164. },
  25165. enumerable: true,
  25166. configurable: true
  25167. });
  25168. Animation.Parse = function (parsedAnimation) {
  25169. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25170. var dataType = parsedAnimation.dataType;
  25171. var keys = [];
  25172. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25173. var key = parsedAnimation.keys[index];
  25174. var data;
  25175. switch (dataType) {
  25176. case Animation.ANIMATIONTYPE_FLOAT:
  25177. data = key.values[0];
  25178. break;
  25179. case Animation.ANIMATIONTYPE_QUATERNION:
  25180. data = BABYLON.Quaternion.FromArray(key.values);
  25181. break;
  25182. case Animation.ANIMATIONTYPE_MATRIX:
  25183. data = BABYLON.Matrix.FromArray(key.values);
  25184. break;
  25185. case Animation.ANIMATIONTYPE_COLOR3:
  25186. data = BABYLON.Color3.FromArray(key.values);
  25187. break;
  25188. case Animation.ANIMATIONTYPE_VECTOR3:
  25189. default:
  25190. data = BABYLON.Vector3.FromArray(key.values);
  25191. break;
  25192. }
  25193. keys.push({
  25194. frame: key.frame,
  25195. value: data
  25196. });
  25197. }
  25198. animation.setKeys(keys);
  25199. if (parsedAnimation.ranges) {
  25200. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25201. data = parsedAnimation.ranges[index];
  25202. animation.createRange(data.name, data.from, data.to);
  25203. }
  25204. }
  25205. return animation;
  25206. };
  25207. Animation.AppendSerializedAnimations = function (source, destination) {
  25208. if (source.animations) {
  25209. destination.animations = [];
  25210. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25211. var animation = source.animations[animationIndex];
  25212. destination.animations.push(animation.serialize());
  25213. }
  25214. }
  25215. };
  25216. // Statics
  25217. Animation._ANIMATIONTYPE_FLOAT = 0;
  25218. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25219. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25220. Animation._ANIMATIONTYPE_MATRIX = 3;
  25221. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25222. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25223. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25224. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25225. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25226. return Animation;
  25227. })();
  25228. BABYLON.Animation = Animation;
  25229. })(BABYLON || (BABYLON = {}));
  25230. var BABYLON;
  25231. (function (BABYLON) {
  25232. var Animatable = (function () {
  25233. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25234. if (fromFrame === void 0) { fromFrame = 0; }
  25235. if (toFrame === void 0) { toFrame = 100; }
  25236. if (loopAnimation === void 0) { loopAnimation = false; }
  25237. if (speedRatio === void 0) { speedRatio = 1.0; }
  25238. this.target = target;
  25239. this.fromFrame = fromFrame;
  25240. this.toFrame = toFrame;
  25241. this.loopAnimation = loopAnimation;
  25242. this.speedRatio = speedRatio;
  25243. this.onAnimationEnd = onAnimationEnd;
  25244. this._animations = new Array();
  25245. this._paused = false;
  25246. this.animationStarted = false;
  25247. if (animations) {
  25248. this.appendAnimations(target, animations);
  25249. }
  25250. this._scene = scene;
  25251. scene._activeAnimatables.push(this);
  25252. }
  25253. // Methods
  25254. Animatable.prototype.getAnimations = function () {
  25255. return this._animations;
  25256. };
  25257. Animatable.prototype.appendAnimations = function (target, animations) {
  25258. for (var index = 0; index < animations.length; index++) {
  25259. var animation = animations[index];
  25260. animation._target = target;
  25261. this._animations.push(animation);
  25262. }
  25263. };
  25264. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25265. var animations = this._animations;
  25266. for (var index = 0; index < animations.length; index++) {
  25267. if (animations[index].targetProperty === property) {
  25268. return animations[index];
  25269. }
  25270. }
  25271. return null;
  25272. };
  25273. Animatable.prototype.reset = function () {
  25274. var animations = this._animations;
  25275. for (var index = 0; index < animations.length; index++) {
  25276. animations[index].reset();
  25277. }
  25278. this._localDelayOffset = null;
  25279. this._pausedDelay = null;
  25280. };
  25281. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25282. var animations = this._animations;
  25283. for (var index = 0; index < animations.length; index++) {
  25284. animations[index].enableBlending = true;
  25285. animations[index].blendingSpeed = blendingSpeed;
  25286. }
  25287. };
  25288. Animatable.prototype.disableBlending = function () {
  25289. var animations = this._animations;
  25290. for (var index = 0; index < animations.length; index++) {
  25291. animations[index].enableBlending = false;
  25292. }
  25293. };
  25294. Animatable.prototype.goToFrame = function (frame) {
  25295. var animations = this._animations;
  25296. for (var index = 0; index < animations.length; index++) {
  25297. animations[index].goToFrame(frame);
  25298. }
  25299. };
  25300. Animatable.prototype.pause = function () {
  25301. if (this._paused) {
  25302. return;
  25303. }
  25304. this._paused = true;
  25305. };
  25306. Animatable.prototype.restart = function () {
  25307. this._paused = false;
  25308. };
  25309. Animatable.prototype.stop = function () {
  25310. var index = this._scene._activeAnimatables.indexOf(this);
  25311. if (index > -1) {
  25312. this._scene._activeAnimatables.splice(index, 1);
  25313. var animations = this._animations;
  25314. for (var index = 0; index < animations.length; index++) {
  25315. animations[index].reset();
  25316. }
  25317. if (this.onAnimationEnd) {
  25318. this.onAnimationEnd();
  25319. }
  25320. }
  25321. };
  25322. Animatable.prototype._animate = function (delay) {
  25323. if (this._paused) {
  25324. this.animationStarted = false;
  25325. if (!this._pausedDelay) {
  25326. this._pausedDelay = delay;
  25327. }
  25328. return true;
  25329. }
  25330. if (!this._localDelayOffset) {
  25331. this._localDelayOffset = delay;
  25332. }
  25333. else if (this._pausedDelay) {
  25334. this._localDelayOffset += delay - this._pausedDelay;
  25335. this._pausedDelay = null;
  25336. }
  25337. // Animating
  25338. var running = false;
  25339. var animations = this._animations;
  25340. var index;
  25341. for (index = 0; index < animations.length; index++) {
  25342. var animation = animations[index];
  25343. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25344. running = running || isRunning;
  25345. }
  25346. this.animationStarted = running;
  25347. if (!running) {
  25348. // Remove from active animatables
  25349. index = this._scene._activeAnimatables.indexOf(this);
  25350. this._scene._activeAnimatables.splice(index, 1);
  25351. }
  25352. if (!running && this.onAnimationEnd) {
  25353. this.onAnimationEnd();
  25354. this.onAnimationEnd = null;
  25355. }
  25356. return running;
  25357. };
  25358. return Animatable;
  25359. })();
  25360. BABYLON.Animatable = Animatable;
  25361. })(BABYLON || (BABYLON = {}));
  25362. var BABYLON;
  25363. (function (BABYLON) {
  25364. var EasingFunction = (function () {
  25365. function EasingFunction() {
  25366. // Properties
  25367. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25368. }
  25369. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25370. get: function () {
  25371. return EasingFunction._EASINGMODE_EASEIN;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25377. get: function () {
  25378. return EasingFunction._EASINGMODE_EASEOUT;
  25379. },
  25380. enumerable: true,
  25381. configurable: true
  25382. });
  25383. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25384. get: function () {
  25385. return EasingFunction._EASINGMODE_EASEINOUT;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25391. var n = Math.min(Math.max(easingMode, 0), 2);
  25392. this._easingMode = n;
  25393. };
  25394. EasingFunction.prototype.getEasingMode = function () {
  25395. return this._easingMode;
  25396. };
  25397. EasingFunction.prototype.easeInCore = function (gradient) {
  25398. throw new Error('You must implement this method');
  25399. };
  25400. EasingFunction.prototype.ease = function (gradient) {
  25401. switch (this._easingMode) {
  25402. case EasingFunction.EASINGMODE_EASEIN:
  25403. return this.easeInCore(gradient);
  25404. case EasingFunction.EASINGMODE_EASEOUT:
  25405. return (1 - this.easeInCore(1 - gradient));
  25406. }
  25407. if (gradient >= 0.5) {
  25408. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25409. }
  25410. return (this.easeInCore(gradient * 2) * 0.5);
  25411. };
  25412. //Statics
  25413. EasingFunction._EASINGMODE_EASEIN = 0;
  25414. EasingFunction._EASINGMODE_EASEOUT = 1;
  25415. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25416. return EasingFunction;
  25417. })();
  25418. BABYLON.EasingFunction = EasingFunction;
  25419. var CircleEase = (function (_super) {
  25420. __extends(CircleEase, _super);
  25421. function CircleEase() {
  25422. _super.apply(this, arguments);
  25423. }
  25424. CircleEase.prototype.easeInCore = function (gradient) {
  25425. gradient = Math.max(0, Math.min(1, gradient));
  25426. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25427. };
  25428. return CircleEase;
  25429. })(EasingFunction);
  25430. BABYLON.CircleEase = CircleEase;
  25431. var BackEase = (function (_super) {
  25432. __extends(BackEase, _super);
  25433. function BackEase(amplitude) {
  25434. if (amplitude === void 0) { amplitude = 1; }
  25435. _super.call(this);
  25436. this.amplitude = amplitude;
  25437. }
  25438. BackEase.prototype.easeInCore = function (gradient) {
  25439. var num = Math.max(0, this.amplitude);
  25440. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25441. };
  25442. return BackEase;
  25443. })(EasingFunction);
  25444. BABYLON.BackEase = BackEase;
  25445. var BounceEase = (function (_super) {
  25446. __extends(BounceEase, _super);
  25447. function BounceEase(bounces, bounciness) {
  25448. if (bounces === void 0) { bounces = 3; }
  25449. if (bounciness === void 0) { bounciness = 2; }
  25450. _super.call(this);
  25451. this.bounces = bounces;
  25452. this.bounciness = bounciness;
  25453. }
  25454. BounceEase.prototype.easeInCore = function (gradient) {
  25455. var y = Math.max(0.0, this.bounces);
  25456. var bounciness = this.bounciness;
  25457. if (bounciness <= 1.0) {
  25458. bounciness = 1.001;
  25459. }
  25460. var num9 = Math.pow(bounciness, y);
  25461. var num5 = 1.0 - bounciness;
  25462. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25463. var num15 = gradient * num4;
  25464. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25465. var num3 = Math.floor(num65);
  25466. var num13 = num3 + 1.0;
  25467. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25468. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25469. var num7 = (num8 + num12) * 0.5;
  25470. var num6 = gradient - num7;
  25471. var num2 = num7 - num8;
  25472. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25473. };
  25474. return BounceEase;
  25475. })(EasingFunction);
  25476. BABYLON.BounceEase = BounceEase;
  25477. var CubicEase = (function (_super) {
  25478. __extends(CubicEase, _super);
  25479. function CubicEase() {
  25480. _super.apply(this, arguments);
  25481. }
  25482. CubicEase.prototype.easeInCore = function (gradient) {
  25483. return (gradient * gradient * gradient);
  25484. };
  25485. return CubicEase;
  25486. })(EasingFunction);
  25487. BABYLON.CubicEase = CubicEase;
  25488. var ElasticEase = (function (_super) {
  25489. __extends(ElasticEase, _super);
  25490. function ElasticEase(oscillations, springiness) {
  25491. if (oscillations === void 0) { oscillations = 3; }
  25492. if (springiness === void 0) { springiness = 3; }
  25493. _super.call(this);
  25494. this.oscillations = oscillations;
  25495. this.springiness = springiness;
  25496. }
  25497. ElasticEase.prototype.easeInCore = function (gradient) {
  25498. var num2;
  25499. var num3 = Math.max(0.0, this.oscillations);
  25500. var num = Math.max(0.0, this.springiness);
  25501. if (num == 0) {
  25502. num2 = gradient;
  25503. }
  25504. else {
  25505. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  25506. }
  25507. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  25508. };
  25509. return ElasticEase;
  25510. })(EasingFunction);
  25511. BABYLON.ElasticEase = ElasticEase;
  25512. var ExponentialEase = (function (_super) {
  25513. __extends(ExponentialEase, _super);
  25514. function ExponentialEase(exponent) {
  25515. if (exponent === void 0) { exponent = 2; }
  25516. _super.call(this);
  25517. this.exponent = exponent;
  25518. }
  25519. ExponentialEase.prototype.easeInCore = function (gradient) {
  25520. if (this.exponent <= 0) {
  25521. return gradient;
  25522. }
  25523. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  25524. };
  25525. return ExponentialEase;
  25526. })(EasingFunction);
  25527. BABYLON.ExponentialEase = ExponentialEase;
  25528. var PowerEase = (function (_super) {
  25529. __extends(PowerEase, _super);
  25530. function PowerEase(power) {
  25531. if (power === void 0) { power = 2; }
  25532. _super.call(this);
  25533. this.power = power;
  25534. }
  25535. PowerEase.prototype.easeInCore = function (gradient) {
  25536. var y = Math.max(0.0, this.power);
  25537. return Math.pow(gradient, y);
  25538. };
  25539. return PowerEase;
  25540. })(EasingFunction);
  25541. BABYLON.PowerEase = PowerEase;
  25542. var QuadraticEase = (function (_super) {
  25543. __extends(QuadraticEase, _super);
  25544. function QuadraticEase() {
  25545. _super.apply(this, arguments);
  25546. }
  25547. QuadraticEase.prototype.easeInCore = function (gradient) {
  25548. return (gradient * gradient);
  25549. };
  25550. return QuadraticEase;
  25551. })(EasingFunction);
  25552. BABYLON.QuadraticEase = QuadraticEase;
  25553. var QuarticEase = (function (_super) {
  25554. __extends(QuarticEase, _super);
  25555. function QuarticEase() {
  25556. _super.apply(this, arguments);
  25557. }
  25558. QuarticEase.prototype.easeInCore = function (gradient) {
  25559. return (gradient * gradient * gradient * gradient);
  25560. };
  25561. return QuarticEase;
  25562. })(EasingFunction);
  25563. BABYLON.QuarticEase = QuarticEase;
  25564. var QuinticEase = (function (_super) {
  25565. __extends(QuinticEase, _super);
  25566. function QuinticEase() {
  25567. _super.apply(this, arguments);
  25568. }
  25569. QuinticEase.prototype.easeInCore = function (gradient) {
  25570. return (gradient * gradient * gradient * gradient * gradient);
  25571. };
  25572. return QuinticEase;
  25573. })(EasingFunction);
  25574. BABYLON.QuinticEase = QuinticEase;
  25575. var SineEase = (function (_super) {
  25576. __extends(SineEase, _super);
  25577. function SineEase() {
  25578. _super.apply(this, arguments);
  25579. }
  25580. SineEase.prototype.easeInCore = function (gradient) {
  25581. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  25582. };
  25583. return SineEase;
  25584. })(EasingFunction);
  25585. BABYLON.SineEase = SineEase;
  25586. var BezierCurveEase = (function (_super) {
  25587. __extends(BezierCurveEase, _super);
  25588. function BezierCurveEase(x1, y1, x2, y2) {
  25589. if (x1 === void 0) { x1 = 0; }
  25590. if (y1 === void 0) { y1 = 0; }
  25591. if (x2 === void 0) { x2 = 1; }
  25592. if (y2 === void 0) { y2 = 1; }
  25593. _super.call(this);
  25594. this.x1 = x1;
  25595. this.y1 = y1;
  25596. this.x2 = x2;
  25597. this.y2 = y2;
  25598. }
  25599. BezierCurveEase.prototype.easeInCore = function (gradient) {
  25600. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  25601. };
  25602. return BezierCurveEase;
  25603. })(EasingFunction);
  25604. BABYLON.BezierCurveEase = BezierCurveEase;
  25605. })(BABYLON || (BABYLON = {}));
  25606. var BABYLON;
  25607. (function (BABYLON) {
  25608. var Bone = (function (_super) {
  25609. __extends(Bone, _super);
  25610. function Bone(name, skeleton, parentBone, matrix, restPose) {
  25611. _super.call(this, name, skeleton.getScene());
  25612. this.name = name;
  25613. this.children = new Array();
  25614. this.animations = new Array();
  25615. this._worldTransform = new BABYLON.Matrix();
  25616. this._absoluteTransform = new BABYLON.Matrix();
  25617. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  25618. this._skeleton = skeleton;
  25619. this._matrix = matrix;
  25620. this._baseMatrix = matrix;
  25621. this._restPose = restPose ? restPose : matrix.clone();
  25622. skeleton.bones.push(this);
  25623. if (parentBone) {
  25624. this._parent = parentBone;
  25625. parentBone.children.push(this);
  25626. }
  25627. else {
  25628. this._parent = null;
  25629. }
  25630. this._updateDifferenceMatrix();
  25631. }
  25632. // Members
  25633. Bone.prototype.getParent = function () {
  25634. return this._parent;
  25635. };
  25636. Bone.prototype.getLocalMatrix = function () {
  25637. return this._matrix;
  25638. };
  25639. Bone.prototype.getBaseMatrix = function () {
  25640. return this._baseMatrix;
  25641. };
  25642. Bone.prototype.getRestPose = function () {
  25643. return this._restPose;
  25644. };
  25645. Bone.prototype.returnToRest = function () {
  25646. this.updateMatrix(this._restPose.clone());
  25647. };
  25648. Bone.prototype.getWorldMatrix = function () {
  25649. return this._worldTransform;
  25650. };
  25651. Bone.prototype.getInvertedAbsoluteTransform = function () {
  25652. return this._invertedAbsoluteTransform;
  25653. };
  25654. Bone.prototype.getAbsoluteTransform = function () {
  25655. return this._absoluteTransform;
  25656. };
  25657. // Methods
  25658. Bone.prototype.updateMatrix = function (matrix) {
  25659. this._baseMatrix = matrix.clone();
  25660. this._matrix = matrix.clone();
  25661. this._skeleton._markAsDirty();
  25662. this._updateDifferenceMatrix();
  25663. };
  25664. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  25665. if (!rootMatrix) {
  25666. rootMatrix = this._baseMatrix;
  25667. }
  25668. if (this._parent) {
  25669. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  25670. }
  25671. else {
  25672. this._absoluteTransform.copyFrom(rootMatrix);
  25673. }
  25674. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  25675. for (var index = 0; index < this.children.length; index++) {
  25676. this.children[index]._updateDifferenceMatrix();
  25677. }
  25678. };
  25679. Bone.prototype.markAsDirty = function () {
  25680. this._currentRenderId++;
  25681. this._skeleton._markAsDirty();
  25682. };
  25683. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  25684. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  25685. // all animation may be coming from a library skeleton, so may need to create animation
  25686. if (this.animations.length === 0) {
  25687. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  25688. this.animations[0].setKeys([]);
  25689. }
  25690. // get animation info / verify there is such a range from the source bone
  25691. var sourceRange = source.animations[0].getRange(rangeName);
  25692. if (!sourceRange) {
  25693. return false;
  25694. }
  25695. var from = sourceRange.from;
  25696. var to = sourceRange.to;
  25697. var sourceKeys = source.animations[0].getKeys();
  25698. // rescaling prep
  25699. var sourceBoneLength = source.length;
  25700. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  25701. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  25702. var destKeys = this.animations[0].getKeys();
  25703. // loop vars declaration / initialization
  25704. var orig;
  25705. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  25706. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  25707. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  25708. var mat;
  25709. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  25710. orig = sourceKeys[key];
  25711. if (orig.frame >= from && orig.frame <= to) {
  25712. if (scalingReqd) {
  25713. orig.value.decompose(origScale, origRotation, origTranslation);
  25714. origTranslation.scaleInPlace(ratio);
  25715. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  25716. }
  25717. else {
  25718. mat = orig.value;
  25719. }
  25720. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  25721. }
  25722. }
  25723. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  25724. return true;
  25725. };
  25726. return Bone;
  25727. })(BABYLON.Node);
  25728. BABYLON.Bone = Bone;
  25729. })(BABYLON || (BABYLON = {}));
  25730. var BABYLON;
  25731. (function (BABYLON) {
  25732. var Skeleton = (function () {
  25733. function Skeleton(name, id, scene) {
  25734. this.name = name;
  25735. this.id = id;
  25736. this.bones = new Array();
  25737. this.needInitialSkinMatrix = false;
  25738. this._isDirty = true;
  25739. this._meshesWithPoseMatrix = new Array();
  25740. this._identity = BABYLON.Matrix.Identity();
  25741. this._ranges = {};
  25742. this.bones = [];
  25743. this._scene = scene;
  25744. scene.skeletons.push(this);
  25745. //make sure it will recalculate the matrix next time prepare is called.
  25746. this._isDirty = true;
  25747. }
  25748. // Members
  25749. Skeleton.prototype.getTransformMatrices = function (mesh) {
  25750. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  25751. return mesh._bonesTransformMatrices;
  25752. }
  25753. return this._transformMatrices;
  25754. };
  25755. Skeleton.prototype.getScene = function () {
  25756. return this._scene;
  25757. };
  25758. // Methods
  25759. /**
  25760. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25761. */
  25762. Skeleton.prototype.toString = function (fullDetails) {
  25763. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  25764. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25765. if (fullDetails) {
  25766. ret += ", Ranges: {";
  25767. var first = true;
  25768. for (var name in this._ranges) {
  25769. if (!first) {
  25770. ret + ", ";
  25771. first = false;
  25772. }
  25773. ret += name;
  25774. }
  25775. ret += "}";
  25776. }
  25777. return ret;
  25778. };
  25779. /**
  25780. * Get bone's index searching by name
  25781. * @param {string} name is bone's name to search for
  25782. * @return {number} Indice of the bone. Returns -1 if not found
  25783. */
  25784. Skeleton.prototype.getBoneIndexByName = function (name) {
  25785. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  25786. if (this.bones[boneIndex].name === name) {
  25787. return boneIndex;
  25788. }
  25789. }
  25790. return -1;
  25791. };
  25792. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  25793. // check name not already in use
  25794. if (!this._ranges[name]) {
  25795. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  25796. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25797. if (this.bones[i].animations[0]) {
  25798. this.bones[i].animations[0].createRange(name, from, to);
  25799. }
  25800. }
  25801. }
  25802. };
  25803. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  25804. if (deleteFrames === void 0) { deleteFrames = true; }
  25805. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25806. if (this.bones[i].animations[0]) {
  25807. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  25808. }
  25809. }
  25810. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25811. };
  25812. Skeleton.prototype.getAnimationRange = function (name) {
  25813. return this._ranges[name];
  25814. };
  25815. /**
  25816. * Returns as an Array, all AnimationRanges defined on this skeleton
  25817. */
  25818. Skeleton.prototype.getAnimationRanges = function () {
  25819. var animationRanges = [];
  25820. var name;
  25821. var i = 0;
  25822. for (name in this._ranges) {
  25823. animationRanges[i] = this._ranges[name];
  25824. i++;
  25825. }
  25826. return animationRanges;
  25827. };
  25828. /**
  25829. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  25830. */
  25831. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  25832. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  25833. if (this._ranges[name] || !source.getAnimationRange(name)) {
  25834. return false;
  25835. }
  25836. var ret = true;
  25837. var frameOffset = this._getHighestAnimationFrame() + 1;
  25838. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  25839. var boneDict = {};
  25840. var sourceBones = source.bones;
  25841. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  25842. boneDict[sourceBones[i].name] = sourceBones[i];
  25843. }
  25844. if (this.bones.length !== sourceBones.length) {
  25845. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  25846. ret = false;
  25847. }
  25848. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25849. var boneName = this.bones[i].name;
  25850. var sourceBone = boneDict[boneName];
  25851. if (sourceBone) {
  25852. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  25853. }
  25854. else {
  25855. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  25856. ret = false;
  25857. }
  25858. }
  25859. // do not call createAnimationRange(), since it also is done to bones, which was already done
  25860. var range = source.getAnimationRange(name);
  25861. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  25862. return ret;
  25863. };
  25864. Skeleton.prototype.returnToRest = function () {
  25865. for (var index = 0; index < this.bones.length; index++) {
  25866. this.bones[index].returnToRest();
  25867. }
  25868. };
  25869. Skeleton.prototype._getHighestAnimationFrame = function () {
  25870. var ret = 0;
  25871. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  25872. if (this.bones[i].animations[0]) {
  25873. var highest = this.bones[i].animations[0].getHighestFrame();
  25874. if (ret < highest) {
  25875. ret = highest;
  25876. }
  25877. }
  25878. }
  25879. return ret;
  25880. };
  25881. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  25882. var range = this.getAnimationRange(name);
  25883. if (!range) {
  25884. return null;
  25885. }
  25886. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  25887. };
  25888. Skeleton.prototype._markAsDirty = function () {
  25889. this._isDirty = true;
  25890. };
  25891. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  25892. this._meshesWithPoseMatrix.push(mesh);
  25893. };
  25894. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  25895. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  25896. if (index > -1) {
  25897. this._meshesWithPoseMatrix.splice(index, 1);
  25898. }
  25899. };
  25900. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  25901. for (var index = 0; index < this.bones.length; index++) {
  25902. var bone = this.bones[index];
  25903. var parentBone = bone.getParent();
  25904. if (parentBone) {
  25905. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  25906. }
  25907. else {
  25908. if (initialSkinMatrix) {
  25909. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  25910. }
  25911. else {
  25912. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  25913. }
  25914. }
  25915. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  25916. }
  25917. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  25918. };
  25919. Skeleton.prototype.prepare = function () {
  25920. if (!this._isDirty) {
  25921. return;
  25922. }
  25923. if (this.needInitialSkinMatrix) {
  25924. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  25925. var mesh = this._meshesWithPoseMatrix[index];
  25926. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  25927. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25928. }
  25929. var poseMatrix = mesh.getPoseMatrix();
  25930. // Prepare bones
  25931. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  25932. var bone = this.bones[boneIndex];
  25933. if (!bone.getParent()) {
  25934. var matrix = bone.getBaseMatrix();
  25935. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  25936. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  25937. }
  25938. }
  25939. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  25940. }
  25941. }
  25942. else {
  25943. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  25944. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  25945. }
  25946. this._computeTransformMatrices(this._transformMatrices, null);
  25947. }
  25948. this._isDirty = false;
  25949. this._scene._activeBones += this.bones.length;
  25950. };
  25951. Skeleton.prototype.getAnimatables = function () {
  25952. if (!this._animatables || this._animatables.length !== this.bones.length) {
  25953. this._animatables = [];
  25954. for (var index = 0; index < this.bones.length; index++) {
  25955. this._animatables.push(this.bones[index]);
  25956. }
  25957. }
  25958. return this._animatables;
  25959. };
  25960. Skeleton.prototype.clone = function (name, id) {
  25961. var result = new Skeleton(name, id || name, this._scene);
  25962. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25963. for (var index = 0; index < this.bones.length; index++) {
  25964. var source = this.bones[index];
  25965. var parentBone = null;
  25966. if (source.getParent()) {
  25967. var parentIndex = this.bones.indexOf(source.getParent());
  25968. parentBone = result.bones[parentIndex];
  25969. }
  25970. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  25971. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  25972. }
  25973. if (this._ranges) {
  25974. result._ranges = {};
  25975. for (var rangeName in this._ranges) {
  25976. result._ranges[rangeName] = this._ranges[rangeName].clone();
  25977. }
  25978. }
  25979. this._isDirty = true;
  25980. return result;
  25981. };
  25982. Skeleton.prototype.dispose = function () {
  25983. this._meshesWithPoseMatrix = [];
  25984. // Animations
  25985. this.getScene().stopAnimation(this);
  25986. // Remove from scene
  25987. this.getScene().removeSkeleton(this);
  25988. };
  25989. Skeleton.prototype.serialize = function () {
  25990. var serializationObject = {};
  25991. serializationObject.name = this.name;
  25992. serializationObject.id = this.id;
  25993. serializationObject.bones = [];
  25994. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  25995. for (var index = 0; index < this.bones.length; index++) {
  25996. var bone = this.bones[index];
  25997. var serializedBone = {
  25998. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  25999. name: bone.name,
  26000. matrix: bone.getLocalMatrix().toArray(),
  26001. rest: bone.getRestPose().toArray()
  26002. };
  26003. serializationObject.bones.push(serializedBone);
  26004. if (bone.length) {
  26005. serializedBone.length = bone.length;
  26006. }
  26007. if (bone.animations && bone.animations.length > 0) {
  26008. serializedBone.animation = bone.animations[0].serialize();
  26009. }
  26010. serializationObject.ranges = [];
  26011. for (var name in this._ranges) {
  26012. var range = {};
  26013. range.name = name;
  26014. range.from = this._ranges[name].from;
  26015. range.to = this._ranges[name].to;
  26016. serializationObject.ranges.push(range);
  26017. }
  26018. }
  26019. return serializationObject;
  26020. };
  26021. Skeleton.Parse = function (parsedSkeleton, scene) {
  26022. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26023. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26024. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26025. var parsedBone = parsedSkeleton.bones[index];
  26026. var parentBone = null;
  26027. if (parsedBone.parentBoneIndex > -1) {
  26028. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26029. }
  26030. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26031. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26032. if (parsedBone.length) {
  26033. bone.length = parsedBone.length;
  26034. }
  26035. if (parsedBone.animation) {
  26036. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26037. }
  26038. }
  26039. // placed after bones, so createAnimationRange can cascade down
  26040. if (parsedSkeleton.ranges) {
  26041. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26042. var data = parsedSkeleton.ranges[index];
  26043. skeleton.createAnimationRange(data.name, data.from, data.to);
  26044. }
  26045. }
  26046. return skeleton;
  26047. };
  26048. return Skeleton;
  26049. })();
  26050. BABYLON.Skeleton = Skeleton;
  26051. })(BABYLON || (BABYLON = {}));
  26052. var BABYLON;
  26053. (function (BABYLON) {
  26054. var PostProcess = (function () {
  26055. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26057. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26058. this.name = name;
  26059. this.width = -1;
  26060. this.height = -1;
  26061. this._reusable = false;
  26062. this._textures = new BABYLON.SmartArray(2);
  26063. this._currentRenderTextureInd = 0;
  26064. if (camera != null) {
  26065. this._camera = camera;
  26066. this._scene = camera.getScene();
  26067. camera.attachPostProcess(this);
  26068. this._engine = this._scene.getEngine();
  26069. }
  26070. else {
  26071. this._engine = engine;
  26072. }
  26073. this._renderRatio = ratio;
  26074. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26075. this._reusable = reusable || false;
  26076. this._textureType = textureType;
  26077. this._samplers = samplers || [];
  26078. this._samplers.push("textureSampler");
  26079. this._fragmentUrl = fragmentUrl;
  26080. this._parameters = parameters || [];
  26081. this.updateEffect(defines);
  26082. }
  26083. PostProcess.prototype.updateEffect = function (defines) {
  26084. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26085. };
  26086. PostProcess.prototype.isReusable = function () {
  26087. return this._reusable;
  26088. };
  26089. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26090. camera = camera || this._camera;
  26091. var scene = camera.getScene();
  26092. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26093. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26094. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26095. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26096. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26097. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26098. if (this._textures.length > 0) {
  26099. for (var i = 0; i < this._textures.length; i++) {
  26100. this._engine._releaseTexture(this._textures.data[i]);
  26101. }
  26102. this._textures.reset();
  26103. }
  26104. this.width = desiredWidth;
  26105. this.height = desiredHeight;
  26106. 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 }));
  26107. if (this._reusable) {
  26108. 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 }));
  26109. }
  26110. if (this.onSizeChanged) {
  26111. this.onSizeChanged();
  26112. }
  26113. }
  26114. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26115. if (this.onActivate) {
  26116. this.onActivate(camera);
  26117. }
  26118. // Clear
  26119. if (this.clearColor) {
  26120. this._engine.clear(this.clearColor, true, true);
  26121. }
  26122. else {
  26123. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26124. }
  26125. if (this._reusable) {
  26126. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26127. }
  26128. };
  26129. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26130. get: function () {
  26131. return this._effect.isSupported;
  26132. },
  26133. enumerable: true,
  26134. configurable: true
  26135. });
  26136. PostProcess.prototype.apply = function () {
  26137. // Check
  26138. if (!this._effect.isReady())
  26139. return null;
  26140. // States
  26141. this._engine.enableEffect(this._effect);
  26142. this._engine.setState(false);
  26143. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26144. this._engine.setDepthBuffer(false);
  26145. this._engine.setDepthWrite(false);
  26146. // Texture
  26147. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26148. // Parameters
  26149. if (this.onApply) {
  26150. this.onApply(this._effect);
  26151. }
  26152. return this._effect;
  26153. };
  26154. PostProcess.prototype.dispose = function (camera) {
  26155. camera = camera || this._camera;
  26156. if (this._textures.length > 0) {
  26157. for (var i = 0; i < this._textures.length; i++) {
  26158. this._engine._releaseTexture(this._textures.data[i]);
  26159. }
  26160. this._textures.reset();
  26161. }
  26162. if (!camera) {
  26163. return;
  26164. }
  26165. camera.detachPostProcess(this);
  26166. var index = camera._postProcesses.indexOf(this);
  26167. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26168. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26169. }
  26170. };
  26171. return PostProcess;
  26172. })();
  26173. BABYLON.PostProcess = PostProcess;
  26174. })(BABYLON || (BABYLON = {}));
  26175. var BABYLON;
  26176. (function (BABYLON) {
  26177. var PostProcessManager = (function () {
  26178. function PostProcessManager(scene) {
  26179. this._vertexDeclaration = [2];
  26180. this._vertexStrideSize = 2 * 4;
  26181. this._scene = scene;
  26182. }
  26183. PostProcessManager.prototype._prepareBuffers = function () {
  26184. if (this._vertexBuffer) {
  26185. return;
  26186. }
  26187. // VBO
  26188. var vertices = [];
  26189. vertices.push(1, 1);
  26190. vertices.push(-1, 1);
  26191. vertices.push(-1, -1);
  26192. vertices.push(1, -1);
  26193. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26194. // Indices
  26195. var indices = [];
  26196. indices.push(0);
  26197. indices.push(1);
  26198. indices.push(2);
  26199. indices.push(0);
  26200. indices.push(2);
  26201. indices.push(3);
  26202. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26203. };
  26204. // Methods
  26205. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26206. var postProcesses = this._scene.activeCamera._postProcesses;
  26207. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26208. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26209. return false;
  26210. }
  26211. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26212. return true;
  26213. };
  26214. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26215. var engine = this._scene.getEngine();
  26216. for (var index = 0; index < postProcesses.length; index++) {
  26217. if (index < postProcesses.length - 1) {
  26218. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26219. }
  26220. else {
  26221. if (targetTexture) {
  26222. engine.bindFramebuffer(targetTexture);
  26223. }
  26224. else {
  26225. engine.restoreDefaultFramebuffer();
  26226. }
  26227. }
  26228. var pp = postProcesses[index];
  26229. var effect = pp.apply();
  26230. if (effect) {
  26231. if (pp.onBeforeRender) {
  26232. pp.onBeforeRender(effect);
  26233. }
  26234. // VBOs
  26235. this._prepareBuffers();
  26236. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26237. // Draw order
  26238. engine.draw(true, 0, 6);
  26239. if (pp.onAfterRender) {
  26240. pp.onAfterRender(effect);
  26241. }
  26242. }
  26243. }
  26244. // Restore depth buffer
  26245. engine.setDepthBuffer(true);
  26246. engine.setDepthWrite(true);
  26247. };
  26248. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26249. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26250. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26251. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26252. return;
  26253. }
  26254. var engine = this._scene.getEngine();
  26255. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26256. if (index < postProcessesTakenIndices.length - 1) {
  26257. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26258. }
  26259. else {
  26260. if (targetTexture) {
  26261. engine.bindFramebuffer(targetTexture, faceIndex);
  26262. }
  26263. else {
  26264. engine.restoreDefaultFramebuffer();
  26265. }
  26266. }
  26267. if (doNotPresent) {
  26268. break;
  26269. }
  26270. var pp = postProcesses[postProcessesTakenIndices[index]];
  26271. var effect = pp.apply();
  26272. if (effect) {
  26273. if (pp.onBeforeRender) {
  26274. pp.onBeforeRender(effect);
  26275. }
  26276. // VBOs
  26277. this._prepareBuffers();
  26278. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26279. // Draw order
  26280. engine.draw(true, 0, 6);
  26281. if (pp.onAfterRender) {
  26282. pp.onAfterRender(effect);
  26283. }
  26284. }
  26285. }
  26286. // Restore depth buffer
  26287. engine.setDepthBuffer(true);
  26288. engine.setDepthWrite(true);
  26289. };
  26290. PostProcessManager.prototype.dispose = function () {
  26291. if (this._vertexBuffer) {
  26292. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26293. this._vertexBuffer = null;
  26294. }
  26295. if (this._indexBuffer) {
  26296. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26297. this._indexBuffer = null;
  26298. }
  26299. };
  26300. return PostProcessManager;
  26301. })();
  26302. BABYLON.PostProcessManager = PostProcessManager;
  26303. })(BABYLON || (BABYLON = {}));
  26304. var BABYLON;
  26305. (function (BABYLON) {
  26306. var PassPostProcess = (function (_super) {
  26307. __extends(PassPostProcess, _super);
  26308. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26309. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26310. }
  26311. return PassPostProcess;
  26312. })(BABYLON.PostProcess);
  26313. BABYLON.PassPostProcess = PassPostProcess;
  26314. })(BABYLON || (BABYLON = {}));
  26315. var BABYLON;
  26316. (function (BABYLON) {
  26317. /**
  26318. * This is a holder class for the physics joint created by the physics plugin.
  26319. * It holds a set of functions to control the underlying joint.
  26320. */
  26321. var PhysicsJoint = (function () {
  26322. function PhysicsJoint(type, jointData) {
  26323. this.type = type;
  26324. this.jointData = jointData;
  26325. jointData.nativeParams = jointData.nativeParams || {};
  26326. }
  26327. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26328. get: function () {
  26329. return this._physicsJoint;
  26330. },
  26331. set: function (newJoint) {
  26332. if (this._physicsJoint) {
  26333. }
  26334. this._physicsJoint = newJoint;
  26335. },
  26336. enumerable: true,
  26337. configurable: true
  26338. });
  26339. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26340. set: function (physicsPlugin) {
  26341. this._physicsPlugin = physicsPlugin;
  26342. },
  26343. enumerable: true,
  26344. configurable: true
  26345. });
  26346. /**
  26347. * Execute a function that is physics-plugin specific.
  26348. * @param {Function} func the function that will be executed.
  26349. * It accepts two parameters: the physics world and the physics joint.
  26350. */
  26351. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26352. func(this._physicsPlugin.world, this._physicsJoint);
  26353. };
  26354. //TODO check if the native joints are the same
  26355. //Joint Types
  26356. PhysicsJoint.DistanceJoint = 0;
  26357. PhysicsJoint.HingeJoint = 1;
  26358. PhysicsJoint.BallAndSocketJoint = 2;
  26359. PhysicsJoint.WheelJoint = 3;
  26360. PhysicsJoint.SliderJoint = 4;
  26361. //OIMO
  26362. PhysicsJoint.PrismaticJoint = 5;
  26363. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26364. PhysicsJoint.UniversalJoint = 6;
  26365. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26366. //Cannon
  26367. //Similar to a Ball-Joint. Different in params
  26368. PhysicsJoint.PointToPointJoint = 8;
  26369. //Cannon only at the moment
  26370. PhysicsJoint.SpringJoint = 9;
  26371. return PhysicsJoint;
  26372. })();
  26373. BABYLON.PhysicsJoint = PhysicsJoint;
  26374. /**
  26375. * A class representing a physics distance joint.
  26376. */
  26377. var DistanceJoint = (function (_super) {
  26378. __extends(DistanceJoint, _super);
  26379. function DistanceJoint(jointData) {
  26380. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26381. }
  26382. /**
  26383. * Update the predefined distance.
  26384. */
  26385. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26386. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26387. };
  26388. return DistanceJoint;
  26389. })(PhysicsJoint);
  26390. BABYLON.DistanceJoint = DistanceJoint;
  26391. /**
  26392. * This class represents a single hinge physics joint
  26393. */
  26394. var HingeJoint = (function (_super) {
  26395. __extends(HingeJoint, _super);
  26396. function HingeJoint(jointData) {
  26397. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26398. }
  26399. /**
  26400. * Set the motor values.
  26401. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26402. * @param {number} force the force to apply
  26403. * @param {number} maxForce max force for this motor.
  26404. */
  26405. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26406. this._physicsPlugin.setMotor(this, force, maxForce);
  26407. };
  26408. /**
  26409. * Set the motor's limits.
  26410. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26411. */
  26412. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26413. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26414. };
  26415. return HingeJoint;
  26416. })(PhysicsJoint);
  26417. BABYLON.HingeJoint = HingeJoint;
  26418. /**
  26419. * This class represents a dual hinge physics joint (same as wheel joint)
  26420. */
  26421. var Hinge2Joint = (function (_super) {
  26422. __extends(Hinge2Joint, _super);
  26423. function Hinge2Joint(jointData) {
  26424. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26425. }
  26426. /**
  26427. * Set the motor values.
  26428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26429. * @param {number} force the force to apply
  26430. * @param {number} maxForce max force for this motor.
  26431. * @param {motorIndex} the motor's index, 0 or 1.
  26432. */
  26433. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26434. if (motorIndex === void 0) { motorIndex = 0; }
  26435. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26436. };
  26437. /**
  26438. * Set the motor limits.
  26439. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26440. * @param {number} upperLimit the upper limit
  26441. * @param {number} lowerLimit lower limit
  26442. * @param {motorIndex} the motor's index, 0 or 1.
  26443. */
  26444. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26445. if (motorIndex === void 0) { motorIndex = 0; }
  26446. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26447. };
  26448. return Hinge2Joint;
  26449. })(PhysicsJoint);
  26450. BABYLON.Hinge2Joint = Hinge2Joint;
  26451. })(BABYLON || (BABYLON = {}));
  26452. var BABYLON;
  26453. (function (BABYLON) {
  26454. var PhysicsImpostor = (function () {
  26455. function PhysicsImpostor(object, type, _options, scene) {
  26456. var _this = this;
  26457. if (_options === void 0) { _options = { mass: 0 }; }
  26458. this.object = object;
  26459. this.type = type;
  26460. this._options = _options;
  26461. this._bodyUpdateRequired = false;
  26462. this._onBeforePhysicsStepCallbacks = new Array();
  26463. this._onAfterPhysicsStepCallbacks = new Array();
  26464. this._onPhysicsCollideCallbacks = [];
  26465. this._deltaPosition = BABYLON.Vector3.Zero();
  26466. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26467. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26468. /**
  26469. * this function is executed by the physics engine.
  26470. */
  26471. this.beforeStep = function () {
  26472. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26473. //conjugate deltaRotation
  26474. if (_this._deltaRotationConjugated) {
  26475. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26476. }
  26477. else {
  26478. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26479. }
  26480. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26481. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26482. func(_this);
  26483. });
  26484. };
  26485. /**
  26486. * this function is executed by the physics engine.
  26487. */
  26488. this.afterStep = function () {
  26489. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26490. func(_this);
  26491. });
  26492. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26493. _this.object.position.addInPlace(_this._deltaPosition);
  26494. if (_this._deltaRotation) {
  26495. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  26496. }
  26497. };
  26498. //event and body object due to cannon's event-based architecture.
  26499. this.onCollide = function (e) {
  26500. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  26501. if (otherImpostor) {
  26502. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  26503. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  26504. }).forEach(function (obj) {
  26505. obj.callback(_this, otherImpostor);
  26506. });
  26507. }
  26508. };
  26509. //legacy support for old syntax.
  26510. if (!scene && object.getScene) {
  26511. scene = object.getScene();
  26512. }
  26513. this._physicsEngine = scene.getPhysicsEngine();
  26514. if (!this._physicsEngine) {
  26515. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  26516. }
  26517. else {
  26518. //set the object's quaternion, if not set
  26519. if (!this.object.rotationQuaternion) {
  26520. if (this.object.rotation) {
  26521. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  26522. }
  26523. else {
  26524. this.object.rotationQuaternion = new BABYLON.Quaternion();
  26525. }
  26526. }
  26527. //default options params
  26528. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  26529. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  26530. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  26531. this._joints = [];
  26532. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  26533. if (!this.object.parent) {
  26534. this._init();
  26535. }
  26536. }
  26537. }
  26538. /**
  26539. * This function will completly initialize this impostor.
  26540. * It will create a new body - but only if this mesh has no parent.
  26541. * If it has, this impostor will not be used other than to define the impostor
  26542. * of the child mesh.
  26543. */
  26544. PhysicsImpostor.prototype._init = function () {
  26545. this._physicsEngine.removeImpostor(this);
  26546. this.physicsBody = null;
  26547. this._parent = this._parent || this._getPhysicsParent();
  26548. if (!this.parent) {
  26549. this._physicsEngine.addImpostor(this);
  26550. }
  26551. };
  26552. PhysicsImpostor.prototype._getPhysicsParent = function () {
  26553. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  26554. var parentMesh = this.object.parent;
  26555. return parentMesh.physicsImpostor;
  26556. }
  26557. return;
  26558. };
  26559. /**
  26560. * Should a new body be generated.
  26561. */
  26562. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  26563. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  26564. };
  26565. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  26566. this.forceUpdate();
  26567. };
  26568. /**
  26569. * Force a regeneration of this or the parent's impostor's body.
  26570. * Use under cautious - This will remove all joints already implemented.
  26571. */
  26572. PhysicsImpostor.prototype.forceUpdate = function () {
  26573. this._init();
  26574. if (this.parent) {
  26575. this.parent.forceUpdate();
  26576. }
  26577. };
  26578. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  26579. /*public get mesh(): AbstractMesh {
  26580. return this._mesh;
  26581. }*/
  26582. /**
  26583. * Gets the body that holds this impostor. Either its own, or its parent.
  26584. */
  26585. get: function () {
  26586. return this._parent ? this._parent.physicsBody : this._physicsBody;
  26587. },
  26588. /**
  26589. * Set the physics body. Used mainly by the physics engine/plugin
  26590. */
  26591. set: function (physicsBody) {
  26592. if (this._physicsBody) {
  26593. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  26594. }
  26595. this._physicsBody = physicsBody;
  26596. this.resetUpdateFlags();
  26597. },
  26598. enumerable: true,
  26599. configurable: true
  26600. });
  26601. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  26602. get: function () {
  26603. return this._parent;
  26604. },
  26605. enumerable: true,
  26606. configurable: true
  26607. });
  26608. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  26609. this._bodyUpdateRequired = false;
  26610. };
  26611. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  26612. if (this.object.getBoundingInfo) {
  26613. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  26614. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  26615. }
  26616. else {
  26617. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  26618. }
  26619. };
  26620. PhysicsImpostor.prototype.getObjectCenter = function () {
  26621. if (this.object.getBoundingInfo) {
  26622. return this.object.getBoundingInfo().boundingBox.center;
  26623. }
  26624. else {
  26625. return this.object.position;
  26626. }
  26627. };
  26628. /**
  26629. * Get a specific parametes from the options parameter.
  26630. */
  26631. PhysicsImpostor.prototype.getParam = function (paramName) {
  26632. return this._options[paramName];
  26633. };
  26634. /**
  26635. * Sets a specific parameter in the options given to the physics plugin
  26636. */
  26637. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  26638. this._options[paramName] = value;
  26639. this._bodyUpdateRequired = true;
  26640. };
  26641. /**
  26642. * Specifically change the body's mass option. Won't recreate the physics body object
  26643. */
  26644. PhysicsImpostor.prototype.setMass = function (mass) {
  26645. if (this.getParam("mass") !== mass) {
  26646. this.setParam("mass", mass);
  26647. }
  26648. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  26649. };
  26650. PhysicsImpostor.prototype.getLinearVelocity = function () {
  26651. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  26652. };
  26653. /**
  26654. * Set the body's linear velocity.
  26655. */
  26656. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  26657. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  26658. };
  26659. PhysicsImpostor.prototype.getAngularVelocity = function () {
  26660. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  26661. };
  26662. /**
  26663. * Set the body's linear velocity.
  26664. */
  26665. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  26666. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  26667. };
  26668. /**
  26669. * Execute a function with the physics plugin native code.
  26670. * Provide a function the will have two variables - the world object and the physics body object.
  26671. */
  26672. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  26673. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  26674. };
  26675. /**
  26676. * Register a function that will be executed before the physics world is stepping forward.
  26677. */
  26678. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  26679. this._onBeforePhysicsStepCallbacks.push(func);
  26680. };
  26681. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  26682. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  26683. if (index > -1) {
  26684. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  26685. }
  26686. else {
  26687. BABYLON.Tools.Warn("Function to remove was not found");
  26688. }
  26689. };
  26690. /**
  26691. * Register a function that will be executed after the physics step
  26692. */
  26693. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  26694. this._onAfterPhysicsStepCallbacks.push(func);
  26695. };
  26696. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  26697. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  26698. if (index > -1) {
  26699. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  26700. }
  26701. else {
  26702. BABYLON.Tools.Warn("Function to remove was not found");
  26703. }
  26704. };
  26705. /**
  26706. * register a function that will be executed when this impostor collides against a different body.
  26707. */
  26708. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  26709. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  26710. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  26711. };
  26712. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  26713. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  26714. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  26715. if (index > -1) {
  26716. this._onPhysicsCollideCallbacks.splice(index, 1);
  26717. }
  26718. else {
  26719. BABYLON.Tools.Warn("Function to remove was not found");
  26720. }
  26721. };
  26722. /**
  26723. * Apply a force
  26724. */
  26725. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  26726. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  26727. };
  26728. /**
  26729. * Apply an impulse
  26730. */
  26731. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  26732. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  26733. };
  26734. /**
  26735. * A help function to create a joint.
  26736. */
  26737. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  26738. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  26739. this.addJoint(otherImpostor, joint);
  26740. };
  26741. /**
  26742. * Add a joint to this impostor with a different impostor.
  26743. */
  26744. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  26745. this._joints.push({
  26746. otherImpostor: otherImpostor,
  26747. joint: joint
  26748. });
  26749. this._physicsEngine.addJoint(this, otherImpostor, joint);
  26750. };
  26751. /**
  26752. * Will keep this body still, in a sleep mode.
  26753. */
  26754. PhysicsImpostor.prototype.sleep = function () {
  26755. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  26756. };
  26757. /**
  26758. * Wake the body up.
  26759. */
  26760. PhysicsImpostor.prototype.wakeUp = function () {
  26761. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  26762. };
  26763. PhysicsImpostor.prototype.dispose = function () {
  26764. this.physicsBody = null;
  26765. if (this.parent) {
  26766. this.parent.forceUpdate();
  26767. }
  26768. else {
  26769. }
  26770. };
  26771. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  26772. this._deltaPosition.copyFrom(position);
  26773. };
  26774. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  26775. if (!this._deltaRotation) {
  26776. this._deltaRotation = new BABYLON.Quaternion();
  26777. }
  26778. this._deltaRotation.copyFrom(rotation);
  26779. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  26780. };
  26781. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  26782. //Impostor types
  26783. PhysicsImpostor.NoImpostor = 0;
  26784. PhysicsImpostor.SphereImpostor = 1;
  26785. PhysicsImpostor.BoxImpostor = 2;
  26786. PhysicsImpostor.PlaneImpostor = 3;
  26787. PhysicsImpostor.MeshImpostor = 4;
  26788. PhysicsImpostor.CylinderImpostor = 7;
  26789. PhysicsImpostor.ParticleImpostor = 8;
  26790. PhysicsImpostor.HeightmapImpostor = 9;
  26791. return PhysicsImpostor;
  26792. })();
  26793. BABYLON.PhysicsImpostor = PhysicsImpostor;
  26794. })(BABYLON || (BABYLON = {}));
  26795. var BABYLON;
  26796. (function (BABYLON) {
  26797. var PhysicsEngine = (function () {
  26798. function PhysicsEngine(gravity, _physicsPlugin) {
  26799. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  26800. this._physicsPlugin = _physicsPlugin;
  26801. //new methods and parameters
  26802. this._impostors = [];
  26803. this._joints = [];
  26804. if (!this._physicsPlugin.isSupported()) {
  26805. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  26806. + "Please make sure it is included.");
  26807. }
  26808. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  26809. this.setGravity(gravity);
  26810. this.setTimeStep();
  26811. }
  26812. PhysicsEngine.prototype.setGravity = function (gravity) {
  26813. this.gravity = gravity;
  26814. this._physicsPlugin.setGravity(this.gravity);
  26815. };
  26816. /**
  26817. * Set the time step of the physics engine.
  26818. * default is 1/60.
  26819. * To slow it down, enter 1/600 for example.
  26820. * To speed it up, 1/30
  26821. * @param {number} newTimeStep the new timestep to apply to this world.
  26822. */
  26823. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  26824. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  26825. this._physicsPlugin.setTimeStep(newTimeStep);
  26826. };
  26827. PhysicsEngine.prototype.dispose = function () {
  26828. this._impostors.forEach(function (impostor) {
  26829. impostor.dispose();
  26830. });
  26831. this._physicsPlugin.dispose();
  26832. };
  26833. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  26834. return this._physicsPlugin.name;
  26835. };
  26836. /**
  26837. * Adding a new impostor for the impostor tracking.
  26838. * This will be done by the impostor itself.
  26839. * @param {PhysicsImpostor} impostor the impostor to add
  26840. */
  26841. PhysicsEngine.prototype.addImpostor = function (impostor) {
  26842. impostor.uniqueId = this._impostors.push(impostor);
  26843. //if no parent, generate the body
  26844. if (!impostor.parent) {
  26845. this._physicsPlugin.generatePhysicsBody(impostor);
  26846. }
  26847. };
  26848. /**
  26849. * Remove an impostor from the engine.
  26850. * This impostor and its mesh will not longer be updated by the physics engine.
  26851. * @param {PhysicsImpostor} impostor the impostor to remove
  26852. */
  26853. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  26854. var index = this._impostors.indexOf(impostor);
  26855. if (index > -1) {
  26856. var removed = this._impostors.splice(index, 1);
  26857. //Is it needed?
  26858. if (removed.length) {
  26859. //this will also remove it from the world.
  26860. removed[0].physicsBody = null;
  26861. }
  26862. }
  26863. };
  26864. /**
  26865. * Add a joint to the physics engine
  26866. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  26867. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  26868. * @param {PhysicsJoint} the joint that will connect both impostors.
  26869. */
  26870. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  26871. var impostorJoint = {
  26872. mainImpostor: mainImpostor,
  26873. connectedImpostor: connectedImpostor,
  26874. joint: joint
  26875. };
  26876. joint.physicsPlugin = this._physicsPlugin;
  26877. this._joints.push(impostorJoint);
  26878. this._physicsPlugin.generateJoint(impostorJoint);
  26879. };
  26880. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  26881. var matchingJoints = this._joints.filter(function (impostorJoint) {
  26882. return (impostorJoint.connectedImpostor === connectedImpostor
  26883. && impostorJoint.joint === joint
  26884. && impostorJoint.mainImpostor === mainImpostor);
  26885. });
  26886. if (matchingJoints.length) {
  26887. this._physicsPlugin.removeJoint(matchingJoints[0]);
  26888. }
  26889. };
  26890. /**
  26891. * Called by the scene. no need to call it.
  26892. */
  26893. PhysicsEngine.prototype._step = function (delta) {
  26894. var _this = this;
  26895. //check if any mesh has no body / requires an update
  26896. this._impostors.forEach(function (impostor) {
  26897. if (impostor.isBodyInitRequired()) {
  26898. _this._physicsPlugin.generatePhysicsBody(impostor);
  26899. }
  26900. });
  26901. if (delta > 0.1) {
  26902. delta = 0.1;
  26903. }
  26904. else if (delta <= 0) {
  26905. delta = 1.0 / 60.0;
  26906. }
  26907. this._physicsPlugin.executeStep(delta, this._impostors);
  26908. };
  26909. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  26910. return this._physicsPlugin;
  26911. };
  26912. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  26913. for (var i = 0; i < this._impostors.length; ++i) {
  26914. if (this._impostors[i].object === object) {
  26915. return this._impostors[i];
  26916. }
  26917. }
  26918. };
  26919. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  26920. for (var i = 0; i < this._impostors.length; ++i) {
  26921. if (this._impostors[i].physicsBody === body) {
  26922. return this._impostors[i];
  26923. }
  26924. }
  26925. };
  26926. // Statics, Legacy support.
  26927. /**
  26928. * @Deprecated
  26929. *
  26930. */
  26931. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  26932. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  26933. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  26934. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  26935. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  26936. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  26937. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  26938. PhysicsEngine.CapsuleImpostor = -1;
  26939. PhysicsEngine.ConeImpostor = -1;
  26940. PhysicsEngine.ConvexHullImpostor = -1;
  26941. PhysicsEngine.Epsilon = 0.001;
  26942. return PhysicsEngine;
  26943. })();
  26944. BABYLON.PhysicsEngine = PhysicsEngine;
  26945. })(BABYLON || (BABYLON = {}));
  26946. var BABYLON;
  26947. (function (BABYLON) {
  26948. var VertexData = (function () {
  26949. function VertexData() {
  26950. }
  26951. VertexData.prototype.set = function (data, kind) {
  26952. switch (kind) {
  26953. case BABYLON.VertexBuffer.PositionKind:
  26954. this.positions = data;
  26955. break;
  26956. case BABYLON.VertexBuffer.NormalKind:
  26957. this.normals = data;
  26958. break;
  26959. case BABYLON.VertexBuffer.UVKind:
  26960. this.uvs = data;
  26961. break;
  26962. case BABYLON.VertexBuffer.UV2Kind:
  26963. this.uvs2 = data;
  26964. break;
  26965. case BABYLON.VertexBuffer.UV3Kind:
  26966. this.uvs3 = data;
  26967. break;
  26968. case BABYLON.VertexBuffer.UV4Kind:
  26969. this.uvs4 = data;
  26970. break;
  26971. case BABYLON.VertexBuffer.UV5Kind:
  26972. this.uvs5 = data;
  26973. break;
  26974. case BABYLON.VertexBuffer.UV6Kind:
  26975. this.uvs6 = data;
  26976. break;
  26977. case BABYLON.VertexBuffer.ColorKind:
  26978. this.colors = data;
  26979. break;
  26980. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26981. this.matricesIndices = data;
  26982. break;
  26983. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26984. this.matricesWeights = data;
  26985. break;
  26986. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26987. this.matricesIndicesExtra = data;
  26988. break;
  26989. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26990. this.matricesWeightsExtra = data;
  26991. break;
  26992. }
  26993. };
  26994. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26995. this._applyTo(mesh, updatable);
  26996. };
  26997. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26998. this._applyTo(geometry, updatable);
  26999. };
  27000. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27001. this._update(mesh);
  27002. };
  27003. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27004. this._update(geometry);
  27005. };
  27006. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27007. if (this.positions) {
  27008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27009. }
  27010. if (this.normals) {
  27011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27012. }
  27013. if (this.uvs) {
  27014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27015. }
  27016. if (this.uvs2) {
  27017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27018. }
  27019. if (this.uvs3) {
  27020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27021. }
  27022. if (this.uvs4) {
  27023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27024. }
  27025. if (this.uvs5) {
  27026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27027. }
  27028. if (this.uvs6) {
  27029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27030. }
  27031. if (this.colors) {
  27032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27033. }
  27034. if (this.matricesIndices) {
  27035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27036. }
  27037. if (this.matricesWeights) {
  27038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27039. }
  27040. if (this.matricesIndicesExtra) {
  27041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27042. }
  27043. if (this.matricesWeightsExtra) {
  27044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27045. }
  27046. if (this.indices) {
  27047. meshOrGeometry.setIndices(this.indices);
  27048. }
  27049. };
  27050. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27051. if (this.positions) {
  27052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27053. }
  27054. if (this.normals) {
  27055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27056. }
  27057. if (this.uvs) {
  27058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27059. }
  27060. if (this.uvs2) {
  27061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27062. }
  27063. if (this.uvs3) {
  27064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27065. }
  27066. if (this.uvs4) {
  27067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27068. }
  27069. if (this.uvs5) {
  27070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27071. }
  27072. if (this.uvs6) {
  27073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27074. }
  27075. if (this.colors) {
  27076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27077. }
  27078. if (this.matricesIndices) {
  27079. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27080. }
  27081. if (this.matricesWeights) {
  27082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27083. }
  27084. if (this.matricesIndicesExtra) {
  27085. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27086. }
  27087. if (this.matricesWeightsExtra) {
  27088. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27089. }
  27090. if (this.indices) {
  27091. meshOrGeometry.setIndices(this.indices);
  27092. }
  27093. };
  27094. VertexData.prototype.transform = function (matrix) {
  27095. var transformed = BABYLON.Vector3.Zero();
  27096. var index;
  27097. if (this.positions) {
  27098. var position = BABYLON.Vector3.Zero();
  27099. for (index = 0; index < this.positions.length; index += 3) {
  27100. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27101. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27102. this.positions[index] = transformed.x;
  27103. this.positions[index + 1] = transformed.y;
  27104. this.positions[index + 2] = transformed.z;
  27105. }
  27106. }
  27107. if (this.normals) {
  27108. var normal = BABYLON.Vector3.Zero();
  27109. for (index = 0; index < this.normals.length; index += 3) {
  27110. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27111. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27112. this.normals[index] = transformed.x;
  27113. this.normals[index + 1] = transformed.y;
  27114. this.normals[index + 2] = transformed.z;
  27115. }
  27116. }
  27117. };
  27118. VertexData.prototype.merge = function (other) {
  27119. if (other.indices) {
  27120. if (!this.indices) {
  27121. this.indices = [];
  27122. }
  27123. var offset = this.positions ? this.positions.length / 3 : 0;
  27124. for (var index = 0; index < other.indices.length; index++) {
  27125. //TODO check type - if Int32Array!
  27126. this.indices.push(other.indices[index] + offset);
  27127. }
  27128. }
  27129. this.positions = this._mergeElement(this.positions, other.positions);
  27130. this.normals = this._mergeElement(this.normals, other.normals);
  27131. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27132. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27133. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27134. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27135. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27136. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27137. this.colors = this._mergeElement(this.colors, other.colors);
  27138. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27139. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27140. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27141. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27142. };
  27143. VertexData.prototype._mergeElement = function (source, other) {
  27144. if (!other)
  27145. return source;
  27146. if (!source)
  27147. return other;
  27148. var len = other.length + source.length;
  27149. var isSrcTypedArray = source instanceof Float32Array;
  27150. var isOthTypedArray = other instanceof Float32Array;
  27151. // use non-loop method when the source is Float32Array
  27152. if (isSrcTypedArray) {
  27153. var ret32 = new Float32Array(len);
  27154. ret32.set(source);
  27155. ret32.set(other, source.length);
  27156. return ret32;
  27157. }
  27158. else if (!isOthTypedArray) {
  27159. return source.concat(other);
  27160. }
  27161. else {
  27162. var ret = source.slice(0); // copy source to a separate array
  27163. for (var i = 0, len = other.length; i < len; i++) {
  27164. ret.push(other[i]);
  27165. }
  27166. return ret;
  27167. }
  27168. };
  27169. VertexData.prototype.serialize = function () {
  27170. var serializationObject = this.serialize();
  27171. if (this.positions) {
  27172. serializationObject.positions = this.positions;
  27173. }
  27174. if (this.normals) {
  27175. serializationObject.normals = this.normals;
  27176. }
  27177. if (this.uvs) {
  27178. serializationObject.uvs = this.uvs;
  27179. }
  27180. if (this.uvs2) {
  27181. serializationObject.uvs2 = this.uvs2;
  27182. }
  27183. if (this.uvs3) {
  27184. serializationObject.uvs3 = this.uvs3;
  27185. }
  27186. if (this.uvs4) {
  27187. serializationObject.uvs4 = this.uvs4;
  27188. }
  27189. if (this.uvs5) {
  27190. serializationObject.uvs5 = this.uvs5;
  27191. }
  27192. if (this.uvs6) {
  27193. serializationObject.uvs6 = this.uvs6;
  27194. }
  27195. if (this.colors) {
  27196. serializationObject.colors = this.colors;
  27197. }
  27198. if (this.matricesIndices) {
  27199. serializationObject.matricesIndices = this.matricesIndices;
  27200. serializationObject.matricesIndices._isExpanded = true;
  27201. }
  27202. if (this.matricesWeights) {
  27203. serializationObject.matricesWeights = this.matricesWeights;
  27204. }
  27205. if (this.matricesIndicesExtra) {
  27206. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27207. serializationObject.matricesIndicesExtra._isExpanded = true;
  27208. }
  27209. if (this.matricesWeightsExtra) {
  27210. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27211. }
  27212. serializationObject.indices = this.indices;
  27213. return serializationObject;
  27214. };
  27215. // Statics
  27216. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27217. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27218. };
  27219. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27220. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27221. };
  27222. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27223. var result = new VertexData();
  27224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27225. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27226. }
  27227. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27228. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27229. }
  27230. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27231. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27232. }
  27233. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27234. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27235. }
  27236. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27237. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27238. }
  27239. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27240. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27241. }
  27242. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27243. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27244. }
  27245. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27246. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27247. }
  27248. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27249. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27250. }
  27251. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27252. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27253. }
  27254. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27255. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27256. }
  27257. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27258. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27259. }
  27260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27261. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27262. }
  27263. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27264. return result;
  27265. };
  27266. VertexData.CreateRibbon = function (options) {
  27267. var pathArray = options.pathArray;
  27268. var closeArray = options.closeArray || false;
  27269. var closePath = options.closePath || false;
  27270. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27271. var offset = options.offset || defaultOffset;
  27272. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27273. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27274. var positions = [];
  27275. var indices = [];
  27276. var normals = [];
  27277. var uvs = [];
  27278. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27279. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27280. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27281. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27282. var minlg; // minimal length among all paths from pathArray
  27283. var lg = []; // array of path lengths : nb of vertex per path
  27284. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27285. var p; // path iterator
  27286. var i; // point iterator
  27287. var j; // point iterator
  27288. // if single path in pathArray
  27289. if (pathArray.length < 2) {
  27290. var ar1 = [];
  27291. var ar2 = [];
  27292. for (i = 0; i < pathArray[0].length - offset; i++) {
  27293. ar1.push(pathArray[0][i]);
  27294. ar2.push(pathArray[0][i + offset]);
  27295. }
  27296. pathArray = [ar1, ar2];
  27297. }
  27298. // positions and horizontal distances (u)
  27299. var idc = 0;
  27300. var closePathCorr = (closePath) ? 1 : 0;
  27301. var path;
  27302. var l;
  27303. minlg = pathArray[0].length;
  27304. var vectlg;
  27305. var dist;
  27306. for (p = 0; p < pathArray.length; p++) {
  27307. uTotalDistance[p] = 0;
  27308. us[p] = [0];
  27309. path = pathArray[p];
  27310. l = path.length;
  27311. minlg = (minlg < l) ? minlg : l;
  27312. j = 0;
  27313. while (j < l) {
  27314. positions.push(path[j].x, path[j].y, path[j].z);
  27315. if (j > 0) {
  27316. vectlg = path[j].subtract(path[j - 1]).length();
  27317. dist = vectlg + uTotalDistance[p];
  27318. us[p].push(dist);
  27319. uTotalDistance[p] = dist;
  27320. }
  27321. j++;
  27322. }
  27323. if (closePath) {
  27324. j--;
  27325. positions.push(path[0].x, path[0].y, path[0].z);
  27326. vectlg = path[j].subtract(path[0]).length();
  27327. dist = vectlg + uTotalDistance[p];
  27328. us[p].push(dist);
  27329. uTotalDistance[p] = dist;
  27330. }
  27331. lg[p] = l + closePathCorr;
  27332. idx[p] = idc;
  27333. idc += (l + closePathCorr);
  27334. }
  27335. // vertical distances (v)
  27336. var path1;
  27337. var path2;
  27338. var vertex1;
  27339. var vertex2;
  27340. for (i = 0; i < minlg + closePathCorr; i++) {
  27341. vTotalDistance[i] = 0;
  27342. vs[i] = [0];
  27343. for (p = 0; p < pathArray.length - 1; p++) {
  27344. path1 = pathArray[p];
  27345. path2 = pathArray[p + 1];
  27346. if (i === minlg) {
  27347. vertex1 = path1[0];
  27348. vertex2 = path2[0];
  27349. }
  27350. else {
  27351. vertex1 = path1[i];
  27352. vertex2 = path2[i];
  27353. }
  27354. vectlg = vertex2.subtract(vertex1).length();
  27355. dist = vectlg + vTotalDistance[i];
  27356. vs[i].push(dist);
  27357. vTotalDistance[i] = dist;
  27358. }
  27359. if (closeArray) {
  27360. path1 = pathArray[p];
  27361. path2 = pathArray[0];
  27362. if (i === minlg) {
  27363. vertex2 = path2[0];
  27364. }
  27365. vectlg = vertex2.subtract(vertex1).length();
  27366. dist = vectlg + vTotalDistance[i];
  27367. vTotalDistance[i] = dist;
  27368. }
  27369. }
  27370. // uvs
  27371. var u;
  27372. var v;
  27373. for (p = 0; p < pathArray.length; p++) {
  27374. for (i = 0; i < minlg + closePathCorr; i++) {
  27375. u = us[p][i] / uTotalDistance[p];
  27376. v = vs[i][p] / vTotalDistance[i];
  27377. uvs.push(u, v);
  27378. }
  27379. }
  27380. // indices
  27381. p = 0; // path index
  27382. var pi = 0; // positions array index
  27383. var l1 = lg[p] - 1; // path1 length
  27384. var l2 = lg[p + 1] - 1; // path2 length
  27385. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27386. var shft = idx[1] - idx[0]; // shift
  27387. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27388. while (pi <= min && p < path1nb) {
  27389. // 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
  27390. indices.push(pi, pi + shft, pi + 1);
  27391. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27392. pi += 1;
  27393. if (pi === min) {
  27394. p++;
  27395. if (p === lg.length - 1) {
  27396. shft = idx[0] - idx[p];
  27397. l1 = lg[p] - 1;
  27398. l2 = lg[0] - 1;
  27399. }
  27400. else {
  27401. shft = idx[p + 1] - idx[p];
  27402. l1 = lg[p] - 1;
  27403. l2 = lg[p + 1] - 1;
  27404. }
  27405. pi = idx[p];
  27406. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27407. }
  27408. }
  27409. // normals
  27410. VertexData.ComputeNormals(positions, indices, normals);
  27411. if (closePath) {
  27412. var indexFirst = 0;
  27413. var indexLast = 0;
  27414. for (p = 0; p < pathArray.length; p++) {
  27415. indexFirst = idx[p] * 3;
  27416. if (p + 1 < pathArray.length) {
  27417. indexLast = (idx[p + 1] - 1) * 3;
  27418. }
  27419. else {
  27420. indexLast = normals.length - 3;
  27421. }
  27422. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27423. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27424. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27425. normals[indexLast] = normals[indexFirst];
  27426. normals[indexLast + 1] = normals[indexFirst + 1];
  27427. normals[indexLast + 2] = normals[indexFirst + 2];
  27428. }
  27429. }
  27430. // sides
  27431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27432. // Result
  27433. var vertexData = new VertexData();
  27434. vertexData.indices = indices;
  27435. vertexData.positions = positions;
  27436. vertexData.normals = normals;
  27437. vertexData.uvs = uvs;
  27438. if (closePath) {
  27439. vertexData._idx = idx;
  27440. }
  27441. return vertexData;
  27442. };
  27443. VertexData.CreateBox = function (options) {
  27444. var normalsSource = [
  27445. new BABYLON.Vector3(0, 0, 1),
  27446. new BABYLON.Vector3(0, 0, -1),
  27447. new BABYLON.Vector3(1, 0, 0),
  27448. new BABYLON.Vector3(-1, 0, 0),
  27449. new BABYLON.Vector3(0, 1, 0),
  27450. new BABYLON.Vector3(0, -1, 0)
  27451. ];
  27452. var indices = [];
  27453. var positions = [];
  27454. var normals = [];
  27455. var uvs = [];
  27456. var width = options.width || options.size || 1;
  27457. var height = options.height || options.size || 1;
  27458. var depth = options.depth || options.size || 1;
  27459. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27460. var faceUV = options.faceUV || new Array(6);
  27461. var faceColors = options.faceColors;
  27462. var colors = [];
  27463. // default face colors and UV if undefined
  27464. for (var f = 0; f < 6; f++) {
  27465. if (faceUV[f] === undefined) {
  27466. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27467. }
  27468. if (faceColors && faceColors[f] === undefined) {
  27469. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27470. }
  27471. }
  27472. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27473. // Create each face in turn.
  27474. for (var index = 0; index < normalsSource.length; index++) {
  27475. var normal = normalsSource[index];
  27476. // Get two vectors perpendicular to the face normal and to each other.
  27477. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27478. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27479. // Six indices (two triangles) per face.
  27480. var verticesLength = positions.length / 3;
  27481. indices.push(verticesLength);
  27482. indices.push(verticesLength + 1);
  27483. indices.push(verticesLength + 2);
  27484. indices.push(verticesLength);
  27485. indices.push(verticesLength + 2);
  27486. indices.push(verticesLength + 3);
  27487. // Four vertices per face.
  27488. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27489. positions.push(vertex.x, vertex.y, vertex.z);
  27490. normals.push(normal.x, normal.y, normal.z);
  27491. uvs.push(faceUV[index].z, faceUV[index].w);
  27492. if (faceColors) {
  27493. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27494. }
  27495. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27496. positions.push(vertex.x, vertex.y, vertex.z);
  27497. normals.push(normal.x, normal.y, normal.z);
  27498. uvs.push(faceUV[index].x, faceUV[index].w);
  27499. if (faceColors) {
  27500. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27501. }
  27502. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27503. positions.push(vertex.x, vertex.y, vertex.z);
  27504. normals.push(normal.x, normal.y, normal.z);
  27505. uvs.push(faceUV[index].x, faceUV[index].y);
  27506. if (faceColors) {
  27507. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27508. }
  27509. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27510. positions.push(vertex.x, vertex.y, vertex.z);
  27511. normals.push(normal.x, normal.y, normal.z);
  27512. uvs.push(faceUV[index].z, faceUV[index].y);
  27513. if (faceColors) {
  27514. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27515. }
  27516. }
  27517. // sides
  27518. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27519. // Result
  27520. var vertexData = new VertexData();
  27521. vertexData.indices = indices;
  27522. vertexData.positions = positions;
  27523. vertexData.normals = normals;
  27524. vertexData.uvs = uvs;
  27525. if (faceColors) {
  27526. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27527. vertexData.colors = totalColors;
  27528. }
  27529. return vertexData;
  27530. };
  27531. VertexData.CreateSphere = function (options) {
  27532. var segments = options.segments || 32;
  27533. var diameterX = options.diameterX || options.diameter || 1;
  27534. var diameterY = options.diameterY || options.diameter || 1;
  27535. var diameterZ = options.diameterZ || options.diameter || 1;
  27536. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27537. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27538. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27539. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27540. var totalZRotationSteps = 2 + segments;
  27541. var totalYRotationSteps = 2 * totalZRotationSteps;
  27542. var indices = [];
  27543. var positions = [];
  27544. var normals = [];
  27545. var uvs = [];
  27546. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27547. var normalizedZ = zRotationStep / totalZRotationSteps;
  27548. var angleZ = normalizedZ * Math.PI * slice;
  27549. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27550. var normalizedY = yRotationStep / totalYRotationSteps;
  27551. var angleY = normalizedY * Math.PI * 2 * arc;
  27552. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27553. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27554. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27555. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27556. var vertex = complete.multiply(radius);
  27557. var normal = complete.divide(radius).normalize();
  27558. positions.push(vertex.x, vertex.y, vertex.z);
  27559. normals.push(normal.x, normal.y, normal.z);
  27560. uvs.push(normalizedY, normalizedZ);
  27561. }
  27562. if (zRotationStep > 0) {
  27563. var verticesCount = positions.length / 3;
  27564. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27565. indices.push((firstIndex));
  27566. indices.push((firstIndex + 1));
  27567. indices.push(firstIndex + totalYRotationSteps + 1);
  27568. indices.push((firstIndex + totalYRotationSteps + 1));
  27569. indices.push((firstIndex + 1));
  27570. indices.push((firstIndex + totalYRotationSteps + 2));
  27571. }
  27572. }
  27573. }
  27574. // Sides
  27575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27576. // Result
  27577. var vertexData = new VertexData();
  27578. vertexData.indices = indices;
  27579. vertexData.positions = positions;
  27580. vertexData.normals = normals;
  27581. vertexData.uvs = uvs;
  27582. return vertexData;
  27583. };
  27584. // Cylinder and cone
  27585. VertexData.CreateCylinder = function (options) {
  27586. var height = options.height || 2;
  27587. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27588. var diameterBottom = options.diameterBottom || options.diameter || 1;
  27589. var tessellation = options.tessellation || 24;
  27590. var subdivisions = options.subdivisions || 1;
  27591. var hasRings = options.hasRings;
  27592. var enclose = options.enclose;
  27593. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27594. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27595. var faceUV = options.faceUV || new Array(3);
  27596. var faceColors = options.faceColors;
  27597. // default face colors and UV if undefined
  27598. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27599. var ringNb = (hasRings) ? subdivisions : 1;
  27600. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27601. var f;
  27602. for (f = 0; f < surfaceNb; f++) {
  27603. if (faceColors && faceColors[f] === undefined) {
  27604. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27605. }
  27606. }
  27607. for (f = 0; f < surfaceNb; f++) {
  27608. if (faceUV && faceUV[f] === undefined) {
  27609. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27610. }
  27611. }
  27612. var indices = [];
  27613. var positions = [];
  27614. var normals = [];
  27615. var uvs = [];
  27616. var colors = [];
  27617. var angle_step = Math.PI * 2 * arc / tessellation;
  27618. var angle;
  27619. var h;
  27620. var radius;
  27621. var tan = (diameterBottom - diameterTop) / 2 / height;
  27622. var ringVertex = BABYLON.Vector3.Zero();
  27623. var ringNormal = BABYLON.Vector3.Zero();
  27624. var ringFirstVertex = BABYLON.Vector3.Zero();
  27625. var ringFirstNormal = BABYLON.Vector3.Zero();
  27626. var quadNormal = BABYLON.Vector3.Zero();
  27627. var Y = BABYLON.Axis.Y;
  27628. // positions, normals, uvs
  27629. var i;
  27630. var j;
  27631. var r;
  27632. var ringIdx = 1;
  27633. var s = 1; // surface index
  27634. var cs = 0;
  27635. var v = 0;
  27636. for (i = 0; i <= subdivisions; i++) {
  27637. h = i / subdivisions;
  27638. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27639. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27640. for (r = 0; r < ringIdx; r++) {
  27641. if (hasRings) {
  27642. s += r;
  27643. }
  27644. if (enclose) {
  27645. s += 2 * r;
  27646. }
  27647. for (j = 0; j <= tessellation; j++) {
  27648. angle = j * angle_step;
  27649. // position
  27650. ringVertex.x = Math.cos(-angle) * radius;
  27651. ringVertex.y = -height / 2 + h * height;
  27652. ringVertex.z = Math.sin(-angle) * radius;
  27653. // normal
  27654. if (diameterTop === 0 && i === subdivisions) {
  27655. // if no top cap, reuse former normals
  27656. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27657. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27658. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27659. }
  27660. else {
  27661. ringNormal.x = ringVertex.x;
  27662. ringNormal.z = ringVertex.z;
  27663. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27664. ringNormal.normalize();
  27665. }
  27666. // keep first ring vertex values for enclose
  27667. if (j === 0) {
  27668. ringFirstVertex.copyFrom(ringVertex);
  27669. ringFirstNormal.copyFrom(ringNormal);
  27670. }
  27671. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27672. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27673. if (hasRings) {
  27674. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27675. }
  27676. else {
  27677. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27678. }
  27679. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27680. if (faceColors) {
  27681. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27682. }
  27683. }
  27684. // if enclose, add four vertices and their dedicated normals
  27685. if (arc !== 1 && enclose) {
  27686. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27687. positions.push(0, ringVertex.y, 0);
  27688. positions.push(0, ringVertex.y, 0);
  27689. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27690. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27691. quadNormal.normalize();
  27692. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27693. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27694. quadNormal.normalize();
  27695. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27696. if (hasRings) {
  27697. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27698. }
  27699. else {
  27700. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27701. }
  27702. uvs.push(faceUV[s + 1].x, v);
  27703. uvs.push(faceUV[s + 1].z, v);
  27704. if (hasRings) {
  27705. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27706. }
  27707. else {
  27708. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27709. }
  27710. uvs.push(faceUV[s + 2].x, v);
  27711. uvs.push(faceUV[s + 2].z, v);
  27712. if (faceColors) {
  27713. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27714. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27715. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27716. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27717. }
  27718. }
  27719. if (cs !== s) {
  27720. cs = s;
  27721. }
  27722. }
  27723. }
  27724. // indices
  27725. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27726. var s;
  27727. i = 0;
  27728. for (s = 0; s < subdivisions; s++) {
  27729. for (j = 0; j < tessellation; j++) {
  27730. var i0 = i * (e + 1) + j;
  27731. var i1 = (i + 1) * (e + 1) + j;
  27732. var i2 = i * (e + 1) + (j + 1);
  27733. var i3 = (i + 1) * (e + 1) + (j + 1);
  27734. indices.push(i0, i1, i2);
  27735. indices.push(i3, i2, i1);
  27736. }
  27737. if (arc !== 1 && enclose) {
  27738. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27739. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27740. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27741. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27742. }
  27743. i = (hasRings) ? (i + 2) : (i + 1);
  27744. }
  27745. // Caps
  27746. var createCylinderCap = function (isTop) {
  27747. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27748. if (radius === 0) {
  27749. return;
  27750. }
  27751. // Cap positions, normals & uvs
  27752. var angle;
  27753. var circleVector;
  27754. var i;
  27755. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27756. var c;
  27757. if (faceColors) {
  27758. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27759. }
  27760. // cap center
  27761. var vbase = positions.length / 3;
  27762. var offset = isTop ? height / 2 : -height / 2;
  27763. var center = new BABYLON.Vector3(0, offset, 0);
  27764. positions.push(center.x, center.y, center.z);
  27765. normals.push(0, isTop ? 1 : -1, 0);
  27766. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27767. if (faceColors) {
  27768. colors.push(c.r, c.g, c.b, c.a);
  27769. }
  27770. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27771. for (i = 0; i <= tessellation; i++) {
  27772. angle = Math.PI * 2 * i * arc / tessellation;
  27773. var cos = Math.cos(-angle);
  27774. var sin = Math.sin(-angle);
  27775. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27776. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27777. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27778. normals.push(0, isTop ? 1 : -1, 0);
  27779. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27780. if (faceColors) {
  27781. colors.push(c.r, c.g, c.b, c.a);
  27782. }
  27783. }
  27784. // Cap indices
  27785. for (i = 0; i < tessellation; i++) {
  27786. if (!isTop) {
  27787. indices.push(vbase);
  27788. indices.push(vbase + (i + 1));
  27789. indices.push(vbase + (i + 2));
  27790. }
  27791. else {
  27792. indices.push(vbase);
  27793. indices.push(vbase + (i + 2));
  27794. indices.push(vbase + (i + 1));
  27795. }
  27796. }
  27797. };
  27798. // add caps to geometry
  27799. createCylinderCap(false);
  27800. createCylinderCap(true);
  27801. // Sides
  27802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27803. var vertexData = new VertexData();
  27804. vertexData.indices = indices;
  27805. vertexData.positions = positions;
  27806. vertexData.normals = normals;
  27807. vertexData.uvs = uvs;
  27808. if (faceColors) {
  27809. vertexData.colors = colors;
  27810. }
  27811. return vertexData;
  27812. };
  27813. VertexData.CreateTorus = function (options) {
  27814. var indices = [];
  27815. var positions = [];
  27816. var normals = [];
  27817. var uvs = [];
  27818. var diameter = options.diameter || 1;
  27819. var thickness = options.thickness || 0.5;
  27820. var tessellation = options.tessellation || 16;
  27821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27822. var stride = tessellation + 1;
  27823. for (var i = 0; i <= tessellation; i++) {
  27824. var u = i / tessellation;
  27825. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27826. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27827. for (var j = 0; j <= tessellation; j++) {
  27828. var v = 1 - j / tessellation;
  27829. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27830. var dx = Math.cos(innerAngle);
  27831. var dy = Math.sin(innerAngle);
  27832. // Create a vertex.
  27833. var normal = new BABYLON.Vector3(dx, dy, 0);
  27834. var position = normal.scale(thickness / 2);
  27835. var textureCoordinate = new BABYLON.Vector2(u, v);
  27836. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27837. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27838. positions.push(position.x, position.y, position.z);
  27839. normals.push(normal.x, normal.y, normal.z);
  27840. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27841. // And create indices for two triangles.
  27842. var nextI = (i + 1) % stride;
  27843. var nextJ = (j + 1) % stride;
  27844. indices.push(i * stride + j);
  27845. indices.push(i * stride + nextJ);
  27846. indices.push(nextI * stride + j);
  27847. indices.push(i * stride + nextJ);
  27848. indices.push(nextI * stride + nextJ);
  27849. indices.push(nextI * stride + j);
  27850. }
  27851. }
  27852. // Sides
  27853. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27854. // Result
  27855. var vertexData = new VertexData();
  27856. vertexData.indices = indices;
  27857. vertexData.positions = positions;
  27858. vertexData.normals = normals;
  27859. vertexData.uvs = uvs;
  27860. return vertexData;
  27861. };
  27862. VertexData.CreateLineSystem = function (options) {
  27863. var indices = [];
  27864. var positions = [];
  27865. var lines = options.lines;
  27866. var idx = 0;
  27867. for (var l = 0; l < lines.length; l++) {
  27868. var points = lines[l];
  27869. for (var index = 0; index < points.length; index++) {
  27870. positions.push(points[index].x, points[index].y, points[index].z);
  27871. if (index > 0) {
  27872. indices.push(idx - 1);
  27873. indices.push(idx);
  27874. }
  27875. idx++;
  27876. }
  27877. }
  27878. var vertexData = new VertexData();
  27879. vertexData.indices = indices;
  27880. vertexData.positions = positions;
  27881. return vertexData;
  27882. };
  27883. VertexData.CreateDashedLines = function (options) {
  27884. var dashSize = options.dashSize || 3;
  27885. var gapSize = options.gapSize || 1;
  27886. var dashNb = options.dashNb || 200;
  27887. var points = options.points;
  27888. var positions = new Array();
  27889. var indices = new Array();
  27890. var curvect = BABYLON.Vector3.Zero();
  27891. var lg = 0;
  27892. var nb = 0;
  27893. var shft = 0;
  27894. var dashshft = 0;
  27895. var curshft = 0;
  27896. var idx = 0;
  27897. var i = 0;
  27898. for (i = 0; i < points.length - 1; i++) {
  27899. points[i + 1].subtractToRef(points[i], curvect);
  27900. lg += curvect.length();
  27901. }
  27902. shft = lg / dashNb;
  27903. dashshft = dashSize * shft / (dashSize + gapSize);
  27904. for (i = 0; i < points.length - 1; i++) {
  27905. points[i + 1].subtractToRef(points[i], curvect);
  27906. nb = Math.floor(curvect.length() / shft);
  27907. curvect.normalize();
  27908. for (var j = 0; j < nb; j++) {
  27909. curshft = shft * j;
  27910. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27911. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27912. indices.push(idx, idx + 1);
  27913. idx += 2;
  27914. }
  27915. }
  27916. // Result
  27917. var vertexData = new VertexData();
  27918. vertexData.positions = positions;
  27919. vertexData.indices = indices;
  27920. return vertexData;
  27921. };
  27922. VertexData.CreateGround = function (options) {
  27923. var indices = [];
  27924. var positions = [];
  27925. var normals = [];
  27926. var uvs = [];
  27927. var row, col;
  27928. var width = options.width || 1;
  27929. var height = options.height || 1;
  27930. var subdivisions = options.subdivisions || 1;
  27931. for (row = 0; row <= subdivisions; row++) {
  27932. for (col = 0; col <= subdivisions; col++) {
  27933. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27934. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27935. positions.push(position.x, position.y, position.z);
  27936. normals.push(normal.x, normal.y, normal.z);
  27937. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27938. }
  27939. }
  27940. for (row = 0; row < subdivisions; row++) {
  27941. for (col = 0; col < subdivisions; col++) {
  27942. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27943. indices.push(col + 1 + row * (subdivisions + 1));
  27944. indices.push(col + row * (subdivisions + 1));
  27945. indices.push(col + (row + 1) * (subdivisions + 1));
  27946. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27947. indices.push(col + row * (subdivisions + 1));
  27948. }
  27949. }
  27950. // Result
  27951. var vertexData = new VertexData();
  27952. vertexData.indices = indices;
  27953. vertexData.positions = positions;
  27954. vertexData.normals = normals;
  27955. vertexData.uvs = uvs;
  27956. return vertexData;
  27957. };
  27958. VertexData.CreateTiledGround = function (options) {
  27959. var xmin = options.xmin;
  27960. var zmin = options.zmin;
  27961. var xmax = options.xmax;
  27962. var zmax = options.zmax;
  27963. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27964. var precision = options.precision || { w: 1, h: 1 };
  27965. var indices = [];
  27966. var positions = [];
  27967. var normals = [];
  27968. var uvs = [];
  27969. var row, col, tileRow, tileCol;
  27970. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27971. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27972. precision.w = (precision.w < 1) ? 1 : precision.w;
  27973. precision.h = (precision.h < 1) ? 1 : precision.h;
  27974. var tileSize = {
  27975. 'w': (xmax - xmin) / subdivisions.w,
  27976. 'h': (zmax - zmin) / subdivisions.h
  27977. };
  27978. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27979. // Indices
  27980. var base = positions.length / 3;
  27981. var rowLength = precision.w + 1;
  27982. for (row = 0; row < precision.h; row++) {
  27983. for (col = 0; col < precision.w; col++) {
  27984. var square = [
  27985. base + col + row * rowLength,
  27986. base + (col + 1) + row * rowLength,
  27987. base + (col + 1) + (row + 1) * rowLength,
  27988. base + col + (row + 1) * rowLength
  27989. ];
  27990. indices.push(square[1]);
  27991. indices.push(square[2]);
  27992. indices.push(square[3]);
  27993. indices.push(square[0]);
  27994. indices.push(square[1]);
  27995. indices.push(square[3]);
  27996. }
  27997. }
  27998. // Position, normals and uvs
  27999. var position = BABYLON.Vector3.Zero();
  28000. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28001. for (row = 0; row <= precision.h; row++) {
  28002. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28003. for (col = 0; col <= precision.w; col++) {
  28004. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28005. position.y = 0;
  28006. positions.push(position.x, position.y, position.z);
  28007. normals.push(normal.x, normal.y, normal.z);
  28008. uvs.push(col / precision.w, row / precision.h);
  28009. }
  28010. }
  28011. }
  28012. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28013. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28014. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28015. }
  28016. }
  28017. // Result
  28018. var vertexData = new VertexData();
  28019. vertexData.indices = indices;
  28020. vertexData.positions = positions;
  28021. vertexData.normals = normals;
  28022. vertexData.uvs = uvs;
  28023. return vertexData;
  28024. };
  28025. VertexData.CreateGroundFromHeightMap = function (options) {
  28026. var indices = [];
  28027. var positions = [];
  28028. var normals = [];
  28029. var uvs = [];
  28030. var row, col;
  28031. // Vertices
  28032. for (row = 0; row <= options.subdivisions; row++) {
  28033. for (col = 0; col <= options.subdivisions; col++) {
  28034. 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));
  28035. // Compute height
  28036. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28037. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28038. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28039. var r = options.buffer[pos] / 255.0;
  28040. var g = options.buffer[pos + 1] / 255.0;
  28041. var b = options.buffer[pos + 2] / 255.0;
  28042. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28043. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28044. // Add vertex
  28045. positions.push(position.x, position.y, position.z);
  28046. normals.push(0, 0, 0);
  28047. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28048. }
  28049. }
  28050. // Indices
  28051. for (row = 0; row < options.subdivisions; row++) {
  28052. for (col = 0; col < options.subdivisions; col++) {
  28053. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28054. indices.push(col + 1 + row * (options.subdivisions + 1));
  28055. indices.push(col + row * (options.subdivisions + 1));
  28056. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28057. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28058. indices.push(col + row * (options.subdivisions + 1));
  28059. }
  28060. }
  28061. // Normals
  28062. VertexData.ComputeNormals(positions, indices, normals);
  28063. // Result
  28064. var vertexData = new VertexData();
  28065. vertexData.indices = indices;
  28066. vertexData.positions = positions;
  28067. vertexData.normals = normals;
  28068. vertexData.uvs = uvs;
  28069. return vertexData;
  28070. };
  28071. VertexData.CreatePlane = function (options) {
  28072. var indices = [];
  28073. var positions = [];
  28074. var normals = [];
  28075. var uvs = [];
  28076. var width = options.width || options.size || 1;
  28077. var height = options.height || options.size || 1;
  28078. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28079. // Vertices
  28080. var halfWidth = width / 2.0;
  28081. var halfHeight = height / 2.0;
  28082. positions.push(-halfWidth, -halfHeight, 0);
  28083. normals.push(0, 0, -1.0);
  28084. uvs.push(0.0, 0.0);
  28085. positions.push(halfWidth, -halfHeight, 0);
  28086. normals.push(0, 0, -1.0);
  28087. uvs.push(1.0, 0.0);
  28088. positions.push(halfWidth, halfHeight, 0);
  28089. normals.push(0, 0, -1.0);
  28090. uvs.push(1.0, 1.0);
  28091. positions.push(-halfWidth, halfHeight, 0);
  28092. normals.push(0, 0, -1.0);
  28093. uvs.push(0.0, 1.0);
  28094. // Indices
  28095. indices.push(0);
  28096. indices.push(1);
  28097. indices.push(2);
  28098. indices.push(0);
  28099. indices.push(2);
  28100. indices.push(3);
  28101. // Sides
  28102. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28103. // Result
  28104. var vertexData = new VertexData();
  28105. vertexData.indices = indices;
  28106. vertexData.positions = positions;
  28107. vertexData.normals = normals;
  28108. vertexData.uvs = uvs;
  28109. return vertexData;
  28110. };
  28111. VertexData.CreateDisc = function (options) {
  28112. var positions = [];
  28113. var indices = [];
  28114. var normals = [];
  28115. var uvs = [];
  28116. var radius = options.radius || 0.5;
  28117. var tessellation = options.tessellation || 64;
  28118. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28119. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28120. // positions and uvs
  28121. positions.push(0, 0, 0); // disc center first
  28122. uvs.push(0.5, 0.5);
  28123. var theta = Math.PI * 2 * arc;
  28124. var step = theta / tessellation;
  28125. for (var a = 0; a < theta; a += step) {
  28126. var x = Math.cos(a);
  28127. var y = Math.sin(a);
  28128. var u = (x + 1) / 2;
  28129. var v = (1 - y) / 2;
  28130. positions.push(radius * x, radius * y, 0);
  28131. uvs.push(u, v);
  28132. }
  28133. if (arc === 1) {
  28134. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28135. uvs.push(uvs[2], uvs[3]);
  28136. }
  28137. //indices
  28138. var vertexNb = positions.length / 3;
  28139. for (var i = 1; i < vertexNb - 1; i++) {
  28140. indices.push(i + 1, 0, i);
  28141. }
  28142. // result
  28143. VertexData.ComputeNormals(positions, indices, normals);
  28144. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28145. var vertexData = new VertexData();
  28146. vertexData.indices = indices;
  28147. vertexData.positions = positions;
  28148. vertexData.normals = normals;
  28149. vertexData.uvs = uvs;
  28150. return vertexData;
  28151. };
  28152. VertexData.CreateIcoSphere = function (options) {
  28153. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28154. var radius = options.radius || 1;
  28155. var flat = (options.flat === undefined) ? true : options.flat;
  28156. var subdivisions = options.subdivisions || 4;
  28157. var radiusX = options.radiusX || radius;
  28158. var radiusY = options.radiusY || radius;
  28159. var radiusZ = options.radiusZ || radius;
  28160. var t = (1 + Math.sqrt(5)) / 2;
  28161. // 12 vertex x,y,z
  28162. var ico_vertices = [
  28163. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28164. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28165. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28166. ];
  28167. // index of 3 vertex makes a face of icopshere
  28168. var ico_indices = [
  28169. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28170. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28171. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28172. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28173. ];
  28174. // vertex for uv have aliased position, not for UV
  28175. var vertices_unalias_id = [
  28176. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28177. // vertex alias
  28178. 0,
  28179. 2,
  28180. 3,
  28181. 3,
  28182. 3,
  28183. 4,
  28184. 7,
  28185. 8,
  28186. 9,
  28187. 9,
  28188. 10,
  28189. 11 // 23: B + 12
  28190. ];
  28191. // uv as integer step (not pixels !)
  28192. var ico_vertexuv = [
  28193. 5, 1, 3, 1, 6, 4, 0, 0,
  28194. 5, 3, 4, 2, 2, 2, 4, 0,
  28195. 2, 0, 1, 1, 6, 0, 6, 2,
  28196. // vertex alias (for same vertex on different faces)
  28197. 0, 4,
  28198. 3, 3,
  28199. 4, 4,
  28200. 3, 1,
  28201. 4, 2,
  28202. 4, 4,
  28203. 0, 2,
  28204. 1, 1,
  28205. 2, 2,
  28206. 3, 3,
  28207. 1, 3,
  28208. 2, 4 // 23: B + 12
  28209. ];
  28210. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28211. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28212. // First island of uv mapping
  28213. // v = 4h 3+ 2
  28214. // v = 3h 9+ 4
  28215. // v = 2h 9+ 5 B
  28216. // v = 1h 9 1 0
  28217. // v = 0h 3 8 7 A
  28218. // u = 0 1 2 3 4 5 6 *a
  28219. // Second island of uv mapping
  28220. // v = 4h 0+ B+ 4+
  28221. // v = 3h A+ 2+
  28222. // v = 2h 7+ 6 3+
  28223. // v = 1h 8+ 3+
  28224. // v = 0h
  28225. // u = 0 1 2 3 4 5 6 *a
  28226. // Face layout on texture UV mapping
  28227. // ============
  28228. // \ 4 /\ 16 / ======
  28229. // \ / \ / /\ 11 /
  28230. // \/ 7 \/ / \ /
  28231. // ======= / 10 \/
  28232. // /\ 17 /\ =======
  28233. // / \ / \ \ 15 /\
  28234. // / 8 \/ 12 \ \ / \
  28235. // ============ \/ 6 \
  28236. // \ 18 /\ ============
  28237. // \ / \ \ 5 /\ 0 /
  28238. // \/ 13 \ \ / \ /
  28239. // ======= \/ 1 \/
  28240. // =============
  28241. // /\ 19 /\ 2 /\
  28242. // / \ / \ / \
  28243. // / 14 \/ 9 \/ 3 \
  28244. // ===================
  28245. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28246. var ustep = 138 / 1024;
  28247. var vstep = 239 / 1024;
  28248. var uoffset = 60 / 1024;
  28249. var voffset = 26 / 1024;
  28250. // Second island should have margin, not to touch the first island
  28251. // avoid any borderline artefact in pixel rounding
  28252. var island_u_offset = -40 / 1024;
  28253. var island_v_offset = +20 / 1024;
  28254. // face is either island 0 or 1 :
  28255. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28256. var island = [
  28257. 0, 0, 0, 0, 1,
  28258. 0, 0, 1, 1, 0,
  28259. 0, 0, 1, 1, 0,
  28260. 0, 1, 1, 1, 0 // 15 - 19
  28261. ];
  28262. var indices = [];
  28263. var positions = [];
  28264. var normals = [];
  28265. var uvs = [];
  28266. var current_indice = 0;
  28267. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28268. var face_vertex_pos = new Array(3);
  28269. var face_vertex_uv = new Array(3);
  28270. var v012;
  28271. for (v012 = 0; v012 < 3; v012++) {
  28272. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28273. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28274. }
  28275. // create all with normals
  28276. for (var face = 0; face < 20; face++) {
  28277. // 3 vertex per face
  28278. for (v012 = 0; v012 < 3; v012++) {
  28279. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28280. var v_id = ico_indices[3 * face + v012];
  28281. // vertex have 3D position (x,y,z)
  28282. 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]);
  28283. // Normalize to get normal, then scale to radius
  28284. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28285. // uv Coordinates from vertex ID
  28286. 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);
  28287. }
  28288. // Subdivide the face (interpolate pos, norm, uv)
  28289. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28290. // - norm is linear interpolation of vertex corner normal
  28291. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28292. // - uv is linear interpolation
  28293. //
  28294. // Topology is as below for sub-divide by 2
  28295. // vertex shown as v0,v1,v2
  28296. // interp index is i1 to progress in range [v0,v1[
  28297. // interp index is i2 to progress in range [v0,v2[
  28298. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28299. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28300. //
  28301. //
  28302. // i2 v2
  28303. // ^ ^
  28304. // / / \
  28305. // / / \
  28306. // / / \
  28307. // / / (0,1) \
  28308. // / #---------\
  28309. // / / \ (0,0)'/ \
  28310. // / / \ / \
  28311. // / / \ / \
  28312. // / / (0,0) \ / (1,0) \
  28313. // / #---------#---------\
  28314. // v0 v1
  28315. //
  28316. // --------------------> i1
  28317. //
  28318. // interp of (i1,i2):
  28319. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28320. // along i1 : lerp(x0,x1, i1/(S-i2))
  28321. //
  28322. // centroid of triangle is needed to get help normal computation
  28323. // (c1,c2) are used for centroid location
  28324. var interp_vertex = function (i1, i2, c1, c2) {
  28325. // vertex is interpolated from
  28326. // - face_vertex_pos[0..2]
  28327. // - face_vertex_uv[0..2]
  28328. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28329. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28330. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28331. pos_interp.normalize();
  28332. var vertex_normal;
  28333. if (flat) {
  28334. // in flat mode, recalculate normal as face centroid normal
  28335. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28336. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28337. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28338. }
  28339. else {
  28340. // in smooth mode, recalculate normal from each single vertex position
  28341. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28342. }
  28343. // Vertex normal need correction due to X,Y,Z radius scaling
  28344. vertex_normal.x /= radiusX;
  28345. vertex_normal.y /= radiusY;
  28346. vertex_normal.z /= radiusZ;
  28347. vertex_normal.normalize();
  28348. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28349. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28350. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28351. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28352. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28353. uvs.push(uv_interp.x, uv_interp.y);
  28354. // push each vertex has member of a face
  28355. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28356. indices.push(current_indice);
  28357. current_indice++;
  28358. };
  28359. for (var i2 = 0; i2 < subdivisions; i2++) {
  28360. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28361. // face : (i1,i2) for /\ :
  28362. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28363. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28364. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28365. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28366. if (i1 + i2 + 1 < subdivisions) {
  28367. // face : (i1,i2)' for \/ :
  28368. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28369. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28370. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28371. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28372. }
  28373. }
  28374. }
  28375. }
  28376. // Sides
  28377. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28378. // Result
  28379. var vertexData = new VertexData();
  28380. vertexData.indices = indices;
  28381. vertexData.positions = positions;
  28382. vertexData.normals = normals;
  28383. vertexData.uvs = uvs;
  28384. return vertexData;
  28385. };
  28386. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28387. VertexData.CreatePolyhedron = function (options) {
  28388. // provided polyhedron types :
  28389. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28390. // 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)
  28391. var polyhedra = [];
  28392. 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]] };
  28393. 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]] };
  28394. polyhedra[2] = {
  28395. 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]],
  28396. 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]]
  28397. };
  28398. polyhedra[3] = {
  28399. 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]],
  28400. 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]]
  28401. };
  28402. polyhedra[4] = {
  28403. 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]],
  28404. 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]]
  28405. };
  28406. 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]] };
  28407. 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]] };
  28408. 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]] };
  28409. 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]] };
  28410. 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]] };
  28411. 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]] };
  28412. 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]] };
  28413. 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]] };
  28414. 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]] };
  28415. polyhedra[14] = {
  28416. 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]],
  28417. 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]]
  28418. };
  28419. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28420. var size = options.size;
  28421. var sizeX = options.sizeX || size || 1;
  28422. var sizeY = options.sizeY || size || 1;
  28423. var sizeZ = options.sizeZ || size || 1;
  28424. var data = options.custom || polyhedra[type];
  28425. var nbfaces = data.face.length;
  28426. var faceUV = options.faceUV || new Array(nbfaces);
  28427. var faceColors = options.faceColors;
  28428. var flat = (options.flat === undefined) ? true : options.flat;
  28429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28430. var positions = [];
  28431. var indices = [];
  28432. var normals = [];
  28433. var uvs = [];
  28434. var colors = [];
  28435. var index = 0;
  28436. var faceIdx = 0; // face cursor in the array "indexes"
  28437. var indexes = [];
  28438. var i = 0;
  28439. var f = 0;
  28440. var u, v, ang, x, y, tmp;
  28441. // default face colors and UV if undefined
  28442. if (flat) {
  28443. for (f = 0; f < nbfaces; f++) {
  28444. if (faceColors && faceColors[f] === undefined) {
  28445. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28446. }
  28447. if (faceUV && faceUV[f] === undefined) {
  28448. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28449. }
  28450. }
  28451. }
  28452. if (!flat) {
  28453. for (i = 0; i < data.vertex.length; i++) {
  28454. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28455. uvs.push(0, 0);
  28456. }
  28457. for (f = 0; f < nbfaces; f++) {
  28458. for (i = 0; i < data.face[f].length - 2; i++) {
  28459. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28460. }
  28461. }
  28462. }
  28463. else {
  28464. for (f = 0; f < nbfaces; f++) {
  28465. var fl = data.face[f].length; // number of vertices of the current face
  28466. ang = 2 * Math.PI / fl;
  28467. x = 0.5 * Math.tan(ang / 2);
  28468. y = 0.5;
  28469. // positions, uvs, colors
  28470. for (i = 0; i < fl; i++) {
  28471. // positions
  28472. 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);
  28473. indexes.push(index);
  28474. index++;
  28475. // uvs
  28476. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28477. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28478. uvs.push(u, v);
  28479. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28480. y = x * Math.sin(ang) + y * Math.cos(ang);
  28481. x = tmp;
  28482. // colors
  28483. if (faceColors) {
  28484. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28485. }
  28486. }
  28487. // indices from indexes
  28488. for (i = 0; i < fl - 2; i++) {
  28489. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28490. }
  28491. faceIdx += fl;
  28492. }
  28493. }
  28494. VertexData.ComputeNormals(positions, indices, normals);
  28495. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28496. var vertexData = new VertexData();
  28497. vertexData.positions = positions;
  28498. vertexData.indices = indices;
  28499. vertexData.normals = normals;
  28500. vertexData.uvs = uvs;
  28501. if (faceColors && flat) {
  28502. vertexData.colors = colors;
  28503. }
  28504. return vertexData;
  28505. };
  28506. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28507. VertexData.CreateTorusKnot = function (options) {
  28508. var indices = [];
  28509. var positions = [];
  28510. var normals = [];
  28511. var uvs = [];
  28512. var radius = options.radius || 2;
  28513. var tube = options.tube || 0.5;
  28514. var radialSegments = options.radialSegments || 32;
  28515. var tubularSegments = options.tubularSegments || 32;
  28516. var p = options.p || 2;
  28517. var q = options.q || 3;
  28518. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28519. // Helper
  28520. var getPos = function (angle) {
  28521. var cu = Math.cos(angle);
  28522. var su = Math.sin(angle);
  28523. var quOverP = q / p * angle;
  28524. var cs = Math.cos(quOverP);
  28525. var tx = radius * (2 + cs) * 0.5 * cu;
  28526. var ty = radius * (2 + cs) * su * 0.5;
  28527. var tz = radius * Math.sin(quOverP) * 0.5;
  28528. return new BABYLON.Vector3(tx, ty, tz);
  28529. };
  28530. // Vertices
  28531. var i;
  28532. var j;
  28533. for (i = 0; i <= radialSegments; i++) {
  28534. var modI = i % radialSegments;
  28535. var u = modI / radialSegments * 2 * p * Math.PI;
  28536. var p1 = getPos(u);
  28537. var p2 = getPos(u + 0.01);
  28538. var tang = p2.subtract(p1);
  28539. var n = p2.add(p1);
  28540. var bitan = BABYLON.Vector3.Cross(tang, n);
  28541. n = BABYLON.Vector3.Cross(bitan, tang);
  28542. bitan.normalize();
  28543. n.normalize();
  28544. for (j = 0; j < tubularSegments; j++) {
  28545. var modJ = j % tubularSegments;
  28546. var v = modJ / tubularSegments * 2 * Math.PI;
  28547. var cx = -tube * Math.cos(v);
  28548. var cy = tube * Math.sin(v);
  28549. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28550. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28551. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28552. uvs.push(i / radialSegments);
  28553. uvs.push(j / tubularSegments);
  28554. }
  28555. }
  28556. for (i = 0; i < radialSegments; i++) {
  28557. for (j = 0; j < tubularSegments; j++) {
  28558. var jNext = (j + 1) % tubularSegments;
  28559. var a = i * tubularSegments + j;
  28560. var b = (i + 1) * tubularSegments + j;
  28561. var c = (i + 1) * tubularSegments + jNext;
  28562. var d = i * tubularSegments + jNext;
  28563. indices.push(d);
  28564. indices.push(b);
  28565. indices.push(a);
  28566. indices.push(d);
  28567. indices.push(c);
  28568. indices.push(b);
  28569. }
  28570. }
  28571. // Normals
  28572. VertexData.ComputeNormals(positions, indices, normals);
  28573. // Sides
  28574. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28575. // Result
  28576. var vertexData = new VertexData();
  28577. vertexData.indices = indices;
  28578. vertexData.positions = positions;
  28579. vertexData.normals = normals;
  28580. vertexData.uvs = uvs;
  28581. return vertexData;
  28582. };
  28583. // Tools
  28584. /**
  28585. * @param {any} - positions (number[] or Float32Array)
  28586. * @param {any} - indices (number[] or Uint16Array)
  28587. * @param {any} - normals (number[] or Float32Array)
  28588. */
  28589. VertexData.ComputeNormals = function (positions, indices, normals) {
  28590. var index = 0;
  28591. var p1p2x = 0.0;
  28592. var p1p2y = 0.0;
  28593. var p1p2z = 0.0;
  28594. var p3p2x = 0.0;
  28595. var p3p2y = 0.0;
  28596. var p3p2z = 0.0;
  28597. var faceNormalx = 0.0;
  28598. var faceNormaly = 0.0;
  28599. var faceNormalz = 0.0;
  28600. var length = 0.0;
  28601. var i1 = 0;
  28602. var i2 = 0;
  28603. var i3 = 0;
  28604. for (index = 0; index < positions.length; index++) {
  28605. normals[index] = 0.0;
  28606. }
  28607. // indice triplet = 1 face
  28608. var nbFaces = indices.length / 3;
  28609. for (index = 0; index < nbFaces; index++) {
  28610. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  28611. i2 = indices[index * 3 + 1];
  28612. i3 = indices[index * 3 + 2];
  28613. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  28614. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  28615. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  28616. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  28617. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  28618. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  28619. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  28620. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  28621. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  28622. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28623. length = (length === 0) ? 1.0 : length;
  28624. faceNormalx /= length; // normalize this normal
  28625. faceNormaly /= length;
  28626. faceNormalz /= length;
  28627. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  28628. normals[i1 * 3 + 1] += faceNormaly;
  28629. normals[i1 * 3 + 2] += faceNormalz;
  28630. normals[i2 * 3] += faceNormalx;
  28631. normals[i2 * 3 + 1] += faceNormaly;
  28632. normals[i2 * 3 + 2] += faceNormalz;
  28633. normals[i3 * 3] += faceNormalx;
  28634. normals[i3 * 3 + 1] += faceNormaly;
  28635. normals[i3 * 3 + 2] += faceNormalz;
  28636. }
  28637. // last normalization of each normal
  28638. for (index = 0; index < normals.length / 3; index++) {
  28639. faceNormalx = normals[index * 3];
  28640. faceNormaly = normals[index * 3 + 1];
  28641. faceNormalz = normals[index * 3 + 2];
  28642. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28643. length = (length === 0) ? 1.0 : length;
  28644. faceNormalx /= length;
  28645. faceNormaly /= length;
  28646. faceNormalz /= length;
  28647. normals[index * 3] = faceNormalx;
  28648. normals[index * 3 + 1] = faceNormaly;
  28649. normals[index * 3 + 2] = faceNormalz;
  28650. }
  28651. };
  28652. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  28653. var li = indices.length;
  28654. var ln = normals.length;
  28655. var i;
  28656. var n;
  28657. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28658. switch (sideOrientation) {
  28659. case BABYLON.Mesh.FRONTSIDE:
  28660. // nothing changed
  28661. break;
  28662. case BABYLON.Mesh.BACKSIDE:
  28663. var tmp;
  28664. // indices
  28665. for (i = 0; i < li; i += 3) {
  28666. tmp = indices[i];
  28667. indices[i] = indices[i + 2];
  28668. indices[i + 2] = tmp;
  28669. }
  28670. // normals
  28671. for (n = 0; n < ln; n++) {
  28672. normals[n] = -normals[n];
  28673. }
  28674. break;
  28675. case BABYLON.Mesh.DOUBLESIDE:
  28676. // positions
  28677. var lp = positions.length;
  28678. var l = lp / 3;
  28679. for (var p = 0; p < lp; p++) {
  28680. positions[lp + p] = positions[p];
  28681. }
  28682. // indices
  28683. for (i = 0; i < li; i += 3) {
  28684. indices[i + li] = indices[i + 2] + l;
  28685. indices[i + 1 + li] = indices[i + 1] + l;
  28686. indices[i + 2 + li] = indices[i] + l;
  28687. }
  28688. // normals
  28689. for (n = 0; n < ln; n++) {
  28690. normals[ln + n] = -normals[n];
  28691. }
  28692. // uvs
  28693. var lu = uvs.length;
  28694. for (var u = 0; u < lu; u++) {
  28695. uvs[u + lu] = uvs[u];
  28696. }
  28697. break;
  28698. }
  28699. };
  28700. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28701. var vertexData = new VertexData();
  28702. // positions
  28703. var positions = parsedVertexData.positions;
  28704. if (positions) {
  28705. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28706. }
  28707. // normals
  28708. var normals = parsedVertexData.normals;
  28709. if (normals) {
  28710. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28711. }
  28712. // uvs
  28713. var uvs = parsedVertexData.uvs;
  28714. if (uvs) {
  28715. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28716. }
  28717. // uv2s
  28718. var uv2s = parsedVertexData.uv2s;
  28719. if (uv2s) {
  28720. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28721. }
  28722. // uv3s
  28723. var uv3s = parsedVertexData.uv3s;
  28724. if (uv3s) {
  28725. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28726. }
  28727. // uv4s
  28728. var uv4s = parsedVertexData.uv4s;
  28729. if (uv4s) {
  28730. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28731. }
  28732. // uv5s
  28733. var uv5s = parsedVertexData.uv5s;
  28734. if (uv5s) {
  28735. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28736. }
  28737. // uv6s
  28738. var uv6s = parsedVertexData.uv6s;
  28739. if (uv6s) {
  28740. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28741. }
  28742. // colors
  28743. var colors = parsedVertexData.colors;
  28744. if (colors) {
  28745. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28746. }
  28747. // matricesIndices
  28748. var matricesIndices = parsedVertexData.matricesIndices;
  28749. if (matricesIndices) {
  28750. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28751. }
  28752. // matricesWeights
  28753. var matricesWeights = parsedVertexData.matricesWeights;
  28754. if (matricesWeights) {
  28755. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28756. }
  28757. // indices
  28758. var indices = parsedVertexData.indices;
  28759. if (indices) {
  28760. vertexData.indices = indices;
  28761. }
  28762. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28763. };
  28764. return VertexData;
  28765. })();
  28766. BABYLON.VertexData = VertexData;
  28767. })(BABYLON || (BABYLON = {}));
  28768. var BABYLON;
  28769. (function (BABYLON) {
  28770. var Tags = (function () {
  28771. function Tags() {
  28772. }
  28773. Tags.EnableFor = function (obj) {
  28774. obj._tags = obj._tags || {};
  28775. obj.hasTags = function () {
  28776. return Tags.HasTags(obj);
  28777. };
  28778. obj.addTags = function (tagsString) {
  28779. return Tags.AddTagsTo(obj, tagsString);
  28780. };
  28781. obj.removeTags = function (tagsString) {
  28782. return Tags.RemoveTagsFrom(obj, tagsString);
  28783. };
  28784. obj.matchesTagsQuery = function (tagsQuery) {
  28785. return Tags.MatchesQuery(obj, tagsQuery);
  28786. };
  28787. };
  28788. Tags.DisableFor = function (obj) {
  28789. delete obj._tags;
  28790. delete obj.hasTags;
  28791. delete obj.addTags;
  28792. delete obj.removeTags;
  28793. delete obj.matchesTagsQuery;
  28794. };
  28795. Tags.HasTags = function (obj) {
  28796. if (!obj._tags) {
  28797. return false;
  28798. }
  28799. return !BABYLON.Tools.IsEmpty(obj._tags);
  28800. };
  28801. Tags.GetTags = function (obj, asString) {
  28802. if (asString === void 0) { asString = true; }
  28803. if (!obj._tags) {
  28804. return null;
  28805. }
  28806. if (asString) {
  28807. var tagsArray = [];
  28808. for (var tag in obj._tags) {
  28809. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  28810. tagsArray.push(tag);
  28811. }
  28812. }
  28813. return tagsArray.join(" ");
  28814. }
  28815. else {
  28816. return obj._tags;
  28817. }
  28818. };
  28819. // the tags 'true' and 'false' are reserved and cannot be used as tags
  28820. // a tag cannot start with '||', '&&', and '!'
  28821. // it cannot contain whitespaces
  28822. Tags.AddTagsTo = function (obj, tagsString) {
  28823. if (!tagsString) {
  28824. return;
  28825. }
  28826. if (typeof tagsString !== "string") {
  28827. return;
  28828. }
  28829. var tags = tagsString.split(" ");
  28830. for (var t in tags) {
  28831. Tags._AddTagTo(obj, tags[t]);
  28832. }
  28833. };
  28834. Tags._AddTagTo = function (obj, tag) {
  28835. tag = tag.trim();
  28836. if (tag === "" || tag === "true" || tag === "false") {
  28837. return;
  28838. }
  28839. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  28840. return;
  28841. }
  28842. Tags.EnableFor(obj);
  28843. obj._tags[tag] = true;
  28844. };
  28845. Tags.RemoveTagsFrom = function (obj, tagsString) {
  28846. if (!Tags.HasTags(obj)) {
  28847. return;
  28848. }
  28849. var tags = tagsString.split(" ");
  28850. for (var t in tags) {
  28851. Tags._RemoveTagFrom(obj, tags[t]);
  28852. }
  28853. };
  28854. Tags._RemoveTagFrom = function (obj, tag) {
  28855. delete obj._tags[tag];
  28856. };
  28857. Tags.MatchesQuery = function (obj, tagsQuery) {
  28858. if (tagsQuery === undefined) {
  28859. return true;
  28860. }
  28861. if (tagsQuery === "") {
  28862. return Tags.HasTags(obj);
  28863. }
  28864. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  28865. };
  28866. return Tags;
  28867. })();
  28868. BABYLON.Tags = Tags;
  28869. })(BABYLON || (BABYLON = {}));
  28870. var BABYLON;
  28871. (function (BABYLON) {
  28872. var Internals;
  28873. (function (Internals) {
  28874. var AndOrNotEvaluator = (function () {
  28875. function AndOrNotEvaluator() {
  28876. }
  28877. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  28878. if (!query.match(/\([^\(\)]*\)/g)) {
  28879. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  28880. }
  28881. else {
  28882. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  28883. // remove parenthesis
  28884. r = r.slice(1, r.length - 1);
  28885. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  28886. });
  28887. }
  28888. if (query === "true") {
  28889. return true;
  28890. }
  28891. if (query === "false") {
  28892. return false;
  28893. }
  28894. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  28895. };
  28896. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  28897. evaluateCallback = evaluateCallback || (function (r) {
  28898. return r === "true" ? true : false;
  28899. });
  28900. var result;
  28901. var or = parenthesisContent.split("||");
  28902. for (var i in or) {
  28903. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  28904. var and = ori.split("&&");
  28905. if (and.length > 1) {
  28906. for (var j = 0; j < and.length; ++j) {
  28907. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  28908. if (andj !== "true" && andj !== "false") {
  28909. if (andj[0] === "!") {
  28910. result = !evaluateCallback(andj.substring(1));
  28911. }
  28912. else {
  28913. result = evaluateCallback(andj);
  28914. }
  28915. }
  28916. else {
  28917. result = andj === "true" ? true : false;
  28918. }
  28919. if (!result) {
  28920. ori = "false";
  28921. break;
  28922. }
  28923. }
  28924. }
  28925. if (result || ori === "true") {
  28926. result = true;
  28927. break;
  28928. }
  28929. // result equals false (or undefined)
  28930. if (ori !== "true" && ori !== "false") {
  28931. if (ori[0] === "!") {
  28932. result = !evaluateCallback(ori.substring(1));
  28933. }
  28934. else {
  28935. result = evaluateCallback(ori);
  28936. }
  28937. }
  28938. else {
  28939. result = ori === "true" ? true : false;
  28940. }
  28941. }
  28942. // the whole parenthesis scope is replaced by 'true' or 'false'
  28943. return result ? "true" : "false";
  28944. };
  28945. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  28946. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  28947. // remove whitespaces
  28948. r = r.replace(/[\s]/g, function () { return ""; });
  28949. return r.length % 2 ? "!" : "";
  28950. });
  28951. booleanString = booleanString.trim();
  28952. if (booleanString === "!true") {
  28953. booleanString = "false";
  28954. }
  28955. else if (booleanString === "!false") {
  28956. booleanString = "true";
  28957. }
  28958. return booleanString;
  28959. };
  28960. return AndOrNotEvaluator;
  28961. })();
  28962. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  28963. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28964. })(BABYLON || (BABYLON = {}));
  28965. var BABYLON;
  28966. (function (BABYLON) {
  28967. var PostProcessRenderPass = (function () {
  28968. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  28969. this._enabled = true;
  28970. this._refCount = 0;
  28971. this._name = name;
  28972. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  28973. this.setRenderList(renderList);
  28974. this._renderTexture.onBeforeRender = beforeRender;
  28975. this._renderTexture.onAfterRender = afterRender;
  28976. this._scene = scene;
  28977. this._renderList = renderList;
  28978. }
  28979. // private
  28980. PostProcessRenderPass.prototype._incRefCount = function () {
  28981. if (this._refCount === 0) {
  28982. this._scene.customRenderTargets.push(this._renderTexture);
  28983. }
  28984. return ++this._refCount;
  28985. };
  28986. PostProcessRenderPass.prototype._decRefCount = function () {
  28987. this._refCount--;
  28988. if (this._refCount <= 0) {
  28989. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  28990. }
  28991. return this._refCount;
  28992. };
  28993. PostProcessRenderPass.prototype._update = function () {
  28994. this.setRenderList(this._renderList);
  28995. };
  28996. // public
  28997. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  28998. this._renderTexture.renderList = renderList;
  28999. };
  29000. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29001. return this._renderTexture;
  29002. };
  29003. return PostProcessRenderPass;
  29004. })();
  29005. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29006. })(BABYLON || (BABYLON = {}));
  29007. var BABYLON;
  29008. (function (BABYLON) {
  29009. var PostProcessRenderEffect = (function () {
  29010. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29011. this._engine = engine;
  29012. this._name = name;
  29013. this._singleInstance = singleInstance || true;
  29014. this._getPostProcess = getPostProcess;
  29015. this._cameras = [];
  29016. this._indicesForCamera = [];
  29017. this._postProcesses = {};
  29018. this._renderPasses = {};
  29019. this._renderEffectAsPasses = {};
  29020. }
  29021. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29022. get: function () {
  29023. for (var index in this._postProcesses) {
  29024. if (!this._postProcesses[index].isSupported) {
  29025. return false;
  29026. }
  29027. }
  29028. return true;
  29029. },
  29030. enumerable: true,
  29031. configurable: true
  29032. });
  29033. PostProcessRenderEffect.prototype._update = function () {
  29034. for (var renderPassName in this._renderPasses) {
  29035. this._renderPasses[renderPassName]._update();
  29036. }
  29037. };
  29038. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29039. this._renderPasses[renderPass._name] = renderPass;
  29040. this._linkParameters();
  29041. };
  29042. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29043. delete this._renderPasses[renderPass._name];
  29044. this._linkParameters();
  29045. };
  29046. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29047. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29048. this._linkParameters();
  29049. };
  29050. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29051. for (var renderPassName in this._renderPasses) {
  29052. if (renderPassName === passName) {
  29053. return this._renderPasses[passName];
  29054. }
  29055. }
  29056. };
  29057. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29058. this._renderPasses = {};
  29059. this._linkParameters();
  29060. };
  29061. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29062. var cameraKey;
  29063. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29064. for (var i = 0; i < _cam.length; i++) {
  29065. var camera = _cam[i];
  29066. var cameraName = camera.name;
  29067. if (this._singleInstance) {
  29068. cameraKey = 0;
  29069. }
  29070. else {
  29071. cameraKey = cameraName;
  29072. }
  29073. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29074. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29075. if (!this._indicesForCamera[cameraName]) {
  29076. this._indicesForCamera[cameraName] = [];
  29077. }
  29078. this._indicesForCamera[cameraName].push(index);
  29079. if (this._cameras.indexOf(camera) === -1) {
  29080. this._cameras[cameraName] = camera;
  29081. }
  29082. for (var passName in this._renderPasses) {
  29083. this._renderPasses[passName]._incRefCount();
  29084. }
  29085. }
  29086. this._linkParameters();
  29087. };
  29088. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29089. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29090. for (var i = 0; i < _cam.length; i++) {
  29091. var camera = _cam[i];
  29092. var cameraName = camera.name;
  29093. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29094. var index = this._cameras.indexOf(cameraName);
  29095. this._indicesForCamera.splice(index, 1);
  29096. this._cameras.splice(index, 1);
  29097. for (var passName in this._renderPasses) {
  29098. this._renderPasses[passName]._decRefCount();
  29099. }
  29100. }
  29101. };
  29102. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29103. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29104. for (var i = 0; i < _cam.length; i++) {
  29105. var camera = _cam[i];
  29106. var cameraName = camera.name;
  29107. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29108. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29109. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29110. }
  29111. }
  29112. for (var passName in this._renderPasses) {
  29113. this._renderPasses[passName]._incRefCount();
  29114. }
  29115. }
  29116. };
  29117. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29118. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29119. for (var i = 0; i < _cam.length; i++) {
  29120. var camera = _cam[i];
  29121. var cameraName = camera.Name;
  29122. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29123. for (var passName in this._renderPasses) {
  29124. this._renderPasses[passName]._decRefCount();
  29125. }
  29126. }
  29127. };
  29128. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29129. if (this._singleInstance) {
  29130. return this._postProcesses[0];
  29131. }
  29132. else {
  29133. return this._postProcesses[camera.name];
  29134. }
  29135. };
  29136. PostProcessRenderEffect.prototype._linkParameters = function () {
  29137. var _this = this;
  29138. for (var index in this._postProcesses) {
  29139. if (this.applyParameters) {
  29140. this.applyParameters(this._postProcesses[index]);
  29141. }
  29142. this._postProcesses[index].onBeforeRender = function (effect) {
  29143. _this._linkTextures(effect);
  29144. };
  29145. }
  29146. };
  29147. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29148. for (var renderPassName in this._renderPasses) {
  29149. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29150. }
  29151. for (var renderEffectName in this._renderEffectAsPasses) {
  29152. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29153. }
  29154. };
  29155. return PostProcessRenderEffect;
  29156. })();
  29157. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29158. })(BABYLON || (BABYLON = {}));
  29159. var BABYLON;
  29160. (function (BABYLON) {
  29161. var PostProcessRenderPipeline = (function () {
  29162. function PostProcessRenderPipeline(engine, name) {
  29163. this._engine = engine;
  29164. this._name = name;
  29165. this._renderEffects = {};
  29166. this._renderEffectsForIsolatedPass = {};
  29167. this._cameras = [];
  29168. }
  29169. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29170. get: function () {
  29171. for (var renderEffectName in this._renderEffects) {
  29172. if (!this._renderEffects[renderEffectName].isSupported) {
  29173. return false;
  29174. }
  29175. }
  29176. return true;
  29177. },
  29178. enumerable: true,
  29179. configurable: true
  29180. });
  29181. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29182. this._renderEffects[renderEffect._name] = renderEffect;
  29183. };
  29184. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29185. var renderEffects = this._renderEffects[renderEffectName];
  29186. if (!renderEffects) {
  29187. return;
  29188. }
  29189. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29190. };
  29191. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29192. var renderEffects = this._renderEffects[renderEffectName];
  29193. if (!renderEffects) {
  29194. return;
  29195. }
  29196. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29197. };
  29198. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29199. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29200. var indicesToDelete = [];
  29201. var i;
  29202. for (i = 0; i < _cam.length; i++) {
  29203. var camera = _cam[i];
  29204. var cameraName = camera.name;
  29205. if (this._cameras.indexOf(camera) === -1) {
  29206. this._cameras[cameraName] = camera;
  29207. }
  29208. else if (unique) {
  29209. indicesToDelete.push(i);
  29210. }
  29211. }
  29212. for (i = 0; i < indicesToDelete.length; i++) {
  29213. cameras.splice(indicesToDelete[i], 1);
  29214. }
  29215. for (var renderEffectName in this._renderEffects) {
  29216. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29217. }
  29218. };
  29219. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29220. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29221. for (var renderEffectName in this._renderEffects) {
  29222. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29223. }
  29224. for (var i = 0; i < _cam.length; i++) {
  29225. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29226. }
  29227. };
  29228. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29229. var _this = this;
  29230. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29231. var pass = null;
  29232. var renderEffectName;
  29233. for (renderEffectName in this._renderEffects) {
  29234. pass = this._renderEffects[renderEffectName].getPass(passName);
  29235. if (pass != null) {
  29236. break;
  29237. }
  29238. }
  29239. if (pass === null) {
  29240. return;
  29241. }
  29242. for (renderEffectName in this._renderEffects) {
  29243. this._renderEffects[renderEffectName]._disable(_cam);
  29244. }
  29245. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29246. for (var i = 0; i < _cam.length; i++) {
  29247. var camera = _cam[i];
  29248. var cameraName = camera.name;
  29249. 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); });
  29250. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29251. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29252. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29253. }
  29254. };
  29255. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29256. var _this = this;
  29257. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29258. for (var i = 0; i < _cam.length; i++) {
  29259. var camera = _cam[i];
  29260. var cameraName = camera.name;
  29261. 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); });
  29262. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29263. }
  29264. for (var renderEffectName in this._renderEffects) {
  29265. this._renderEffects[renderEffectName]._enable(_cam);
  29266. }
  29267. };
  29268. PostProcessRenderPipeline.prototype._update = function () {
  29269. for (var renderEffectName in this._renderEffects) {
  29270. this._renderEffects[renderEffectName]._update();
  29271. }
  29272. for (var i = 0; i < this._cameras.length; i++) {
  29273. var cameraName = this._cameras[i].name;
  29274. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29275. this._renderEffectsForIsolatedPass[cameraName]._update();
  29276. }
  29277. }
  29278. };
  29279. PostProcessRenderPipeline.prototype.dispose = function () {
  29280. // Must be implemented by children
  29281. };
  29282. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29283. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29284. return PostProcessRenderPipeline;
  29285. })();
  29286. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29287. })(BABYLON || (BABYLON = {}));
  29288. var BABYLON;
  29289. (function (BABYLON) {
  29290. var PostProcessRenderPipelineManager = (function () {
  29291. function PostProcessRenderPipelineManager() {
  29292. this._renderPipelines = {};
  29293. }
  29294. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29295. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29296. };
  29297. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29298. var renderPipeline = this._renderPipelines[renderPipelineName];
  29299. if (!renderPipeline) {
  29300. return;
  29301. }
  29302. renderPipeline._attachCameras(cameras, unique);
  29303. };
  29304. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29305. var renderPipeline = this._renderPipelines[renderPipelineName];
  29306. if (!renderPipeline) {
  29307. return;
  29308. }
  29309. renderPipeline._detachCameras(cameras);
  29310. };
  29311. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29312. var renderPipeline = this._renderPipelines[renderPipelineName];
  29313. if (!renderPipeline) {
  29314. return;
  29315. }
  29316. renderPipeline._enableEffect(renderEffectName, cameras);
  29317. };
  29318. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29319. var renderPipeline = this._renderPipelines[renderPipelineName];
  29320. if (!renderPipeline) {
  29321. return;
  29322. }
  29323. renderPipeline._disableEffect(renderEffectName, cameras);
  29324. };
  29325. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29326. var renderPipeline = this._renderPipelines[renderPipelineName];
  29327. if (!renderPipeline) {
  29328. return;
  29329. }
  29330. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29331. };
  29332. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29333. var renderPipeline = this._renderPipelines[renderPipelineName];
  29334. if (!renderPipeline) {
  29335. return;
  29336. }
  29337. renderPipeline._disableDisplayOnlyPass(cameras);
  29338. };
  29339. PostProcessRenderPipelineManager.prototype.update = function () {
  29340. for (var renderPipelineName in this._renderPipelines) {
  29341. var pipeline = this._renderPipelines[renderPipelineName];
  29342. if (!pipeline.isSupported) {
  29343. pipeline.dispose();
  29344. delete this._renderPipelines[renderPipelineName];
  29345. }
  29346. else {
  29347. pipeline._update();
  29348. }
  29349. }
  29350. };
  29351. return PostProcessRenderPipelineManager;
  29352. })();
  29353. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29354. })(BABYLON || (BABYLON = {}));
  29355. var BABYLON;
  29356. (function (BABYLON) {
  29357. var BoundingBoxRenderer = (function () {
  29358. function BoundingBoxRenderer(scene) {
  29359. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29360. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29361. this.showBackLines = true;
  29362. this.renderList = new BABYLON.SmartArray(32);
  29363. this._scene = scene;
  29364. }
  29365. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29366. if (this._colorShader) {
  29367. return;
  29368. }
  29369. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29370. attributes: ["position"],
  29371. uniforms: ["worldViewProjection", "color"]
  29372. });
  29373. var engine = this._scene.getEngine();
  29374. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29375. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29376. 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]);
  29377. };
  29378. BoundingBoxRenderer.prototype.reset = function () {
  29379. this.renderList.reset();
  29380. };
  29381. BoundingBoxRenderer.prototype.render = function () {
  29382. if (this.renderList.length === 0) {
  29383. return;
  29384. }
  29385. this._prepareRessources();
  29386. if (!this._colorShader.isReady()) {
  29387. return;
  29388. }
  29389. var engine = this._scene.getEngine();
  29390. engine.setDepthWrite(false);
  29391. this._colorShader._preBind();
  29392. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29393. var boundingBox = this.renderList.data[boundingBoxIndex];
  29394. var min = boundingBox.minimum;
  29395. var max = boundingBox.maximum;
  29396. var diff = max.subtract(min);
  29397. var median = min.add(diff.scale(0.5));
  29398. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29399. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29400. .multiply(boundingBox.getWorldMatrix());
  29401. // VBOs
  29402. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29403. if (this.showBackLines) {
  29404. // Back
  29405. engine.setDepthFunctionToGreaterOrEqual();
  29406. this._scene.resetCachedMaterial();
  29407. this._colorShader.setColor4("color", this.backColor.toColor4());
  29408. this._colorShader.bind(worldMatrix);
  29409. // Draw order
  29410. engine.draw(false, 0, 24);
  29411. }
  29412. // Front
  29413. engine.setDepthFunctionToLess();
  29414. this._scene.resetCachedMaterial();
  29415. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29416. this._colorShader.bind(worldMatrix);
  29417. // Draw order
  29418. engine.draw(false, 0, 24);
  29419. }
  29420. this._colorShader.unbind();
  29421. engine.setDepthFunctionToLessOrEqual();
  29422. engine.setDepthWrite(true);
  29423. };
  29424. BoundingBoxRenderer.prototype.dispose = function () {
  29425. if (!this._colorShader) {
  29426. return;
  29427. }
  29428. this._colorShader.dispose();
  29429. this._vb.dispose();
  29430. this._scene.getEngine()._releaseBuffer(this._ib);
  29431. };
  29432. return BoundingBoxRenderer;
  29433. })();
  29434. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29435. })(BABYLON || (BABYLON = {}));
  29436. var BABYLON;
  29437. (function (BABYLON) {
  29438. var Condition = (function () {
  29439. function Condition(actionManager) {
  29440. this._actionManager = actionManager;
  29441. }
  29442. Condition.prototype.isValid = function () {
  29443. return true;
  29444. };
  29445. Condition.prototype._getProperty = function (propertyPath) {
  29446. return this._actionManager._getProperty(propertyPath);
  29447. };
  29448. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29449. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29450. };
  29451. return Condition;
  29452. })();
  29453. BABYLON.Condition = Condition;
  29454. var ValueCondition = (function (_super) {
  29455. __extends(ValueCondition, _super);
  29456. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29457. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29458. _super.call(this, actionManager);
  29459. this.propertyPath = propertyPath;
  29460. this.value = value;
  29461. this.operator = operator;
  29462. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29463. this._property = this._getProperty(this.propertyPath);
  29464. }
  29465. Object.defineProperty(ValueCondition, "IsEqual", {
  29466. get: function () {
  29467. return ValueCondition._IsEqual;
  29468. },
  29469. enumerable: true,
  29470. configurable: true
  29471. });
  29472. Object.defineProperty(ValueCondition, "IsDifferent", {
  29473. get: function () {
  29474. return ValueCondition._IsDifferent;
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. Object.defineProperty(ValueCondition, "IsGreater", {
  29480. get: function () {
  29481. return ValueCondition._IsGreater;
  29482. },
  29483. enumerable: true,
  29484. configurable: true
  29485. });
  29486. Object.defineProperty(ValueCondition, "IsLesser", {
  29487. get: function () {
  29488. return ValueCondition._IsLesser;
  29489. },
  29490. enumerable: true,
  29491. configurable: true
  29492. });
  29493. // Methods
  29494. ValueCondition.prototype.isValid = function () {
  29495. switch (this.operator) {
  29496. case ValueCondition.IsGreater:
  29497. return this._target[this._property] > this.value;
  29498. case ValueCondition.IsLesser:
  29499. return this._target[this._property] < this.value;
  29500. case ValueCondition.IsEqual:
  29501. case ValueCondition.IsDifferent:
  29502. var check;
  29503. if (this.value.equals) {
  29504. check = this.value.equals(this._target[this._property]);
  29505. }
  29506. else {
  29507. check = this.value === this._target[this._property];
  29508. }
  29509. return this.operator === ValueCondition.IsEqual ? check : !check;
  29510. }
  29511. return false;
  29512. };
  29513. // Statics
  29514. ValueCondition._IsEqual = 0;
  29515. ValueCondition._IsDifferent = 1;
  29516. ValueCondition._IsGreater = 2;
  29517. ValueCondition._IsLesser = 3;
  29518. return ValueCondition;
  29519. })(Condition);
  29520. BABYLON.ValueCondition = ValueCondition;
  29521. var PredicateCondition = (function (_super) {
  29522. __extends(PredicateCondition, _super);
  29523. function PredicateCondition(actionManager, predicate) {
  29524. _super.call(this, actionManager);
  29525. this.predicate = predicate;
  29526. }
  29527. PredicateCondition.prototype.isValid = function () {
  29528. return this.predicate();
  29529. };
  29530. return PredicateCondition;
  29531. })(Condition);
  29532. BABYLON.PredicateCondition = PredicateCondition;
  29533. var StateCondition = (function (_super) {
  29534. __extends(StateCondition, _super);
  29535. function StateCondition(actionManager, target, value) {
  29536. _super.call(this, actionManager);
  29537. this.value = value;
  29538. this._target = target;
  29539. }
  29540. // Methods
  29541. StateCondition.prototype.isValid = function () {
  29542. return this._target.state === this.value;
  29543. };
  29544. return StateCondition;
  29545. })(Condition);
  29546. BABYLON.StateCondition = StateCondition;
  29547. })(BABYLON || (BABYLON = {}));
  29548. var BABYLON;
  29549. (function (BABYLON) {
  29550. var Action = (function () {
  29551. function Action(triggerOptions, condition) {
  29552. this.triggerOptions = triggerOptions;
  29553. if (triggerOptions.parameter) {
  29554. this.trigger = triggerOptions.trigger;
  29555. this._triggerParameter = triggerOptions.parameter;
  29556. }
  29557. else {
  29558. this.trigger = triggerOptions;
  29559. }
  29560. this._nextActiveAction = this;
  29561. this._condition = condition;
  29562. }
  29563. // Methods
  29564. Action.prototype._prepare = function () {
  29565. };
  29566. Action.prototype.getTriggerParameter = function () {
  29567. return this._triggerParameter;
  29568. };
  29569. Action.prototype._executeCurrent = function (evt) {
  29570. if (this._nextActiveAction._condition) {
  29571. var condition = this._nextActiveAction._condition;
  29572. var currentRenderId = this._actionManager.getScene().getRenderId();
  29573. // We cache the current evaluation for the current frame
  29574. if (condition._evaluationId === currentRenderId) {
  29575. if (!condition._currentResult) {
  29576. return;
  29577. }
  29578. }
  29579. else {
  29580. condition._evaluationId = currentRenderId;
  29581. if (!condition.isValid()) {
  29582. condition._currentResult = false;
  29583. return;
  29584. }
  29585. condition._currentResult = true;
  29586. }
  29587. }
  29588. this._nextActiveAction.execute(evt);
  29589. this.skipToNextActiveAction();
  29590. };
  29591. Action.prototype.execute = function (evt) {
  29592. };
  29593. Action.prototype.skipToNextActiveAction = function () {
  29594. if (this._nextActiveAction._child) {
  29595. if (!this._nextActiveAction._child._actionManager) {
  29596. this._nextActiveAction._child._actionManager = this._actionManager;
  29597. }
  29598. this._nextActiveAction = this._nextActiveAction._child;
  29599. }
  29600. else {
  29601. this._nextActiveAction = this;
  29602. }
  29603. };
  29604. Action.prototype.then = function (action) {
  29605. this._child = action;
  29606. action._actionManager = this._actionManager;
  29607. action._prepare();
  29608. return action;
  29609. };
  29610. Action.prototype._getProperty = function (propertyPath) {
  29611. return this._actionManager._getProperty(propertyPath);
  29612. };
  29613. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  29614. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29615. };
  29616. return Action;
  29617. })();
  29618. BABYLON.Action = Action;
  29619. })(BABYLON || (BABYLON = {}));
  29620. var BABYLON;
  29621. (function (BABYLON) {
  29622. /**
  29623. * ActionEvent is the event beint sent when an action is triggered.
  29624. */
  29625. var ActionEvent = (function () {
  29626. /**
  29627. * @constructor
  29628. * @param source The mesh or sprite that triggered the action.
  29629. * @param pointerX The X mouse cursor position at the time of the event
  29630. * @param pointerY The Y mouse cursor position at the time of the event
  29631. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  29632. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  29633. */
  29634. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  29635. this.source = source;
  29636. this.pointerX = pointerX;
  29637. this.pointerY = pointerY;
  29638. this.meshUnderPointer = meshUnderPointer;
  29639. this.sourceEvent = sourceEvent;
  29640. this.additionalData = additionalData;
  29641. }
  29642. /**
  29643. * Helper function to auto-create an ActionEvent from a source mesh.
  29644. * @param source The source mesh that triggered the event
  29645. * @param evt {Event} The original (browser) event
  29646. */
  29647. ActionEvent.CreateNew = function (source, evt, additionalData) {
  29648. var scene = source.getScene();
  29649. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  29650. };
  29651. /**
  29652. * Helper function to auto-create an ActionEvent from a source mesh.
  29653. * @param source The source sprite that triggered the event
  29654. * @param scene Scene associated with the sprite
  29655. * @param evt {Event} The original (browser) event
  29656. */
  29657. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  29658. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  29659. };
  29660. /**
  29661. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  29662. * @param scene the scene where the event occurred
  29663. * @param evt {Event} The original (browser) event
  29664. */
  29665. ActionEvent.CreateNewFromScene = function (scene, evt) {
  29666. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  29667. };
  29668. return ActionEvent;
  29669. })();
  29670. BABYLON.ActionEvent = ActionEvent;
  29671. /**
  29672. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  29673. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  29674. */
  29675. var ActionManager = (function () {
  29676. function ActionManager(scene) {
  29677. // Members
  29678. this.actions = new Array();
  29679. this._scene = scene;
  29680. scene._actionManagers.push(this);
  29681. }
  29682. Object.defineProperty(ActionManager, "NothingTrigger", {
  29683. get: function () {
  29684. return ActionManager._NothingTrigger;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. Object.defineProperty(ActionManager, "OnPickTrigger", {
  29690. get: function () {
  29691. return ActionManager._OnPickTrigger;
  29692. },
  29693. enumerable: true,
  29694. configurable: true
  29695. });
  29696. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  29697. get: function () {
  29698. return ActionManager._OnLeftPickTrigger;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  29704. get: function () {
  29705. return ActionManager._OnRightPickTrigger;
  29706. },
  29707. enumerable: true,
  29708. configurable: true
  29709. });
  29710. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  29711. get: function () {
  29712. return ActionManager._OnCenterPickTrigger;
  29713. },
  29714. enumerable: true,
  29715. configurable: true
  29716. });
  29717. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  29718. get: function () {
  29719. return ActionManager._OnPickDownTrigger;
  29720. },
  29721. enumerable: true,
  29722. configurable: true
  29723. });
  29724. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  29725. get: function () {
  29726. return ActionManager._OnPickUpTrigger;
  29727. },
  29728. enumerable: true,
  29729. configurable: true
  29730. });
  29731. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  29732. /// This trigger will only be raised if you also declared a OnPickDown
  29733. get: function () {
  29734. return ActionManager._OnPickOutTrigger;
  29735. },
  29736. enumerable: true,
  29737. configurable: true
  29738. });
  29739. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  29740. get: function () {
  29741. return ActionManager._OnLongPressTrigger;
  29742. },
  29743. enumerable: true,
  29744. configurable: true
  29745. });
  29746. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  29747. get: function () {
  29748. return ActionManager._OnPointerOverTrigger;
  29749. },
  29750. enumerable: true,
  29751. configurable: true
  29752. });
  29753. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  29754. get: function () {
  29755. return ActionManager._OnPointerOutTrigger;
  29756. },
  29757. enumerable: true,
  29758. configurable: true
  29759. });
  29760. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  29761. get: function () {
  29762. return ActionManager._OnEveryFrameTrigger;
  29763. },
  29764. enumerable: true,
  29765. configurable: true
  29766. });
  29767. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  29768. get: function () {
  29769. return ActionManager._OnIntersectionEnterTrigger;
  29770. },
  29771. enumerable: true,
  29772. configurable: true
  29773. });
  29774. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  29775. get: function () {
  29776. return ActionManager._OnIntersectionExitTrigger;
  29777. },
  29778. enumerable: true,
  29779. configurable: true
  29780. });
  29781. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  29782. get: function () {
  29783. return ActionManager._OnKeyDownTrigger;
  29784. },
  29785. enumerable: true,
  29786. configurable: true
  29787. });
  29788. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  29789. get: function () {
  29790. return ActionManager._OnKeyUpTrigger;
  29791. },
  29792. enumerable: true,
  29793. configurable: true
  29794. });
  29795. // Methods
  29796. ActionManager.prototype.dispose = function () {
  29797. var index = this._scene._actionManagers.indexOf(this);
  29798. if (index > -1) {
  29799. this._scene._actionManagers.splice(index, 1);
  29800. }
  29801. };
  29802. ActionManager.prototype.getScene = function () {
  29803. return this._scene;
  29804. };
  29805. /**
  29806. * Does this action manager handles actions of any of the given triggers
  29807. * @param {number[]} triggers - the triggers to be tested
  29808. * @return {boolean} whether one (or more) of the triggers is handeled
  29809. */
  29810. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  29811. for (var index = 0; index < this.actions.length; index++) {
  29812. var action = this.actions[index];
  29813. if (triggers.indexOf(action.trigger) > -1) {
  29814. return true;
  29815. }
  29816. }
  29817. return false;
  29818. };
  29819. /**
  29820. * Does this action manager handles actions of a given trigger
  29821. * @param {number} trigger - the trigger to be tested
  29822. * @return {boolean} whether the trigger is handeled
  29823. */
  29824. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  29825. for (var index = 0; index < this.actions.length; index++) {
  29826. var action = this.actions[index];
  29827. if (action.trigger === trigger) {
  29828. return true;
  29829. }
  29830. }
  29831. return false;
  29832. };
  29833. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  29834. /**
  29835. * Does this action manager has pointer triggers
  29836. * @return {boolean} whether or not it has pointer triggers
  29837. */
  29838. get: function () {
  29839. for (var index = 0; index < this.actions.length; index++) {
  29840. var action = this.actions[index];
  29841. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  29842. return true;
  29843. }
  29844. }
  29845. return false;
  29846. },
  29847. enumerable: true,
  29848. configurable: true
  29849. });
  29850. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  29851. /**
  29852. * Does this action manager has pick triggers
  29853. * @return {boolean} whether or not it has pick triggers
  29854. */
  29855. get: function () {
  29856. for (var index = 0; index < this.actions.length; index++) {
  29857. var action = this.actions[index];
  29858. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  29859. return true;
  29860. }
  29861. }
  29862. return false;
  29863. },
  29864. enumerable: true,
  29865. configurable: true
  29866. });
  29867. /**
  29868. * Registers an action to this action manager
  29869. * @param {BABYLON.Action} action - the action to be registered
  29870. * @return {BABYLON.Action} the action amended (prepared) after registration
  29871. */
  29872. ActionManager.prototype.registerAction = function (action) {
  29873. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  29874. if (this.getScene().actionManager !== this) {
  29875. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  29876. return null;
  29877. }
  29878. }
  29879. this.actions.push(action);
  29880. action._actionManager = this;
  29881. action._prepare();
  29882. return action;
  29883. };
  29884. /**
  29885. * Process a specific trigger
  29886. * @param {number} trigger - the trigger to process
  29887. * @param evt {BABYLON.ActionEvent} the event details to be processed
  29888. */
  29889. ActionManager.prototype.processTrigger = function (trigger, evt) {
  29890. for (var index = 0; index < this.actions.length; index++) {
  29891. var action = this.actions[index];
  29892. if (action.trigger === trigger) {
  29893. if (trigger === ActionManager.OnKeyUpTrigger
  29894. || trigger === ActionManager.OnKeyDownTrigger) {
  29895. var parameter = action.getTriggerParameter();
  29896. if (parameter) {
  29897. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  29898. var actualkey = String.fromCharCode(unicode).toLowerCase();
  29899. if (actualkey !== parameter.toLowerCase()) {
  29900. continue;
  29901. }
  29902. }
  29903. }
  29904. action._executeCurrent(evt);
  29905. }
  29906. }
  29907. };
  29908. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  29909. var properties = propertyPath.split(".");
  29910. for (var index = 0; index < properties.length - 1; index++) {
  29911. target = target[properties[index]];
  29912. }
  29913. return target;
  29914. };
  29915. ActionManager.prototype._getProperty = function (propertyPath) {
  29916. var properties = propertyPath.split(".");
  29917. return properties[properties.length - 1];
  29918. };
  29919. ActionManager.Parse = function (parsedActions, object, scene) {
  29920. var actionManager = new BABYLON.ActionManager(scene);
  29921. if (object === null)
  29922. scene.actionManager = actionManager;
  29923. else
  29924. object.actionManager = actionManager;
  29925. // instanciate a new object
  29926. var instanciate = function (name, params) {
  29927. var newInstance = Object.create(BABYLON[name].prototype);
  29928. newInstance.constructor.apply(newInstance, params);
  29929. return newInstance;
  29930. };
  29931. var parseParameter = function (name, value, target, propertyPath) {
  29932. if (propertyPath === null) {
  29933. // String, boolean or float
  29934. var floatValue = parseFloat(value);
  29935. if (value === "true" || value === "false")
  29936. return value === "true";
  29937. else
  29938. return isNaN(floatValue) ? value : floatValue;
  29939. }
  29940. var effectiveTarget = propertyPath.split(".");
  29941. var values = value.split(",");
  29942. // Get effective Target
  29943. for (var i = 0; i < effectiveTarget.length; i++) {
  29944. target = target[effectiveTarget[i]];
  29945. }
  29946. // Return appropriate value with its type
  29947. if (typeof (target) === "boolean")
  29948. return values[0] === "true";
  29949. if (typeof (target) === "string")
  29950. return values[0];
  29951. // Parameters with multiple values such as Vector3 etc.
  29952. var split = new Array();
  29953. for (var i = 0; i < values.length; i++)
  29954. split.push(parseFloat(values[i]));
  29955. if (target instanceof BABYLON.Vector3)
  29956. return BABYLON.Vector3.FromArray(split);
  29957. if (target instanceof BABYLON.Vector4)
  29958. return BABYLON.Vector4.FromArray(split);
  29959. if (target instanceof BABYLON.Color3)
  29960. return BABYLON.Color3.FromArray(split);
  29961. if (target instanceof BABYLON.Color4)
  29962. return BABYLON.Color4.FromArray(split);
  29963. return parseFloat(values[0]);
  29964. };
  29965. // traverse graph per trigger
  29966. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  29967. if (combineArray === void 0) { combineArray = null; }
  29968. if (parsedAction.detached)
  29969. return;
  29970. var parameters = new Array();
  29971. var target = null;
  29972. var propertyPath = null;
  29973. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  29974. // Parameters
  29975. if (parsedAction.type === 2)
  29976. parameters.push(actionManager);
  29977. else
  29978. parameters.push(trigger);
  29979. if (combine) {
  29980. var actions = new Array();
  29981. for (var j = 0; j < parsedAction.combine.length; j++) {
  29982. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  29983. }
  29984. parameters.push(actions);
  29985. }
  29986. else {
  29987. for (var i = 0; i < parsedAction.properties.length; i++) {
  29988. var value = parsedAction.properties[i].value;
  29989. var name = parsedAction.properties[i].name;
  29990. var targetType = parsedAction.properties[i].targetType;
  29991. if (name === "target")
  29992. if (targetType !== null && targetType === "SceneProperties")
  29993. value = target = scene;
  29994. else
  29995. value = target = scene.getNodeByName(value);
  29996. else if (name === "parent")
  29997. value = scene.getNodeByName(value);
  29998. else if (name === "sound")
  29999. value = scene.getSoundByName(value);
  30000. else if (name !== "propertyPath") {
  30001. if (parsedAction.type === 2 && name === "operator")
  30002. value = BABYLON.ValueCondition[value];
  30003. else
  30004. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30005. }
  30006. else {
  30007. propertyPath = value;
  30008. }
  30009. parameters.push(value);
  30010. }
  30011. }
  30012. if (combineArray === null) {
  30013. parameters.push(condition);
  30014. }
  30015. else {
  30016. parameters.push(null);
  30017. }
  30018. // If interpolate value action
  30019. if (parsedAction.name === "InterpolateValueAction") {
  30020. var param = parameters[parameters.length - 2];
  30021. parameters[parameters.length - 1] = param;
  30022. parameters[parameters.length - 2] = condition;
  30023. }
  30024. // Action or condition(s) and not CombineAction
  30025. var newAction = instanciate(parsedAction.name, parameters);
  30026. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30027. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30028. if (action)
  30029. action.then(nothing);
  30030. else
  30031. actionManager.registerAction(nothing);
  30032. action = nothing;
  30033. }
  30034. if (combineArray === null) {
  30035. if (newAction instanceof BABYLON.Condition) {
  30036. condition = newAction;
  30037. newAction = action;
  30038. }
  30039. else {
  30040. condition = null;
  30041. if (action)
  30042. action.then(newAction);
  30043. else
  30044. actionManager.registerAction(newAction);
  30045. }
  30046. }
  30047. else {
  30048. combineArray.push(newAction);
  30049. }
  30050. for (var i = 0; i < parsedAction.children.length; i++)
  30051. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30052. };
  30053. // triggers
  30054. for (var i = 0; i < parsedActions.children.length; i++) {
  30055. var triggerParams;
  30056. var trigger = parsedActions.children[i];
  30057. if (trigger.properties.length > 0) {
  30058. var param = trigger.properties[0].value;
  30059. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30060. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30061. }
  30062. else
  30063. triggerParams = BABYLON.ActionManager[trigger.name];
  30064. for (var j = 0; j < trigger.children.length; j++) {
  30065. if (!trigger.detached)
  30066. traverse(trigger.children[j], triggerParams, null, null);
  30067. }
  30068. }
  30069. };
  30070. // Statics
  30071. ActionManager._NothingTrigger = 0;
  30072. ActionManager._OnPickTrigger = 1;
  30073. ActionManager._OnLeftPickTrigger = 2;
  30074. ActionManager._OnRightPickTrigger = 3;
  30075. ActionManager._OnCenterPickTrigger = 4;
  30076. ActionManager._OnPickDownTrigger = 5;
  30077. ActionManager._OnPickUpTrigger = 6;
  30078. ActionManager._OnLongPressTrigger = 7;
  30079. ActionManager._OnPointerOverTrigger = 8;
  30080. ActionManager._OnPointerOutTrigger = 9;
  30081. ActionManager._OnEveryFrameTrigger = 10;
  30082. ActionManager._OnIntersectionEnterTrigger = 11;
  30083. ActionManager._OnIntersectionExitTrigger = 12;
  30084. ActionManager._OnKeyDownTrigger = 13;
  30085. ActionManager._OnKeyUpTrigger = 14;
  30086. ActionManager._OnPickOutTrigger = 15;
  30087. ActionManager.DragMovementThreshold = 10; // in pixels
  30088. ActionManager.LongPressDelay = 500; // in milliseconds
  30089. return ActionManager;
  30090. })();
  30091. BABYLON.ActionManager = ActionManager;
  30092. })(BABYLON || (BABYLON = {}));
  30093. var BABYLON;
  30094. (function (BABYLON) {
  30095. var InterpolateValueAction = (function (_super) {
  30096. __extends(InterpolateValueAction, _super);
  30097. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30098. if (duration === void 0) { duration = 1000; }
  30099. _super.call(this, triggerOptions, condition);
  30100. this.propertyPath = propertyPath;
  30101. this.value = value;
  30102. this.duration = duration;
  30103. this.stopOtherAnimations = stopOtherAnimations;
  30104. this.onInterpolationDone = onInterpolationDone;
  30105. this._target = target;
  30106. }
  30107. InterpolateValueAction.prototype._prepare = function () {
  30108. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30109. this._property = this._getProperty(this.propertyPath);
  30110. };
  30111. InterpolateValueAction.prototype.execute = function () {
  30112. var scene = this._actionManager.getScene();
  30113. var keys = [
  30114. {
  30115. frame: 0,
  30116. value: this._target[this._property]
  30117. }, {
  30118. frame: 100,
  30119. value: this.value
  30120. }
  30121. ];
  30122. var dataType;
  30123. if (typeof this.value === "number") {
  30124. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30125. }
  30126. else if (this.value instanceof BABYLON.Color3) {
  30127. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30128. }
  30129. else if (this.value instanceof BABYLON.Vector3) {
  30130. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30131. }
  30132. else if (this.value instanceof BABYLON.Matrix) {
  30133. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30134. }
  30135. else if (this.value instanceof BABYLON.Quaternion) {
  30136. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30137. }
  30138. else {
  30139. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30140. return;
  30141. }
  30142. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30143. animation.setKeys(keys);
  30144. if (this.stopOtherAnimations) {
  30145. scene.stopAnimation(this._target);
  30146. }
  30147. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30148. };
  30149. return InterpolateValueAction;
  30150. })(BABYLON.Action);
  30151. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30152. })(BABYLON || (BABYLON = {}));
  30153. var BABYLON;
  30154. (function (BABYLON) {
  30155. var SwitchBooleanAction = (function (_super) {
  30156. __extends(SwitchBooleanAction, _super);
  30157. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30158. _super.call(this, triggerOptions, condition);
  30159. this.propertyPath = propertyPath;
  30160. this._target = target;
  30161. }
  30162. SwitchBooleanAction.prototype._prepare = function () {
  30163. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30164. this._property = this._getProperty(this.propertyPath);
  30165. };
  30166. SwitchBooleanAction.prototype.execute = function () {
  30167. this._target[this._property] = !this._target[this._property];
  30168. };
  30169. return SwitchBooleanAction;
  30170. })(BABYLON.Action);
  30171. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30172. var SetStateAction = (function (_super) {
  30173. __extends(SetStateAction, _super);
  30174. function SetStateAction(triggerOptions, target, value, condition) {
  30175. _super.call(this, triggerOptions, condition);
  30176. this.value = value;
  30177. this._target = target;
  30178. }
  30179. SetStateAction.prototype.execute = function () {
  30180. this._target.state = this.value;
  30181. };
  30182. return SetStateAction;
  30183. })(BABYLON.Action);
  30184. BABYLON.SetStateAction = SetStateAction;
  30185. var SetValueAction = (function (_super) {
  30186. __extends(SetValueAction, _super);
  30187. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30188. _super.call(this, triggerOptions, condition);
  30189. this.propertyPath = propertyPath;
  30190. this.value = value;
  30191. this._target = target;
  30192. }
  30193. SetValueAction.prototype._prepare = function () {
  30194. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30195. this._property = this._getProperty(this.propertyPath);
  30196. };
  30197. SetValueAction.prototype.execute = function () {
  30198. this._target[this._property] = this.value;
  30199. };
  30200. return SetValueAction;
  30201. })(BABYLON.Action);
  30202. BABYLON.SetValueAction = SetValueAction;
  30203. var IncrementValueAction = (function (_super) {
  30204. __extends(IncrementValueAction, _super);
  30205. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30206. _super.call(this, triggerOptions, condition);
  30207. this.propertyPath = propertyPath;
  30208. this.value = value;
  30209. this._target = target;
  30210. }
  30211. IncrementValueAction.prototype._prepare = function () {
  30212. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30213. this._property = this._getProperty(this.propertyPath);
  30214. if (typeof this._target[this._property] !== "number") {
  30215. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30216. }
  30217. };
  30218. IncrementValueAction.prototype.execute = function () {
  30219. this._target[this._property] += this.value;
  30220. };
  30221. return IncrementValueAction;
  30222. })(BABYLON.Action);
  30223. BABYLON.IncrementValueAction = IncrementValueAction;
  30224. var PlayAnimationAction = (function (_super) {
  30225. __extends(PlayAnimationAction, _super);
  30226. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30227. _super.call(this, triggerOptions, condition);
  30228. this.from = from;
  30229. this.to = to;
  30230. this.loop = loop;
  30231. this._target = target;
  30232. }
  30233. PlayAnimationAction.prototype._prepare = function () {
  30234. };
  30235. PlayAnimationAction.prototype.execute = function () {
  30236. var scene = this._actionManager.getScene();
  30237. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30238. };
  30239. return PlayAnimationAction;
  30240. })(BABYLON.Action);
  30241. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30242. var StopAnimationAction = (function (_super) {
  30243. __extends(StopAnimationAction, _super);
  30244. function StopAnimationAction(triggerOptions, target, condition) {
  30245. _super.call(this, triggerOptions, condition);
  30246. this._target = target;
  30247. }
  30248. StopAnimationAction.prototype._prepare = function () {
  30249. };
  30250. StopAnimationAction.prototype.execute = function () {
  30251. var scene = this._actionManager.getScene();
  30252. scene.stopAnimation(this._target);
  30253. };
  30254. return StopAnimationAction;
  30255. })(BABYLON.Action);
  30256. BABYLON.StopAnimationAction = StopAnimationAction;
  30257. var DoNothingAction = (function (_super) {
  30258. __extends(DoNothingAction, _super);
  30259. function DoNothingAction(triggerOptions, condition) {
  30260. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30261. _super.call(this, triggerOptions, condition);
  30262. }
  30263. DoNothingAction.prototype.execute = function () {
  30264. };
  30265. return DoNothingAction;
  30266. })(BABYLON.Action);
  30267. BABYLON.DoNothingAction = DoNothingAction;
  30268. var CombineAction = (function (_super) {
  30269. __extends(CombineAction, _super);
  30270. function CombineAction(triggerOptions, children, condition) {
  30271. _super.call(this, triggerOptions, condition);
  30272. this.children = children;
  30273. }
  30274. CombineAction.prototype._prepare = function () {
  30275. for (var index = 0; index < this.children.length; index++) {
  30276. this.children[index]._actionManager = this._actionManager;
  30277. this.children[index]._prepare();
  30278. }
  30279. };
  30280. CombineAction.prototype.execute = function (evt) {
  30281. for (var index = 0; index < this.children.length; index++) {
  30282. this.children[index].execute(evt);
  30283. }
  30284. };
  30285. return CombineAction;
  30286. })(BABYLON.Action);
  30287. BABYLON.CombineAction = CombineAction;
  30288. var ExecuteCodeAction = (function (_super) {
  30289. __extends(ExecuteCodeAction, _super);
  30290. function ExecuteCodeAction(triggerOptions, func, condition) {
  30291. _super.call(this, triggerOptions, condition);
  30292. this.func = func;
  30293. }
  30294. ExecuteCodeAction.prototype.execute = function (evt) {
  30295. this.func(evt);
  30296. };
  30297. return ExecuteCodeAction;
  30298. })(BABYLON.Action);
  30299. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30300. var SetParentAction = (function (_super) {
  30301. __extends(SetParentAction, _super);
  30302. function SetParentAction(triggerOptions, target, parent, condition) {
  30303. _super.call(this, triggerOptions, condition);
  30304. this._target = target;
  30305. this._parent = parent;
  30306. }
  30307. SetParentAction.prototype._prepare = function () {
  30308. };
  30309. SetParentAction.prototype.execute = function () {
  30310. if (this._target.parent === this._parent) {
  30311. return;
  30312. }
  30313. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30314. invertParentWorldMatrix.invert();
  30315. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30316. this._target.parent = this._parent;
  30317. };
  30318. return SetParentAction;
  30319. })(BABYLON.Action);
  30320. BABYLON.SetParentAction = SetParentAction;
  30321. var PlaySoundAction = (function (_super) {
  30322. __extends(PlaySoundAction, _super);
  30323. function PlaySoundAction(triggerOptions, sound, condition) {
  30324. _super.call(this, triggerOptions, condition);
  30325. this._sound = sound;
  30326. }
  30327. PlaySoundAction.prototype._prepare = function () {
  30328. };
  30329. PlaySoundAction.prototype.execute = function () {
  30330. if (this._sound !== undefined)
  30331. this._sound.play();
  30332. };
  30333. return PlaySoundAction;
  30334. })(BABYLON.Action);
  30335. BABYLON.PlaySoundAction = PlaySoundAction;
  30336. var StopSoundAction = (function (_super) {
  30337. __extends(StopSoundAction, _super);
  30338. function StopSoundAction(triggerOptions, sound, condition) {
  30339. _super.call(this, triggerOptions, condition);
  30340. this._sound = sound;
  30341. }
  30342. StopSoundAction.prototype._prepare = function () {
  30343. };
  30344. StopSoundAction.prototype.execute = function () {
  30345. if (this._sound !== undefined)
  30346. this._sound.stop();
  30347. };
  30348. return StopSoundAction;
  30349. })(BABYLON.Action);
  30350. BABYLON.StopSoundAction = StopSoundAction;
  30351. })(BABYLON || (BABYLON = {}));
  30352. var BABYLON;
  30353. (function (BABYLON) {
  30354. var Geometry = (function () {
  30355. function Geometry(id, scene, vertexData, updatable, mesh) {
  30356. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30357. this._totalVertices = 0;
  30358. this._isDisposed = false;
  30359. this.id = id;
  30360. this._engine = scene.getEngine();
  30361. this._meshes = [];
  30362. this._scene = scene;
  30363. //Init vertex buffer cache
  30364. this._vertexBuffers = {};
  30365. this._indices = [];
  30366. // vertexData
  30367. if (vertexData) {
  30368. this.setAllVerticesData(vertexData, updatable);
  30369. }
  30370. else {
  30371. this._totalVertices = 0;
  30372. this._indices = [];
  30373. }
  30374. // applyToMesh
  30375. if (mesh) {
  30376. this.applyToMesh(mesh);
  30377. mesh.computeWorldMatrix(true);
  30378. }
  30379. }
  30380. Object.defineProperty(Geometry.prototype, "extend", {
  30381. get: function () {
  30382. return this._extend;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Geometry.prototype.getScene = function () {
  30388. return this._scene;
  30389. };
  30390. Geometry.prototype.getEngine = function () {
  30391. return this._engine;
  30392. };
  30393. Geometry.prototype.isReady = function () {
  30394. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30395. };
  30396. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30397. vertexData.applyToGeometry(this, updatable);
  30398. this.notifyUpdate();
  30399. };
  30400. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30401. if (this._vertexBuffers[kind]) {
  30402. this._vertexBuffers[kind].dispose();
  30403. }
  30404. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30405. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30406. stride = this._vertexBuffers[kind].getStrideSize();
  30407. this._totalVertices = data.length / stride;
  30408. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  30409. var meshes = this._meshes;
  30410. var numOfMeshes = meshes.length;
  30411. for (var index = 0; index < numOfMeshes; index++) {
  30412. var mesh = meshes[index];
  30413. mesh._resetPointsArrayCache();
  30414. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30415. mesh._createGlobalSubMesh();
  30416. mesh.computeWorldMatrix(true);
  30417. }
  30418. }
  30419. this.notifyUpdate(kind);
  30420. };
  30421. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30422. var vertexBuffer = this.getVertexBuffer(kind);
  30423. if (!vertexBuffer) {
  30424. return;
  30425. }
  30426. vertexBuffer.updateDirectly(data, offset);
  30427. this.notifyUpdate(kind);
  30428. };
  30429. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30430. var vertexBuffer = this.getVertexBuffer(kind);
  30431. if (!vertexBuffer) {
  30432. return;
  30433. }
  30434. vertexBuffer.update(data);
  30435. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30436. var stride = vertexBuffer.getStrideSize();
  30437. this._totalVertices = data.length / stride;
  30438. if (updateExtends) {
  30439. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  30440. }
  30441. var meshes = this._meshes;
  30442. var numOfMeshes = meshes.length;
  30443. for (var index = 0; index < numOfMeshes; index++) {
  30444. var mesh = meshes[index];
  30445. mesh._resetPointsArrayCache();
  30446. if (updateExtends) {
  30447. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30448. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30449. var subMesh = mesh.subMeshes[subIndex];
  30450. subMesh.refreshBoundingInfo();
  30451. }
  30452. }
  30453. }
  30454. }
  30455. this.notifyUpdate(kind);
  30456. };
  30457. Geometry.prototype.getTotalVertices = function () {
  30458. if (!this.isReady()) {
  30459. return 0;
  30460. }
  30461. return this._totalVertices;
  30462. };
  30463. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  30464. var vertexBuffer = this.getVertexBuffer(kind);
  30465. if (!vertexBuffer) {
  30466. return null;
  30467. }
  30468. var orig = vertexBuffer.getData();
  30469. if (!copyWhenShared || this._meshes.length === 1) {
  30470. return orig;
  30471. }
  30472. else {
  30473. var len = orig.length;
  30474. var copy = [];
  30475. for (var i = 0; i < len; i++) {
  30476. copy.push(orig[i]);
  30477. }
  30478. return copy;
  30479. }
  30480. };
  30481. Geometry.prototype.getVertexBuffer = function (kind) {
  30482. if (!this.isReady()) {
  30483. return null;
  30484. }
  30485. return this._vertexBuffers[kind];
  30486. };
  30487. Geometry.prototype.getVertexBuffers = function () {
  30488. if (!this.isReady()) {
  30489. return null;
  30490. }
  30491. return this._vertexBuffers;
  30492. };
  30493. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30494. if (!this._vertexBuffers) {
  30495. if (this._delayInfo) {
  30496. return this._delayInfo.indexOf(kind) !== -1;
  30497. }
  30498. return false;
  30499. }
  30500. return this._vertexBuffers[kind] !== undefined;
  30501. };
  30502. Geometry.prototype.getVerticesDataKinds = function () {
  30503. var result = [];
  30504. var kind;
  30505. if (!this._vertexBuffers && this._delayInfo) {
  30506. for (kind in this._delayInfo) {
  30507. result.push(kind);
  30508. }
  30509. }
  30510. else {
  30511. for (kind in this._vertexBuffers) {
  30512. result.push(kind);
  30513. }
  30514. }
  30515. return result;
  30516. };
  30517. Geometry.prototype.setIndices = function (indices, totalVertices) {
  30518. if (this._indexBuffer) {
  30519. this._engine._releaseBuffer(this._indexBuffer);
  30520. }
  30521. this._indices = indices;
  30522. if (this._meshes.length !== 0 && this._indices) {
  30523. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30524. }
  30525. if (totalVertices !== undefined) {
  30526. this._totalVertices = totalVertices;
  30527. }
  30528. var meshes = this._meshes;
  30529. var numOfMeshes = meshes.length;
  30530. for (var index = 0; index < numOfMeshes; index++) {
  30531. meshes[index]._createGlobalSubMesh();
  30532. }
  30533. this.notifyUpdate();
  30534. };
  30535. Geometry.prototype.getTotalIndices = function () {
  30536. if (!this.isReady()) {
  30537. return 0;
  30538. }
  30539. return this._indices.length;
  30540. };
  30541. Geometry.prototype.getIndices = function (copyWhenShared) {
  30542. if (!this.isReady()) {
  30543. return null;
  30544. }
  30545. var orig = this._indices;
  30546. if (!copyWhenShared || this._meshes.length === 1) {
  30547. return orig;
  30548. }
  30549. else {
  30550. var len = orig.length;
  30551. var copy = [];
  30552. for (var i = 0; i < len; i++) {
  30553. copy.push(orig[i]);
  30554. }
  30555. return copy;
  30556. }
  30557. };
  30558. Geometry.prototype.getIndexBuffer = function () {
  30559. if (!this.isReady()) {
  30560. return null;
  30561. }
  30562. return this._indexBuffer;
  30563. };
  30564. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30565. var meshes = this._meshes;
  30566. var index = meshes.indexOf(mesh);
  30567. if (index === -1) {
  30568. return;
  30569. }
  30570. for (var kind in this._vertexBuffers) {
  30571. this._vertexBuffers[kind].dispose();
  30572. }
  30573. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  30574. this._indexBuffer = null;
  30575. }
  30576. meshes.splice(index, 1);
  30577. mesh._geometry = null;
  30578. if (meshes.length === 0 && shouldDispose) {
  30579. this.dispose();
  30580. }
  30581. };
  30582. Geometry.prototype.applyToMesh = function (mesh) {
  30583. if (mesh._geometry === this) {
  30584. return;
  30585. }
  30586. var previousGeometry = mesh._geometry;
  30587. if (previousGeometry) {
  30588. previousGeometry.releaseForMesh(mesh);
  30589. }
  30590. var meshes = this._meshes;
  30591. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30592. mesh._geometry = this;
  30593. this._scene.pushGeometry(this);
  30594. meshes.push(mesh);
  30595. if (this.isReady()) {
  30596. this._applyToMesh(mesh);
  30597. }
  30598. else {
  30599. mesh._boundingInfo = this._boundingInfo;
  30600. }
  30601. };
  30602. Geometry.prototype._applyToMesh = function (mesh) {
  30603. var numOfMeshes = this._meshes.length;
  30604. // vertexBuffers
  30605. for (var kind in this._vertexBuffers) {
  30606. if (numOfMeshes === 1) {
  30607. this._vertexBuffers[kind].create();
  30608. }
  30609. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  30610. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30611. mesh._resetPointsArrayCache();
  30612. if (!this._extend) {
  30613. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  30614. }
  30615. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30616. mesh._createGlobalSubMesh();
  30617. //bounding info was just created again, world matrix should be applied again.
  30618. mesh._updateBoundingInfo();
  30619. }
  30620. }
  30621. // indexBuffer
  30622. if (numOfMeshes === 1 && this._indices) {
  30623. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30624. }
  30625. if (this._indexBuffer) {
  30626. this._indexBuffer.references = numOfMeshes;
  30627. }
  30628. };
  30629. Geometry.prototype.notifyUpdate = function (kind) {
  30630. if (this.onGeometryUpdated) {
  30631. this.onGeometryUpdated(this, kind);
  30632. }
  30633. };
  30634. Geometry.prototype.load = function (scene, onLoaded) {
  30635. var _this = this;
  30636. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30637. return;
  30638. }
  30639. if (this.isReady()) {
  30640. if (onLoaded) {
  30641. onLoaded();
  30642. }
  30643. return;
  30644. }
  30645. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30646. scene._addPendingData(this);
  30647. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30648. _this._delayLoadingFunction(JSON.parse(data), _this);
  30649. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30650. _this._delayInfo = [];
  30651. scene._removePendingData(_this);
  30652. var meshes = _this._meshes;
  30653. var numOfMeshes = meshes.length;
  30654. for (var index = 0; index < numOfMeshes; index++) {
  30655. _this._applyToMesh(meshes[index]);
  30656. }
  30657. if (onLoaded) {
  30658. onLoaded();
  30659. }
  30660. }, function () { }, scene.database);
  30661. };
  30662. Geometry.prototype.isDisposed = function () {
  30663. return this._isDisposed;
  30664. };
  30665. Geometry.prototype.dispose = function () {
  30666. var meshes = this._meshes;
  30667. var numOfMeshes = meshes.length;
  30668. var index;
  30669. for (index = 0; index < numOfMeshes; index++) {
  30670. this.releaseForMesh(meshes[index]);
  30671. }
  30672. this._meshes = [];
  30673. for (var kind in this._vertexBuffers) {
  30674. this._vertexBuffers[kind].dispose();
  30675. }
  30676. this._vertexBuffers = [];
  30677. this._totalVertices = 0;
  30678. if (this._indexBuffer) {
  30679. this._engine._releaseBuffer(this._indexBuffer);
  30680. }
  30681. this._indexBuffer = null;
  30682. this._indices = [];
  30683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30684. this.delayLoadingFile = null;
  30685. this._delayLoadingFunction = null;
  30686. this._delayInfo = [];
  30687. this._boundingInfo = null;
  30688. this._scene.removeGeometry(this);
  30689. this._isDisposed = true;
  30690. };
  30691. Geometry.prototype.copy = function (id) {
  30692. var vertexData = new BABYLON.VertexData();
  30693. vertexData.indices = [];
  30694. var indices = this.getIndices();
  30695. for (var index = 0; index < indices.length; index++) {
  30696. vertexData.indices.push(indices[index]);
  30697. }
  30698. var updatable = false;
  30699. var stopChecking = false;
  30700. var kind;
  30701. for (kind in this._vertexBuffers) {
  30702. // using slice() to make a copy of the array and not just reference it
  30703. var data = this.getVerticesData(kind);
  30704. if (data instanceof Float32Array) {
  30705. vertexData.set(new Float32Array(data), kind);
  30706. }
  30707. else {
  30708. vertexData.set(data.slice(0), kind);
  30709. }
  30710. if (!stopChecking) {
  30711. updatable = this.getVertexBuffer(kind).isUpdatable();
  30712. stopChecking = !updatable;
  30713. }
  30714. }
  30715. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  30716. geometry.delayLoadState = this.delayLoadState;
  30717. geometry.delayLoadingFile = this.delayLoadingFile;
  30718. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30719. for (kind in this._delayInfo) {
  30720. geometry._delayInfo = geometry._delayInfo || [];
  30721. geometry._delayInfo.push(kind);
  30722. }
  30723. // Bounding info
  30724. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30725. return geometry;
  30726. };
  30727. Geometry.prototype.serialize = function () {
  30728. var serializationObject = {};
  30729. serializationObject.id = this.id;
  30730. if (BABYLON.Tags.HasTags(this)) {
  30731. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30732. }
  30733. return serializationObject;
  30734. };
  30735. Geometry.prototype.serializeVerticeData = function () {
  30736. var serializationObject = this.serialize();
  30737. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30738. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30739. }
  30740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30741. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30742. }
  30743. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30744. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30745. }
  30746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30747. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  30748. }
  30749. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30750. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  30751. }
  30752. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30753. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  30754. }
  30755. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30756. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  30757. }
  30758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30759. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  30760. }
  30761. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30762. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30763. }
  30764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30765. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30766. serializationObject.matricesIndices._isExpanded = true;
  30767. }
  30768. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30769. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30770. }
  30771. serializationObject.indices = this.getIndices();
  30772. return serializationObject;
  30773. };
  30774. // Statics
  30775. Geometry.ExtractFromMesh = function (mesh, id) {
  30776. var geometry = mesh._geometry;
  30777. if (!geometry) {
  30778. return null;
  30779. }
  30780. return geometry.copy(id);
  30781. };
  30782. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30783. // be aware Math.random() could cause collisions
  30784. Geometry.RandomId = function () {
  30785. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  30786. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  30787. return v.toString(16);
  30788. });
  30789. };
  30790. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30791. var scene = mesh.getScene();
  30792. // Geometry
  30793. var geometryId = parsedGeometry.geometryId;
  30794. if (geometryId) {
  30795. var geometry = scene.getGeometryByID(geometryId);
  30796. if (geometry) {
  30797. geometry.applyToMesh(mesh);
  30798. }
  30799. }
  30800. else if (parsedGeometry instanceof ArrayBuffer) {
  30801. var binaryInfo = mesh._binaryInfo;
  30802. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30803. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30804. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30805. }
  30806. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30807. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30808. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30809. }
  30810. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30811. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30812. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30813. }
  30814. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30815. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30816. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30817. }
  30818. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30819. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30820. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30821. }
  30822. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30823. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30824. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30825. }
  30826. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30827. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30828. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30829. }
  30830. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30831. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30832. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30833. }
  30834. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30835. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30836. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30837. }
  30838. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30839. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30840. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30841. }
  30842. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30843. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30844. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30845. }
  30846. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30847. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30848. mesh.setIndices(indicesData);
  30849. }
  30850. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30851. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30852. mesh.subMeshes = [];
  30853. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30854. var materialIndex = subMeshesData[(i * 5) + 0];
  30855. var verticesStart = subMeshesData[(i * 5) + 1];
  30856. var verticesCount = subMeshesData[(i * 5) + 2];
  30857. var indexStart = subMeshesData[(i * 5) + 3];
  30858. var indexCount = subMeshesData[(i * 5) + 4];
  30859. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30860. }
  30861. }
  30862. }
  30863. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30864. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  30865. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  30866. if (parsedGeometry.uvs) {
  30867. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  30868. }
  30869. if (parsedGeometry.uvs2) {
  30870. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  30871. }
  30872. if (parsedGeometry.uvs3) {
  30873. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  30874. }
  30875. if (parsedGeometry.uvs4) {
  30876. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  30877. }
  30878. if (parsedGeometry.uvs5) {
  30879. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  30880. }
  30881. if (parsedGeometry.uvs6) {
  30882. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  30883. }
  30884. if (parsedGeometry.colors) {
  30885. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  30886. }
  30887. if (parsedGeometry.matricesIndices) {
  30888. if (!parsedGeometry.matricesIndices._isExpanded) {
  30889. var floatIndices = [];
  30890. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30891. var matricesIndex = parsedGeometry.matricesIndices[i];
  30892. floatIndices.push(matricesIndex & 0x000000FF);
  30893. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30894. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30895. floatIndices.push(matricesIndex >> 24);
  30896. }
  30897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  30898. }
  30899. else {
  30900. delete parsedGeometry.matricesIndices._isExpanded;
  30901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  30902. }
  30903. }
  30904. if (parsedGeometry.matricesIndicesExtra) {
  30905. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30906. var floatIndices = [];
  30907. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30908. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30909. floatIndices.push(matricesIndex & 0x000000FF);
  30910. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30911. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30912. floatIndices.push(matricesIndex >> 24);
  30913. }
  30914. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  30915. }
  30916. else {
  30917. delete parsedGeometry.matricesIndices._isExpanded;
  30918. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  30919. }
  30920. }
  30921. if (parsedGeometry.matricesWeights) {
  30922. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  30923. }
  30924. if (parsedGeometry.matricesWeightsExtra) {
  30925. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  30926. }
  30927. mesh.setIndices(parsedGeometry.indices);
  30928. }
  30929. // SubMeshes
  30930. if (parsedGeometry.subMeshes) {
  30931. mesh.subMeshes = [];
  30932. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30933. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30934. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30935. }
  30936. }
  30937. // Flat shading
  30938. if (mesh._shouldGenerateFlatShading) {
  30939. mesh.convertToFlatShadedMesh();
  30940. delete mesh._shouldGenerateFlatShading;
  30941. }
  30942. // Update
  30943. mesh.computeWorldMatrix(true);
  30944. // Octree
  30945. if (scene['_selectionOctree']) {
  30946. scene['_selectionOctree'].addMesh(mesh);
  30947. }
  30948. };
  30949. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30950. if (scene.getGeometryByID(parsedVertexData.id)) {
  30951. return null; // null since geometry could be something else than a box...
  30952. }
  30953. var geometry = new Geometry(parsedVertexData.id, scene);
  30954. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30955. if (parsedVertexData.delayLoadingFile) {
  30956. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30957. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30958. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30959. geometry._delayInfo = [];
  30960. if (parsedVertexData.hasUVs) {
  30961. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30962. }
  30963. if (parsedVertexData.hasUVs2) {
  30964. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30965. }
  30966. if (parsedVertexData.hasUVs3) {
  30967. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30968. }
  30969. if (parsedVertexData.hasUVs4) {
  30970. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30971. }
  30972. if (parsedVertexData.hasUVs5) {
  30973. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30974. }
  30975. if (parsedVertexData.hasUVs6) {
  30976. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30977. }
  30978. if (parsedVertexData.hasColors) {
  30979. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30980. }
  30981. if (parsedVertexData.hasMatricesIndices) {
  30982. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30983. }
  30984. if (parsedVertexData.hasMatricesWeights) {
  30985. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30986. }
  30987. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30988. }
  30989. else {
  30990. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30991. }
  30992. scene.pushGeometry(geometry, true);
  30993. return geometry;
  30994. };
  30995. return Geometry;
  30996. })();
  30997. BABYLON.Geometry = Geometry;
  30998. /////// Primitives //////////////////////////////////////////////
  30999. var Geometry;
  31000. (function (Geometry) {
  31001. var Primitives;
  31002. (function (Primitives) {
  31003. /// Abstract class
  31004. var _Primitive = (function (_super) {
  31005. __extends(_Primitive, _super);
  31006. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31007. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31008. this._canBeRegenerated = _canBeRegenerated;
  31009. this._beingRegenerated = true;
  31010. this.regenerate();
  31011. this._beingRegenerated = false;
  31012. }
  31013. _Primitive.prototype.canBeRegenerated = function () {
  31014. return this._canBeRegenerated;
  31015. };
  31016. _Primitive.prototype.regenerate = function () {
  31017. if (!this._canBeRegenerated) {
  31018. return;
  31019. }
  31020. this._beingRegenerated = true;
  31021. this.setAllVerticesData(this._regenerateVertexData(), false);
  31022. this._beingRegenerated = false;
  31023. };
  31024. _Primitive.prototype.asNewGeometry = function (id) {
  31025. return _super.prototype.copy.call(this, id);
  31026. };
  31027. // overrides
  31028. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31029. if (!this._beingRegenerated) {
  31030. return;
  31031. }
  31032. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31033. };
  31034. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31035. if (!this._beingRegenerated) {
  31036. return;
  31037. }
  31038. _super.prototype.setVerticesData.call(this, kind, data, false);
  31039. };
  31040. // to override
  31041. // protected
  31042. _Primitive.prototype._regenerateVertexData = function () {
  31043. throw new Error("Abstract method");
  31044. };
  31045. _Primitive.prototype.copy = function (id) {
  31046. throw new Error("Must be overriden in sub-classes.");
  31047. };
  31048. _Primitive.prototype.serialize = function () {
  31049. var serializationObject = _super.prototype.serialize.call(this);
  31050. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31051. return serializationObject;
  31052. };
  31053. return _Primitive;
  31054. })(Geometry);
  31055. Primitives._Primitive = _Primitive;
  31056. var Ribbon = (function (_super) {
  31057. __extends(Ribbon, _super);
  31058. // Members
  31059. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31060. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31061. _super.call(this, id, scene, canBeRegenerated, mesh);
  31062. this.pathArray = pathArray;
  31063. this.closeArray = closeArray;
  31064. this.closePath = closePath;
  31065. this.offset = offset;
  31066. this.side = side;
  31067. }
  31068. Ribbon.prototype._regenerateVertexData = function () {
  31069. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31070. };
  31071. Ribbon.prototype.copy = function (id) {
  31072. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31073. };
  31074. return Ribbon;
  31075. })(_Primitive);
  31076. Primitives.Ribbon = Ribbon;
  31077. var Box = (function (_super) {
  31078. __extends(Box, _super);
  31079. // Members
  31080. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31082. _super.call(this, id, scene, canBeRegenerated, mesh);
  31083. this.size = size;
  31084. this.side = side;
  31085. }
  31086. Box.prototype._regenerateVertexData = function () {
  31087. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31088. };
  31089. Box.prototype.copy = function (id) {
  31090. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31091. };
  31092. Box.prototype.serialize = function () {
  31093. var serializationObject = _super.prototype.serialize.call(this);
  31094. serializationObject.size = this.size;
  31095. return serializationObject;
  31096. };
  31097. Box.Parse = function (parsedBox, scene) {
  31098. if (scene.getGeometryByID(parsedBox.id)) {
  31099. return null; // null since geometry could be something else than a box...
  31100. }
  31101. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31102. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31103. scene.pushGeometry(box, true);
  31104. return box;
  31105. };
  31106. return Box;
  31107. })(_Primitive);
  31108. Primitives.Box = Box;
  31109. var Sphere = (function (_super) {
  31110. __extends(Sphere, _super);
  31111. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31112. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31113. _super.call(this, id, scene, canBeRegenerated, mesh);
  31114. this.segments = segments;
  31115. this.diameter = diameter;
  31116. this.side = side;
  31117. }
  31118. Sphere.prototype._regenerateVertexData = function () {
  31119. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31120. };
  31121. Sphere.prototype.copy = function (id) {
  31122. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31123. };
  31124. Sphere.prototype.serialize = function () {
  31125. var serializationObject = _super.prototype.serialize.call(this);
  31126. serializationObject.segments = this.segments;
  31127. serializationObject.diameter = this.diameter;
  31128. return serializationObject;
  31129. };
  31130. Sphere.Parse = function (parsedSphere, scene) {
  31131. if (scene.getGeometryByID(parsedSphere.id)) {
  31132. return null; // null since geometry could be something else than a sphere...
  31133. }
  31134. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31135. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31136. scene.pushGeometry(sphere, true);
  31137. return sphere;
  31138. };
  31139. return Sphere;
  31140. })(_Primitive);
  31141. Primitives.Sphere = Sphere;
  31142. var Disc = (function (_super) {
  31143. __extends(Disc, _super);
  31144. // Members
  31145. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31146. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31147. _super.call(this, id, scene, canBeRegenerated, mesh);
  31148. this.radius = radius;
  31149. this.tessellation = tessellation;
  31150. this.side = side;
  31151. }
  31152. Disc.prototype._regenerateVertexData = function () {
  31153. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31154. };
  31155. Disc.prototype.copy = function (id) {
  31156. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31157. };
  31158. return Disc;
  31159. })(_Primitive);
  31160. Primitives.Disc = Disc;
  31161. var Cylinder = (function (_super) {
  31162. __extends(Cylinder, _super);
  31163. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31164. if (subdivisions === void 0) { subdivisions = 1; }
  31165. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31166. _super.call(this, id, scene, canBeRegenerated, mesh);
  31167. this.height = height;
  31168. this.diameterTop = diameterTop;
  31169. this.diameterBottom = diameterBottom;
  31170. this.tessellation = tessellation;
  31171. this.subdivisions = subdivisions;
  31172. this.side = side;
  31173. }
  31174. Cylinder.prototype._regenerateVertexData = function () {
  31175. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31176. };
  31177. Cylinder.prototype.copy = function (id) {
  31178. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31179. };
  31180. Cylinder.prototype.serialize = function () {
  31181. var serializationObject = _super.prototype.serialize.call(this);
  31182. serializationObject.height = this.height;
  31183. serializationObject.diameterTop = this.diameterTop;
  31184. serializationObject.diameterBottom = this.diameterBottom;
  31185. serializationObject.tessellation = this.tessellation;
  31186. return serializationObject;
  31187. };
  31188. Cylinder.Parse = function (parsedCylinder, scene) {
  31189. if (scene.getGeometryByID(parsedCylinder.id)) {
  31190. return null; // null since geometry could be something else than a cylinder...
  31191. }
  31192. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31193. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31194. scene.pushGeometry(cylinder, true);
  31195. return cylinder;
  31196. };
  31197. return Cylinder;
  31198. })(_Primitive);
  31199. Primitives.Cylinder = Cylinder;
  31200. var Torus = (function (_super) {
  31201. __extends(Torus, _super);
  31202. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31204. _super.call(this, id, scene, canBeRegenerated, mesh);
  31205. this.diameter = diameter;
  31206. this.thickness = thickness;
  31207. this.tessellation = tessellation;
  31208. this.side = side;
  31209. }
  31210. Torus.prototype._regenerateVertexData = function () {
  31211. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31212. };
  31213. Torus.prototype.copy = function (id) {
  31214. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31215. };
  31216. Torus.prototype.serialize = function () {
  31217. var serializationObject = _super.prototype.serialize.call(this);
  31218. serializationObject.diameter = this.diameter;
  31219. serializationObject.thickness = this.thickness;
  31220. serializationObject.tessellation = this.tessellation;
  31221. return serializationObject;
  31222. };
  31223. Torus.Parse = function (parsedTorus, scene) {
  31224. if (scene.getGeometryByID(parsedTorus.id)) {
  31225. return null; // null since geometry could be something else than a torus...
  31226. }
  31227. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31228. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31229. scene.pushGeometry(torus, true);
  31230. return torus;
  31231. };
  31232. return Torus;
  31233. })(_Primitive);
  31234. Primitives.Torus = Torus;
  31235. var Ground = (function (_super) {
  31236. __extends(Ground, _super);
  31237. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31238. _super.call(this, id, scene, canBeRegenerated, mesh);
  31239. this.width = width;
  31240. this.height = height;
  31241. this.subdivisions = subdivisions;
  31242. }
  31243. Ground.prototype._regenerateVertexData = function () {
  31244. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31245. };
  31246. Ground.prototype.copy = function (id) {
  31247. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31248. };
  31249. Ground.prototype.serialize = function () {
  31250. var serializationObject = _super.prototype.serialize.call(this);
  31251. serializationObject.width = this.width;
  31252. serializationObject.height = this.height;
  31253. serializationObject.subdivisions = this.subdivisions;
  31254. return serializationObject;
  31255. };
  31256. Ground.Parse = function (parsedGround, scene) {
  31257. if (scene.getGeometryByID(parsedGround.id)) {
  31258. return null; // null since geometry could be something else than a ground...
  31259. }
  31260. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31261. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31262. scene.pushGeometry(ground, true);
  31263. return ground;
  31264. };
  31265. return Ground;
  31266. })(_Primitive);
  31267. Primitives.Ground = Ground;
  31268. var TiledGround = (function (_super) {
  31269. __extends(TiledGround, _super);
  31270. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31271. _super.call(this, id, scene, canBeRegenerated, mesh);
  31272. this.xmin = xmin;
  31273. this.zmin = zmin;
  31274. this.xmax = xmax;
  31275. this.zmax = zmax;
  31276. this.subdivisions = subdivisions;
  31277. this.precision = precision;
  31278. }
  31279. TiledGround.prototype._regenerateVertexData = function () {
  31280. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31281. };
  31282. TiledGround.prototype.copy = function (id) {
  31283. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31284. };
  31285. return TiledGround;
  31286. })(_Primitive);
  31287. Primitives.TiledGround = TiledGround;
  31288. var Plane = (function (_super) {
  31289. __extends(Plane, _super);
  31290. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31291. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31292. _super.call(this, id, scene, canBeRegenerated, mesh);
  31293. this.size = size;
  31294. this.side = side;
  31295. }
  31296. Plane.prototype._regenerateVertexData = function () {
  31297. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31298. };
  31299. Plane.prototype.copy = function (id) {
  31300. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31301. };
  31302. Plane.prototype.serialize = function () {
  31303. var serializationObject = _super.prototype.serialize.call(this);
  31304. serializationObject.size = this.size;
  31305. return serializationObject;
  31306. };
  31307. Plane.Parse = function (parsedPlane, scene) {
  31308. if (scene.getGeometryByID(parsedPlane.id)) {
  31309. return null; // null since geometry could be something else than a ground...
  31310. }
  31311. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31312. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31313. scene.pushGeometry(plane, true);
  31314. return plane;
  31315. };
  31316. return Plane;
  31317. })(_Primitive);
  31318. Primitives.Plane = Plane;
  31319. var TorusKnot = (function (_super) {
  31320. __extends(TorusKnot, _super);
  31321. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31322. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31323. _super.call(this, id, scene, canBeRegenerated, mesh);
  31324. this.radius = radius;
  31325. this.tube = tube;
  31326. this.radialSegments = radialSegments;
  31327. this.tubularSegments = tubularSegments;
  31328. this.p = p;
  31329. this.q = q;
  31330. this.side = side;
  31331. }
  31332. TorusKnot.prototype._regenerateVertexData = function () {
  31333. 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 });
  31334. };
  31335. TorusKnot.prototype.copy = function (id) {
  31336. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31337. };
  31338. TorusKnot.prototype.serialize = function () {
  31339. var serializationObject = _super.prototype.serialize.call(this);
  31340. serializationObject.radius = this.radius;
  31341. serializationObject.tube = this.tube;
  31342. serializationObject.radialSegments = this.radialSegments;
  31343. serializationObject.tubularSegments = this.tubularSegments;
  31344. serializationObject.p = this.p;
  31345. serializationObject.q = this.q;
  31346. return serializationObject;
  31347. };
  31348. ;
  31349. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31350. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31351. return null; // null since geometry could be something else than a ground...
  31352. }
  31353. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31354. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31355. scene.pushGeometry(torusKnot, true);
  31356. return torusKnot;
  31357. };
  31358. return TorusKnot;
  31359. })(_Primitive);
  31360. Primitives.TorusKnot = TorusKnot;
  31361. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31362. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31363. })(BABYLON || (BABYLON = {}));
  31364. var BABYLON;
  31365. (function (BABYLON) {
  31366. var GroundMesh = (function (_super) {
  31367. __extends(GroundMesh, _super);
  31368. function GroundMesh(name, scene) {
  31369. _super.call(this, name, scene);
  31370. this.generateOctree = false;
  31371. this._worldInverse = new BABYLON.Matrix();
  31372. }
  31373. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31374. get: function () {
  31375. return this._subdivisions;
  31376. },
  31377. enumerable: true,
  31378. configurable: true
  31379. });
  31380. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31381. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31382. this._subdivisions = chunksCount;
  31383. this.subdivide(this._subdivisions);
  31384. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31385. };
  31386. /**
  31387. * Returns a height (y) value in the Worl system :
  31388. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31389. * Returns the ground y position if (x, z) are outside the ground surface.
  31390. * Not pertinent if the ground is rotated.
  31391. */
  31392. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31393. // express x and y in the ground local system
  31394. x -= this.position.x;
  31395. z -= this.position.z;
  31396. x /= this.scaling.x;
  31397. z /= this.scaling.z;
  31398. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31399. return this.position.y;
  31400. }
  31401. if (!this._heightQuads || this._heightQuads.length == 0) {
  31402. this._initHeightQuads();
  31403. this._computeHeightQuads();
  31404. }
  31405. var facet = this._getFacetAt(x, z);
  31406. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31407. // return y in the World system
  31408. return y * this.scaling.y + this.position.y;
  31409. };
  31410. /**
  31411. * Returns a normalized vector (Vector3) orthogonal to the ground
  31412. * at the ground coordinates (x, z) expressed in the World system.
  31413. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31414. * Not pertinent if the ground is rotated.
  31415. */
  31416. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31417. var normal = new BABYLON.Vector3(0, 1, 0);
  31418. this.getNormalAtCoordinatesToRef(x, z, normal);
  31419. return normal;
  31420. };
  31421. /**
  31422. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31423. * at the ground coordinates (x, z) expressed in the World system.
  31424. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31425. * Not pertinent if the ground is rotated.
  31426. */
  31427. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31428. // express x and y in the ground local system
  31429. x -= this.position.x;
  31430. z -= this.position.z;
  31431. x /= this.scaling.x;
  31432. z /= this.scaling.z;
  31433. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31434. return;
  31435. }
  31436. if (!this._heightQuads || this._heightQuads.length == 0) {
  31437. this._initHeightQuads();
  31438. this._computeHeightQuads();
  31439. }
  31440. var facet = this._getFacetAt(x, z);
  31441. ref.x = facet.x;
  31442. ref.y = facet.y;
  31443. ref.z = facet.z;
  31444. };
  31445. /**
  31446. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31447. * if the ground has been updated.
  31448. * This can be used in the render loop
  31449. */
  31450. GroundMesh.prototype.updateCoordinateHeights = function () {
  31451. if (!this._heightQuads || this._heightQuads.length == 0) {
  31452. this._initHeightQuads();
  31453. }
  31454. this._computeHeightQuads();
  31455. };
  31456. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  31457. GroundMesh.prototype._getFacetAt = function (x, z) {
  31458. // retrieve col and row from x, z coordinates in the ground local system
  31459. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  31460. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  31461. var quad = this._heightQuads[row * this._subdivisions + col];
  31462. var facet;
  31463. if (z < quad.slope.x * x + quad.slope.y) {
  31464. facet = quad.facet1;
  31465. }
  31466. else {
  31467. facet = quad.facet2;
  31468. }
  31469. return facet;
  31470. };
  31471. // Creates and populates the heightMap array with "facet" elements :
  31472. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  31473. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31474. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31475. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31476. GroundMesh.prototype._initHeightQuads = function () {
  31477. this._heightQuads = new Array();
  31478. for (var row = 0; row < this._subdivisions; row++) {
  31479. for (var col = 0; col < this._subdivisions; col++) {
  31480. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  31481. this._heightQuads[row * this._subdivisions + col] = quad;
  31482. }
  31483. }
  31484. };
  31485. // Compute each quad element values and update the the heightMap array :
  31486. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31487. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31488. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31489. GroundMesh.prototype._computeHeightQuads = function () {
  31490. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31491. var v1 = BABYLON.Tmp.Vector3[0];
  31492. var v2 = BABYLON.Tmp.Vector3[1];
  31493. var v3 = BABYLON.Tmp.Vector3[2];
  31494. var v4 = BABYLON.Tmp.Vector3[3];
  31495. var v1v2 = BABYLON.Tmp.Vector3[4];
  31496. var v1v3 = BABYLON.Tmp.Vector3[5];
  31497. var v1v4 = BABYLON.Tmp.Vector3[6];
  31498. var norm1 = BABYLON.Tmp.Vector3[7];
  31499. var norm2 = BABYLON.Tmp.Vector3[8];
  31500. var i = 0;
  31501. var j = 0;
  31502. var k = 0;
  31503. var cd = 0; // 2D slope coefficient : z = cd * x + h
  31504. var h = 0;
  31505. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  31506. var d2 = 0;
  31507. for (var row = 0; row < this._subdivisions; row++) {
  31508. for (var col = 0; col < this._subdivisions; col++) {
  31509. i = col * 3;
  31510. j = row * (this._subdivisions + 1) * 3;
  31511. k = (row + 1) * (this._subdivisions + 1) * 3;
  31512. v1.x = positions[j + i];
  31513. v1.y = positions[j + i + 1];
  31514. v1.z = positions[j + i + 2];
  31515. v2.x = positions[j + i + 3];
  31516. v2.y = positions[j + i + 4];
  31517. v2.z = positions[j + i + 5];
  31518. v3.x = positions[k + i];
  31519. v3.y = positions[k + i + 1];
  31520. v3.z = positions[k + i + 2];
  31521. v4.x = positions[k + i + 3];
  31522. v4.y = positions[k + i + 4];
  31523. v4.z = positions[k + i + 5];
  31524. // 2D slope V1V4
  31525. cd = (v4.z - v1.z) / (v4.x - v1.x);
  31526. h = v1.z - cd * v1.x; // v1 belongs to the slope
  31527. // facet equations :
  31528. // we compute each facet normal vector
  31529. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  31530. // we compute the value d by applying the equation to v1 which belongs to the plane
  31531. // then we store the facet equation in a Vector4
  31532. v2.subtractToRef(v1, v1v2);
  31533. v3.subtractToRef(v1, v1v3);
  31534. v4.subtractToRef(v1, v1v4);
  31535. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  31536. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  31537. norm1.normalize();
  31538. norm2.normalize();
  31539. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  31540. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  31541. var quad = this._heightQuads[row * this._subdivisions + col];
  31542. quad.slope.copyFromFloats(cd, h);
  31543. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  31544. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  31545. }
  31546. }
  31547. };
  31548. return GroundMesh;
  31549. })(BABYLON.Mesh);
  31550. BABYLON.GroundMesh = GroundMesh;
  31551. })(BABYLON || (BABYLON = {}));
  31552. var BABYLON;
  31553. (function (BABYLON) {
  31554. var LinesMesh = (function (_super) {
  31555. __extends(LinesMesh, _super);
  31556. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  31557. if (parent === void 0) { parent = null; }
  31558. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  31559. this.color = new BABYLON.Color3(1, 1, 1);
  31560. this.alpha = 1;
  31561. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  31562. attributes: ["position"],
  31563. uniforms: ["worldViewProjection", "color"],
  31564. needAlphaBlending: true
  31565. });
  31566. }
  31567. Object.defineProperty(LinesMesh.prototype, "material", {
  31568. get: function () {
  31569. return this._colorShader;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  31575. get: function () {
  31576. return false;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  31582. get: function () {
  31583. return false;
  31584. },
  31585. enumerable: true,
  31586. configurable: true
  31587. });
  31588. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  31589. var engine = this.getScene().getEngine();
  31590. var indexToBind = this._geometry.getIndexBuffer();
  31591. // VBOs
  31592. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  31593. // Color
  31594. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  31595. };
  31596. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  31597. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  31598. return;
  31599. }
  31600. var engine = this.getScene().getEngine();
  31601. // Draw order
  31602. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  31603. };
  31604. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  31605. return null;
  31606. };
  31607. LinesMesh.prototype.dispose = function (doNotRecurse) {
  31608. this._colorShader.dispose();
  31609. _super.prototype.dispose.call(this, doNotRecurse);
  31610. };
  31611. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  31612. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  31613. };
  31614. return LinesMesh;
  31615. })(BABYLON.Mesh);
  31616. BABYLON.LinesMesh = LinesMesh;
  31617. })(BABYLON || (BABYLON = {}));
  31618. var BABYLON;
  31619. (function (BABYLON) {
  31620. var DebugLayer = (function () {
  31621. function DebugLayer(scene) {
  31622. var _this = this;
  31623. this._transformationMatrix = BABYLON.Matrix.Identity();
  31624. this._enabled = false;
  31625. this._labelsEnabled = false;
  31626. this._displayStatistics = true;
  31627. this._displayTree = false;
  31628. this._displayLogs = false;
  31629. this._skeletonViewers = new Array();
  31630. this._identityMatrix = BABYLON.Matrix.Identity();
  31631. this.axisRatio = 0.02;
  31632. this.accentColor = "orange";
  31633. this._scene = scene;
  31634. this._syncPositions = function () {
  31635. var engine = _this._scene.getEngine();
  31636. var canvasRect = engine.getRenderingCanvasClientRect();
  31637. if (_this._showUI) {
  31638. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  31639. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  31640. _this._statsDiv.style.width = "400px";
  31641. _this._statsDiv.style.height = "auto";
  31642. _this._statsSubsetDiv.style.maxHeight = "240px";
  31643. _this._optionsDiv.style.left = "0px";
  31644. _this._optionsDiv.style.top = "10px";
  31645. _this._optionsDiv.style.width = "200px";
  31646. _this._optionsDiv.style.height = "auto";
  31647. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  31648. _this._logDiv.style.left = "0px";
  31649. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  31650. _this._logDiv.style.width = "600px";
  31651. _this._logDiv.style.height = "160px";
  31652. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  31653. _this._treeDiv.style.top = "10px";
  31654. _this._treeDiv.style.width = "300px";
  31655. _this._treeDiv.style.height = "auto";
  31656. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  31657. }
  31658. _this._globalDiv.style.left = canvasRect.left + "px";
  31659. _this._globalDiv.style.top = canvasRect.top + "px";
  31660. _this._drawingCanvas.style.left = "0px";
  31661. _this._drawingCanvas.style.top = "0px";
  31662. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  31663. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  31664. var devicePixelRatio = window.devicePixelRatio || 1;
  31665. var context = _this._drawingContext;
  31666. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  31667. context.mozBackingStorePixelRatio ||
  31668. context.msBackingStorePixelRatio ||
  31669. context.oBackingStorePixelRatio ||
  31670. context.backingStorePixelRatio || 1;
  31671. _this._ratio = devicePixelRatio / backingStoreRatio;
  31672. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  31673. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  31674. };
  31675. this._onCanvasClick = function (evt) {
  31676. _this._clickPosition = {
  31677. x: evt.clientX * _this._ratio,
  31678. y: evt.clientY * _this._ratio
  31679. };
  31680. };
  31681. this._syncUI = function () {
  31682. if (_this._showUI) {
  31683. if (_this._displayStatistics) {
  31684. _this._displayStats();
  31685. _this._statsDiv.style.display = "";
  31686. }
  31687. else {
  31688. _this._statsDiv.style.display = "none";
  31689. }
  31690. if (_this._displayLogs) {
  31691. _this._logDiv.style.display = "";
  31692. }
  31693. else {
  31694. _this._logDiv.style.display = "none";
  31695. }
  31696. if (_this._displayTree) {
  31697. _this._treeDiv.style.display = "";
  31698. if (_this._needToRefreshMeshesTree) {
  31699. _this._needToRefreshMeshesTree = false;
  31700. _this._refreshMeshesTreeContent();
  31701. }
  31702. }
  31703. else {
  31704. _this._treeDiv.style.display = "none";
  31705. }
  31706. }
  31707. };
  31708. this._syncData = function () {
  31709. if (_this._labelsEnabled || !_this._showUI) {
  31710. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  31711. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  31712. var engine = _this._scene.getEngine();
  31713. var viewport = _this._camera.viewport;
  31714. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  31715. // Meshes
  31716. var meshes = _this._camera.getActiveMeshes();
  31717. var index;
  31718. var projectedPosition;
  31719. for (index = 0; index < meshes.length; index++) {
  31720. var mesh = meshes.data[index];
  31721. var position = mesh.getBoundingInfo().boundingSphere.center;
  31722. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31723. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  31724. _this._renderAxis(projectedPosition, mesh, globalViewport);
  31725. }
  31726. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  31727. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  31728. }
  31729. }
  31730. // Cameras
  31731. var cameras = _this._scene.cameras;
  31732. for (index = 0; index < cameras.length; index++) {
  31733. var camera = cameras[index];
  31734. if (camera === _this._camera) {
  31735. continue;
  31736. }
  31737. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31738. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  31739. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  31740. _this._camera.detachControl(engine.getRenderingCanvas());
  31741. _this._camera = camera;
  31742. _this._camera.attachControl(engine.getRenderingCanvas());
  31743. }, function () { return "purple"; });
  31744. }
  31745. }
  31746. // Lights
  31747. var lights = _this._scene.lights;
  31748. for (index = 0; index < lights.length; index++) {
  31749. var light = lights[index];
  31750. if (light.position) {
  31751. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  31752. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  31753. _this._renderLabel(light.name, projectedPosition, -20, function () {
  31754. light.setEnabled(!light.isEnabled());
  31755. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  31756. }
  31757. }
  31758. }
  31759. }
  31760. _this._clickPosition = undefined;
  31761. };
  31762. }
  31763. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  31764. while (this._treeSubsetDiv.hasChildNodes()) {
  31765. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  31766. }
  31767. // Add meshes
  31768. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  31769. sortedArray.sort(function (a, b) {
  31770. if (a.name === b.name) {
  31771. return 0;
  31772. }
  31773. return (a.name > b.name) ? 1 : -1;
  31774. });
  31775. for (var index = 0; index < sortedArray.length; index++) {
  31776. var mesh = sortedArray[index];
  31777. if (!mesh.isEnabled()) {
  31778. continue;
  31779. }
  31780. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  31781. m.isVisible = element.checked;
  31782. }, mesh);
  31783. }
  31784. };
  31785. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  31786. this._drawingContext.beginPath();
  31787. this._drawingContext.moveTo(zero.x, zero.y);
  31788. this._drawingContext.lineTo(unit.x, unit.y);
  31789. this._drawingContext.strokeStyle = color;
  31790. this._drawingContext.lineWidth = 4;
  31791. this._drawingContext.stroke();
  31792. this._drawingContext.font = "normal 14px Segoe UI";
  31793. this._drawingContext.fillStyle = color;
  31794. this._drawingContext.fillText(label, unitText.x, unitText.y);
  31795. };
  31796. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  31797. var position = mesh.getBoundingInfo().boundingSphere.center;
  31798. var worldMatrix = mesh.getWorldMatrix();
  31799. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  31800. var unit = (unprojectedVector.subtract(position)).length();
  31801. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31802. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31803. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  31804. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31805. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31806. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  31807. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  31808. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  31809. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  31810. };
  31811. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  31812. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  31813. this._drawingContext.font = "normal 12px Segoe UI";
  31814. var textMetrics = this._drawingContext.measureText(text);
  31815. var centerX = projectedPosition.x - textMetrics.width / 2;
  31816. var centerY = projectedPosition.y;
  31817. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31818. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31819. onClick();
  31820. }
  31821. this._drawingContext.beginPath();
  31822. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31823. this._drawingContext.fillStyle = getFillStyle();
  31824. this._drawingContext.globalAlpha = 0.5;
  31825. this._drawingContext.fill();
  31826. this._drawingContext.globalAlpha = 1.0;
  31827. this._drawingContext.strokeStyle = '#FFFFFF';
  31828. this._drawingContext.lineWidth = 1;
  31829. this._drawingContext.stroke();
  31830. this._drawingContext.fillStyle = "#FFFFFF";
  31831. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31832. this._drawingContext.beginPath();
  31833. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31834. this._drawingContext.fill();
  31835. }
  31836. };
  31837. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31838. if (!this._clickPosition) {
  31839. return false;
  31840. }
  31841. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31842. return false;
  31843. }
  31844. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31845. return false;
  31846. }
  31847. return true;
  31848. };
  31849. DebugLayer.prototype.isVisible = function () {
  31850. return this._enabled;
  31851. };
  31852. DebugLayer.prototype.hide = function () {
  31853. if (!this._enabled) {
  31854. return;
  31855. }
  31856. this._enabled = false;
  31857. var engine = this._scene.getEngine();
  31858. this._scene.unregisterBeforeRender(this._syncData);
  31859. this._scene.unregisterAfterRender(this._syncUI);
  31860. this._rootElement.removeChild(this._globalDiv);
  31861. this._scene.forceShowBoundingBoxes = false;
  31862. this._scene.forceWireframe = false;
  31863. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31864. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31865. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31866. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31867. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31868. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31869. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31870. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  31871. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  31872. this._scene.shadowsEnabled = true;
  31873. this._scene.particlesEnabled = true;
  31874. this._scene.postProcessesEnabled = true;
  31875. this._scene.collisionsEnabled = true;
  31876. this._scene.lightsEnabled = true;
  31877. this._scene.texturesEnabled = true;
  31878. this._scene.lensFlaresEnabled = true;
  31879. this._scene.proceduralTexturesEnabled = true;
  31880. this._scene.renderTargetsEnabled = true;
  31881. this._scene.probesEnabled = true;
  31882. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31883. this._clearSkeletonViewers();
  31884. };
  31885. DebugLayer.prototype._clearSkeletonViewers = function () {
  31886. for (var index = 0; index < this._skeletonViewers.length; index++) {
  31887. this._skeletonViewers[index].dispose();
  31888. }
  31889. this._skeletonViewers = [];
  31890. };
  31891. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  31892. if (showUI === void 0) { showUI = true; }
  31893. if (camera === void 0) { camera = null; }
  31894. if (rootElement === void 0) { rootElement = null; }
  31895. if (this._enabled) {
  31896. return;
  31897. }
  31898. this._enabled = true;
  31899. if (camera) {
  31900. this._camera = camera;
  31901. }
  31902. else {
  31903. this._camera = this._scene.activeCamera;
  31904. }
  31905. this._showUI = showUI;
  31906. var engine = this._scene.getEngine();
  31907. this._globalDiv = document.createElement("div");
  31908. this._rootElement = rootElement || document.body;
  31909. this._rootElement.appendChild(this._globalDiv);
  31910. this._generateDOMelements();
  31911. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31912. this._syncPositions();
  31913. this._scene.registerBeforeRender(this._syncData);
  31914. this._scene.registerAfterRender(this._syncUI);
  31915. };
  31916. DebugLayer.prototype._clearLabels = function () {
  31917. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31918. for (var index = 0; index < this._scene.meshes.length; index++) {
  31919. var mesh = this._scene.meshes[index];
  31920. mesh.renderOverlay = false;
  31921. }
  31922. };
  31923. DebugLayer.prototype._generateheader = function (root, text) {
  31924. var header = document.createElement("div");
  31925. header.innerHTML = text + "&nbsp;";
  31926. header.style.textAlign = "right";
  31927. header.style.width = "100%";
  31928. header.style.color = "white";
  31929. header.style.backgroundColor = "Black";
  31930. header.style.padding = "5px 5px 4px 0px";
  31931. header.style.marginLeft = "-5px";
  31932. header.style.fontWeight = "bold";
  31933. root.appendChild(header);
  31934. };
  31935. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31936. var label = document.createElement("label");
  31937. label.style.display = "inline";
  31938. label.innerHTML = title;
  31939. label.style.color = color;
  31940. root.appendChild(label);
  31941. root.appendChild(document.createElement("br"));
  31942. };
  31943. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31944. if (tag === void 0) { tag = null; }
  31945. var label = document.createElement("label");
  31946. label.style.display = "inline";
  31947. var boundingBoxesCheckbox = document.createElement("input");
  31948. boundingBoxesCheckbox.type = "checkbox";
  31949. boundingBoxesCheckbox.checked = initialState;
  31950. boundingBoxesCheckbox.style.display = "inline";
  31951. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  31952. boundingBoxesCheckbox.style.verticalAlign = "sub";
  31953. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31954. task(evt.target, tag);
  31955. });
  31956. label.appendChild(boundingBoxesCheckbox);
  31957. var container = document.createElement("span");
  31958. var leftPart = document.createElement("span");
  31959. var rightPart = document.createElement("span");
  31960. rightPart.style.cssFloat = "right";
  31961. leftPart.innerHTML = leftTitle;
  31962. rightPart.innerHTML = rightTitle;
  31963. rightPart.style.fontSize = "12px";
  31964. rightPart.style.maxWidth = "200px";
  31965. container.appendChild(leftPart);
  31966. container.appendChild(rightPart);
  31967. label.appendChild(container);
  31968. root.appendChild(label);
  31969. root.appendChild(document.createElement("br"));
  31970. };
  31971. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31972. if (tag === void 0) { tag = null; }
  31973. var label = document.createElement("label");
  31974. label.style.display = "inline";
  31975. var checkBox = document.createElement("input");
  31976. checkBox.type = "checkbox";
  31977. checkBox.checked = initialState;
  31978. checkBox.style.display = "inline";
  31979. checkBox.style.margin = "0px 5px 0px 0px";
  31980. checkBox.style.verticalAlign = "sub";
  31981. checkBox.addEventListener("change", function (evt) {
  31982. task(evt.target, tag);
  31983. });
  31984. label.appendChild(checkBox);
  31985. label.appendChild(document.createTextNode(title));
  31986. root.appendChild(label);
  31987. root.appendChild(document.createElement("br"));
  31988. };
  31989. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31990. if (tag === void 0) { tag = null; }
  31991. var button = document.createElement("button");
  31992. button.innerHTML = title;
  31993. button.style.height = "24px";
  31994. button.style.width = "150px";
  31995. button.style.marginBottom = "5px";
  31996. button.style.color = "#444444";
  31997. button.style.border = "1px solid white";
  31998. button.className = "debugLayerButton";
  31999. button.addEventListener("click", function (evt) {
  32000. task(evt.target, tag);
  32001. });
  32002. root.appendChild(button);
  32003. root.appendChild(document.createElement("br"));
  32004. };
  32005. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32006. if (tag === void 0) { tag = null; }
  32007. var label = document.createElement("label");
  32008. label.style.display = "inline";
  32009. var boundingBoxesRadio = document.createElement("input");
  32010. boundingBoxesRadio.type = "radio";
  32011. boundingBoxesRadio.name = name;
  32012. boundingBoxesRadio.checked = initialState;
  32013. boundingBoxesRadio.style.display = "inline";
  32014. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32015. boundingBoxesRadio.style.verticalAlign = "sub";
  32016. boundingBoxesRadio.addEventListener("change", function (evt) {
  32017. task(evt.target, tag);
  32018. });
  32019. label.appendChild(boundingBoxesRadio);
  32020. label.appendChild(document.createTextNode(title));
  32021. root.appendChild(label);
  32022. root.appendChild(document.createElement("br"));
  32023. };
  32024. DebugLayer.prototype._generateDOMelements = function () {
  32025. var _this = this;
  32026. this._globalDiv.id = "DebugLayer";
  32027. this._globalDiv.style.position = "absolute";
  32028. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32029. this._globalDiv.style.fontSize = "14px";
  32030. this._globalDiv.style.color = "white";
  32031. // Drawing canvas
  32032. this._drawingCanvas = document.createElement("canvas");
  32033. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32034. this._drawingCanvas.style.position = "absolute";
  32035. this._drawingCanvas.style.pointerEvents = "none";
  32036. this._drawingCanvas.style.backgroundColor = "transparent";
  32037. this._drawingContext = this._drawingCanvas.getContext("2d");
  32038. this._globalDiv.appendChild(this._drawingCanvas);
  32039. if (this._showUI) {
  32040. var background = "rgba(128, 128, 128, 0.4)";
  32041. var border = "rgb(180, 180, 180) solid 1px";
  32042. // Stats
  32043. this._statsDiv = document.createElement("div");
  32044. this._statsDiv.id = "DebugLayerStats";
  32045. this._statsDiv.style.border = border;
  32046. this._statsDiv.style.position = "absolute";
  32047. this._statsDiv.style.background = background;
  32048. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32049. this._generateheader(this._statsDiv, "STATISTICS");
  32050. this._statsSubsetDiv = document.createElement("div");
  32051. this._statsSubsetDiv.style.paddingTop = "5px";
  32052. this._statsSubsetDiv.style.paddingBottom = "5px";
  32053. this._statsSubsetDiv.style.overflowY = "auto";
  32054. this._statsDiv.appendChild(this._statsSubsetDiv);
  32055. // Tree
  32056. this._treeDiv = document.createElement("div");
  32057. this._treeDiv.id = "DebugLayerTree";
  32058. this._treeDiv.style.border = border;
  32059. this._treeDiv.style.position = "absolute";
  32060. this._treeDiv.style.background = background;
  32061. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32062. this._treeDiv.style.display = "none";
  32063. this._generateheader(this._treeDiv, "MESHES TREE");
  32064. this._treeSubsetDiv = document.createElement("div");
  32065. this._treeSubsetDiv.style.paddingTop = "5px";
  32066. this._treeSubsetDiv.style.paddingRight = "5px";
  32067. this._treeSubsetDiv.style.overflowY = "auto";
  32068. this._treeSubsetDiv.style.maxHeight = "300px";
  32069. this._treeDiv.appendChild(this._treeSubsetDiv);
  32070. this._needToRefreshMeshesTree = true;
  32071. // Logs
  32072. this._logDiv = document.createElement("div");
  32073. this._logDiv.style.border = border;
  32074. this._logDiv.id = "DebugLayerLogs";
  32075. this._logDiv.style.position = "absolute";
  32076. this._logDiv.style.background = background;
  32077. this._logDiv.style.padding = "0px 0px 0px 5px";
  32078. this._logDiv.style.display = "none";
  32079. this._generateheader(this._logDiv, "LOGS");
  32080. this._logSubsetDiv = document.createElement("div");
  32081. this._logSubsetDiv.style.height = "127px";
  32082. this._logSubsetDiv.style.paddingTop = "5px";
  32083. this._logSubsetDiv.style.overflowY = "auto";
  32084. this._logSubsetDiv.style.fontSize = "12px";
  32085. this._logSubsetDiv.style.fontFamily = "consolas";
  32086. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32087. this._logDiv.appendChild(this._logSubsetDiv);
  32088. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32089. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32090. };
  32091. // Options
  32092. this._optionsDiv = document.createElement("div");
  32093. this._optionsDiv.id = "DebugLayerOptions";
  32094. this._optionsDiv.style.border = border;
  32095. this._optionsDiv.style.position = "absolute";
  32096. this._optionsDiv.style.background = background;
  32097. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32098. this._optionsDiv.style.overflowY = "auto";
  32099. this._generateheader(this._optionsDiv, "OPTIONS");
  32100. this._optionsSubsetDiv = document.createElement("div");
  32101. this._optionsSubsetDiv.style.paddingTop = "5px";
  32102. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32103. this._optionsSubsetDiv.style.overflowY = "auto";
  32104. this._optionsSubsetDiv.style.maxHeight = "200px";
  32105. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32106. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32107. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32108. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32109. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32110. _this._displayTree = element.checked;
  32111. _this._needToRefreshMeshesTree = true;
  32112. });
  32113. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32114. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32115. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32116. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32117. _this._labelsEnabled = element.checked;
  32118. if (!_this._labelsEnabled) {
  32119. _this._clearLabels();
  32120. }
  32121. });
  32122. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32123. if (element.checked) {
  32124. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32125. }
  32126. else {
  32127. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32128. }
  32129. });
  32130. ;
  32131. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32132. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32133. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32134. if (element.checked) {
  32135. _this._scene.forceWireframe = false;
  32136. _this._scene.forcePointsCloud = false;
  32137. }
  32138. });
  32139. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32140. if (element.checked) {
  32141. _this._scene.forceWireframe = true;
  32142. _this._scene.forcePointsCloud = false;
  32143. }
  32144. });
  32145. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32146. if (element.checked) {
  32147. _this._scene.forceWireframe = false;
  32148. _this._scene.forcePointsCloud = true;
  32149. }
  32150. });
  32151. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32152. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32153. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32154. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32155. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32156. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32157. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32158. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32159. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32160. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32161. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32162. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32163. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32164. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32165. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32166. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32167. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32168. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32169. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32170. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32171. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32172. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32173. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32174. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32175. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32176. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32177. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32178. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32179. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32180. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32181. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32182. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32183. if (element.checked) {
  32184. _this._scene.headphone = true;
  32185. }
  32186. });
  32187. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32188. if (element.checked) {
  32189. _this._scene.headphone = false;
  32190. }
  32191. });
  32192. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32193. _this._scene.audioEnabled = !element.checked;
  32194. });
  32195. }
  32196. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32197. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32198. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32199. if (!element.checked) {
  32200. _this._clearSkeletonViewers();
  32201. return;
  32202. }
  32203. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32204. var mesh = _this._scene.meshes[index];
  32205. if (mesh.skeleton) {
  32206. var found = false;
  32207. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32208. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32209. found = true;
  32210. break;
  32211. }
  32212. }
  32213. if (found) {
  32214. continue;
  32215. }
  32216. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32217. viewer.isEnabled = true;
  32218. _this._skeletonViewers.push(viewer);
  32219. }
  32220. }
  32221. });
  32222. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32223. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32224. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32225. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32226. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32227. if (_this._camera) {
  32228. console.log(_this._camera);
  32229. }
  32230. else {
  32231. console.warn("No camera defined, or debug layer created before camera creation!");
  32232. }
  32233. });
  32234. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32235. this._globalDiv.appendChild(this._statsDiv);
  32236. this._globalDiv.appendChild(this._logDiv);
  32237. this._globalDiv.appendChild(this._optionsDiv);
  32238. this._globalDiv.appendChild(this._treeDiv);
  32239. }
  32240. };
  32241. DebugLayer.prototype._displayStats = function () {
  32242. var scene = this._scene;
  32243. var engine = scene.getEngine();
  32244. var glInfo = engine.getGlInfo();
  32245. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32246. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32247. + "<b>Count</b><br>"
  32248. + "Total meshes: " + scene.meshes.length + "<br>"
  32249. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32250. + "Total materials: " + scene.materials.length + "<br>"
  32251. + "Total textures: " + scene.textures.length + "<br>"
  32252. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32253. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32254. + "Active bones: " + scene.getActiveBones() + "<br>"
  32255. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32256. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  32257. + "<b>Duration</b><br>"
  32258. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32259. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32260. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32261. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32262. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32263. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32264. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32265. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  32266. + "</div>"
  32267. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32268. + "<b>Extensions</b><br>"
  32269. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32270. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32271. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32272. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32273. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32274. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32275. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32276. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32277. + "</div><br>"
  32278. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32279. + "<b>Caps.</b><br>"
  32280. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32281. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32282. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32283. + "<b>Info</b><br>"
  32284. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32285. + glInfo.version + "<br>"
  32286. + "</div><br>"
  32287. + glInfo.renderer + "<br>";
  32288. if (this.customStatsFunction) {
  32289. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32290. }
  32291. };
  32292. return DebugLayer;
  32293. })();
  32294. BABYLON.DebugLayer = DebugLayer;
  32295. })(BABYLON || (BABYLON = {}));
  32296. var BABYLON;
  32297. (function (BABYLON) {
  32298. var DefaultLoadingScreen = (function () {
  32299. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32300. var _this = this;
  32301. if (_loadingText === void 0) { _loadingText = ""; }
  32302. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32303. this._renderingCanvas = _renderingCanvas;
  32304. this._loadingText = _loadingText;
  32305. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32306. // Resize
  32307. this._resizeLoadingUI = function () {
  32308. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32309. _this._loadingDiv.style.position = "absolute";
  32310. _this._loadingDiv.style.left = canvasRect.left + "px";
  32311. _this._loadingDiv.style.top = canvasRect.top + "px";
  32312. _this._loadingDiv.style.width = canvasRect.width + "px";
  32313. _this._loadingDiv.style.height = canvasRect.height + "px";
  32314. };
  32315. }
  32316. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32317. var _this = this;
  32318. if (this._loadingDiv) {
  32319. // Do not add a loading screen if there is already one
  32320. return;
  32321. }
  32322. this._loadingDiv = document.createElement("div");
  32323. this._loadingDiv.id = "babylonjsLoadingDiv";
  32324. this._loadingDiv.style.opacity = "0";
  32325. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32326. // Loading text
  32327. this._loadingTextDiv = document.createElement("div");
  32328. this._loadingTextDiv.style.position = "absolute";
  32329. this._loadingTextDiv.style.left = "0";
  32330. this._loadingTextDiv.style.top = "50%";
  32331. this._loadingTextDiv.style.marginTop = "80px";
  32332. this._loadingTextDiv.style.width = "100%";
  32333. this._loadingTextDiv.style.height = "20px";
  32334. this._loadingTextDiv.style.fontFamily = "Arial";
  32335. this._loadingTextDiv.style.fontSize = "14px";
  32336. this._loadingTextDiv.style.color = "white";
  32337. this._loadingTextDiv.style.textAlign = "center";
  32338. this._loadingTextDiv.innerHTML = "Loading";
  32339. this._loadingDiv.appendChild(this._loadingTextDiv);
  32340. //set the predefined text
  32341. this._loadingTextDiv.innerHTML = this._loadingText;
  32342. // Loading img
  32343. var imgBack = new Image();
  32344. 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==";
  32345. imgBack.style.position = "absolute";
  32346. imgBack.style.left = "50%";
  32347. imgBack.style.top = "50%";
  32348. imgBack.style.marginLeft = "-50px";
  32349. imgBack.style.marginTop = "-50px";
  32350. imgBack.style.transition = "transform 1.0s ease";
  32351. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32352. var deg = 360;
  32353. var onTransitionEnd = function () {
  32354. deg += 360;
  32355. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32356. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32357. };
  32358. imgBack.addEventListener("transitionend", onTransitionEnd);
  32359. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32360. this._loadingDiv.appendChild(imgBack);
  32361. // front image
  32362. var imgFront = new Image();
  32363. 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=";
  32364. imgFront.style.position = "absolute";
  32365. imgFront.style.left = "50%";
  32366. imgFront.style.top = "50%";
  32367. imgFront.style.marginLeft = "-50px";
  32368. imgFront.style.marginTop = "-50px";
  32369. this._loadingDiv.appendChild(imgFront);
  32370. this._resizeLoadingUI();
  32371. window.addEventListener("resize", this._resizeLoadingUI);
  32372. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32373. document.body.appendChild(this._loadingDiv);
  32374. setTimeout(function () {
  32375. _this._loadingDiv.style.opacity = "1";
  32376. imgBack.style.transform = "rotateZ(360deg)";
  32377. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32378. }, 0);
  32379. };
  32380. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32381. var _this = this;
  32382. if (!this._loadingDiv) {
  32383. return;
  32384. }
  32385. var onTransitionEnd = function () {
  32386. if (!_this._loadingDiv) {
  32387. return;
  32388. }
  32389. document.body.removeChild(_this._loadingDiv);
  32390. window.removeEventListener("resize", _this._resizeLoadingUI);
  32391. _this._loadingDiv = null;
  32392. };
  32393. this._loadingDiv.style.opacity = "0";
  32394. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32395. };
  32396. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32397. set: function (text) {
  32398. this._loadingText = text;
  32399. if (this._loadingTextDiv) {
  32400. this._loadingTextDiv.innerHTML = this._loadingText;
  32401. }
  32402. },
  32403. enumerable: true,
  32404. configurable: true
  32405. });
  32406. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32407. get: function () {
  32408. return this._loadingDivBackgroundColor;
  32409. },
  32410. set: function (color) {
  32411. this._loadingDivBackgroundColor = color;
  32412. if (!this._loadingDiv) {
  32413. return;
  32414. }
  32415. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32416. },
  32417. enumerable: true,
  32418. configurable: true
  32419. });
  32420. return DefaultLoadingScreen;
  32421. })();
  32422. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  32423. })(BABYLON || (BABYLON = {}));
  32424. var BABYLON;
  32425. (function (BABYLON) {
  32426. var AudioEngine = (function () {
  32427. function AudioEngine() {
  32428. this._audioContext = null;
  32429. this._audioContextInitialized = false;
  32430. this.canUseWebAudio = false;
  32431. this.WarnedWebAudioUnsupported = false;
  32432. this.unlocked = false;
  32433. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32434. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32435. this.canUseWebAudio = true;
  32436. }
  32437. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  32438. this._unlockiOSaudio();
  32439. }
  32440. else {
  32441. this.unlocked = true;
  32442. }
  32443. }
  32444. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32445. get: function () {
  32446. if (!this._audioContextInitialized) {
  32447. this._initializeAudioContext();
  32448. }
  32449. return this._audioContext;
  32450. },
  32451. enumerable: true,
  32452. configurable: true
  32453. });
  32454. AudioEngine.prototype._unlockiOSaudio = function () {
  32455. var _this = this;
  32456. var unlockaudio = function () {
  32457. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  32458. var source = _this.audioContext.createBufferSource();
  32459. source.buffer = buffer;
  32460. source.connect(_this.audioContext.destination);
  32461. source.start(0);
  32462. setTimeout(function () {
  32463. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  32464. _this.unlocked = true;
  32465. window.removeEventListener('touchend', unlockaudio, false);
  32466. if (_this.onAudioUnlocked) {
  32467. _this.onAudioUnlocked();
  32468. }
  32469. }
  32470. }, 0);
  32471. };
  32472. window.addEventListener('touchend', unlockaudio, false);
  32473. };
  32474. AudioEngine.prototype._initializeAudioContext = function () {
  32475. try {
  32476. if (this.canUseWebAudio) {
  32477. this._audioContext = new AudioContext();
  32478. // create a global volume gain node
  32479. this.masterGain = this._audioContext.createGain();
  32480. this.masterGain.gain.value = 1;
  32481. this.masterGain.connect(this._audioContext.destination);
  32482. this._audioContextInitialized = true;
  32483. }
  32484. }
  32485. catch (e) {
  32486. this.canUseWebAudio = false;
  32487. BABYLON.Tools.Error("Web Audio: " + e.message);
  32488. }
  32489. };
  32490. AudioEngine.prototype.dispose = function () {
  32491. if (this.canUseWebAudio && this._audioContextInitialized) {
  32492. if (this._connectedAnalyser) {
  32493. this._connectedAnalyser.stopDebugCanvas();
  32494. this._connectedAnalyser.dispose();
  32495. this.masterGain.disconnect();
  32496. this.masterGain.connect(this._audioContext.destination);
  32497. this._connectedAnalyser = null;
  32498. }
  32499. this.masterGain.gain.value = 1;
  32500. }
  32501. this.WarnedWebAudioUnsupported = false;
  32502. };
  32503. AudioEngine.prototype.getGlobalVolume = function () {
  32504. if (this.canUseWebAudio && this._audioContextInitialized) {
  32505. return this.masterGain.gain.value;
  32506. }
  32507. else {
  32508. return -1;
  32509. }
  32510. };
  32511. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  32512. if (this.canUseWebAudio && this._audioContextInitialized) {
  32513. this.masterGain.gain.value = newVolume;
  32514. }
  32515. };
  32516. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  32517. if (this._connectedAnalyser) {
  32518. this._connectedAnalyser.stopDebugCanvas();
  32519. }
  32520. if (this.canUseWebAudio && this._audioContextInitialized) {
  32521. this._connectedAnalyser = analyser;
  32522. this.masterGain.disconnect();
  32523. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  32524. }
  32525. };
  32526. return AudioEngine;
  32527. })();
  32528. BABYLON.AudioEngine = AudioEngine;
  32529. })(BABYLON || (BABYLON = {}));
  32530. var BABYLON;
  32531. (function (BABYLON) {
  32532. var Sound = (function () {
  32533. /**
  32534. * Create a sound and attach it to a scene
  32535. * @param name Name of your sound
  32536. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  32537. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  32538. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  32539. */
  32540. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  32541. var _this = this;
  32542. this.autoplay = false;
  32543. this.loop = false;
  32544. this.useCustomAttenuation = false;
  32545. this.spatialSound = false;
  32546. this.refDistance = 1;
  32547. this.rolloffFactor = 1;
  32548. this.maxDistance = 100;
  32549. this.distanceModel = "linear";
  32550. this._panningModel = "equalpower";
  32551. this._playbackRate = 1;
  32552. this._streaming = false;
  32553. this._startTime = 0;
  32554. this._startOffset = 0;
  32555. this._position = BABYLON.Vector3.Zero();
  32556. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  32557. this._volume = 1;
  32558. this._isLoaded = false;
  32559. this._isReadyToPlay = false;
  32560. this.isPlaying = false;
  32561. this.isPaused = false;
  32562. this._isDirectional = false;
  32563. // Used if you'd like to create a directional sound.
  32564. // If not set, the sound will be omnidirectional
  32565. this._coneInnerAngle = 360;
  32566. this._coneOuterAngle = 360;
  32567. this._coneOuterGain = 0;
  32568. this._isOutputConnected = false;
  32569. this.name = name;
  32570. this._scene = scene;
  32571. this._readyToPlayCallback = readyToPlayCallback;
  32572. // Default custom attenuation function is a linear attenuation
  32573. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  32574. if (currentDistance < maxDistance) {
  32575. return currentVolume * (1 - currentDistance / maxDistance);
  32576. }
  32577. else {
  32578. return 0;
  32579. }
  32580. };
  32581. if (options) {
  32582. this.autoplay = options.autoplay || false;
  32583. this.loop = options.loop || false;
  32584. // if volume === 0, we need another way to check this option
  32585. if (options.volume !== undefined) {
  32586. this._volume = options.volume;
  32587. }
  32588. this.spatialSound = options.spatialSound || false;
  32589. this.maxDistance = options.maxDistance || 100;
  32590. this.useCustomAttenuation = options.useCustomAttenuation || false;
  32591. this.rolloffFactor = options.rolloffFactor || 1;
  32592. this.refDistance = options.refDistance || 1;
  32593. this.distanceModel = options.distanceModel || "linear";
  32594. this._playbackRate = options.playbackRate || 1;
  32595. this._streaming = options.streaming || false;
  32596. }
  32597. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32598. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  32599. this._soundGain.gain.value = this._volume;
  32600. this._inputAudioNode = this._soundGain;
  32601. this._ouputAudioNode = this._soundGain;
  32602. if (this.spatialSound) {
  32603. this._createSpatialParameters();
  32604. }
  32605. this._scene.mainSoundTrack.AddSound(this);
  32606. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  32607. if (urlOrArrayBuffer) {
  32608. // If it's an URL
  32609. if (typeof (urlOrArrayBuffer) === "string") {
  32610. // Loading sound using XHR2
  32611. if (!this._streaming) {
  32612. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  32613. }
  32614. else {
  32615. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  32616. this._htmlAudioElement.controls = false;
  32617. this._htmlAudioElement.loop = this.loop;
  32618. this._htmlAudioElement.crossOrigin = "anonymous";
  32619. this._htmlAudioElement.preload = "auto";
  32620. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  32621. _this._isReadyToPlay = true;
  32622. if (_this.autoplay) {
  32623. _this.play();
  32624. }
  32625. if (_this._readyToPlayCallback) {
  32626. _this._readyToPlayCallback();
  32627. }
  32628. });
  32629. document.body.appendChild(this._htmlAudioElement);
  32630. }
  32631. }
  32632. else {
  32633. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  32634. if (urlOrArrayBuffer.byteLength > 0) {
  32635. this._soundLoaded(urlOrArrayBuffer);
  32636. }
  32637. }
  32638. else {
  32639. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  32640. }
  32641. }
  32642. }
  32643. }
  32644. else {
  32645. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  32646. this._scene.mainSoundTrack.AddSound(this);
  32647. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  32648. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  32649. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  32650. }
  32651. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  32652. if (this._readyToPlayCallback) {
  32653. window.setTimeout(function () {
  32654. _this._readyToPlayCallback();
  32655. }, 1000);
  32656. }
  32657. }
  32658. }
  32659. Sound.prototype.dispose = function () {
  32660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  32661. if (this.isPlaying) {
  32662. this.stop();
  32663. }
  32664. this._isReadyToPlay = false;
  32665. if (this.soundTrackId === -1) {
  32666. this._scene.mainSoundTrack.RemoveSound(this);
  32667. }
  32668. else {
  32669. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  32670. }
  32671. if (this._soundGain) {
  32672. this._soundGain.disconnect();
  32673. this._soundGain = null;
  32674. }
  32675. if (this._soundPanner) {
  32676. this._soundPanner.disconnect();
  32677. this._soundPanner = null;
  32678. }
  32679. if (this._soundSource) {
  32680. this._soundSource.disconnect();
  32681. this._soundSource = null;
  32682. }
  32683. this._audioBuffer = null;
  32684. if (this._htmlAudioElement) {
  32685. this._htmlAudioElement.pause();
  32686. this._htmlAudioElement.src = "";
  32687. document.body.removeChild(this._htmlAudioElement);
  32688. }
  32689. if (this._connectedMesh) {
  32690. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32691. this._connectedMesh = null;
  32692. }
  32693. }
  32694. };
  32695. Sound.prototype._soundLoaded = function (audioData) {
  32696. var _this = this;
  32697. this._isLoaded = true;
  32698. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  32699. _this._audioBuffer = buffer;
  32700. _this._isReadyToPlay = true;
  32701. if (_this.autoplay) {
  32702. _this.play();
  32703. }
  32704. if (_this._readyToPlayCallback) {
  32705. _this._readyToPlayCallback();
  32706. }
  32707. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  32708. };
  32709. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  32710. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32711. this._audioBuffer = audioBuffer;
  32712. this._isReadyToPlay = true;
  32713. }
  32714. };
  32715. Sound.prototype.updateOptions = function (options) {
  32716. if (options) {
  32717. this.loop = options.loop || this.loop;
  32718. this.maxDistance = options.maxDistance || this.maxDistance;
  32719. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  32720. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  32721. this.refDistance = options.refDistance || this.refDistance;
  32722. this.distanceModel = options.distanceModel || this.distanceModel;
  32723. this._playbackRate = options.playbackRate || this._playbackRate;
  32724. this._updateSpatialParameters();
  32725. if (this.isPlaying) {
  32726. if (this._streaming) {
  32727. this._htmlAudioElement.playbackRate = this._playbackRate;
  32728. }
  32729. else {
  32730. this._soundSource.playbackRate.value = this._playbackRate;
  32731. }
  32732. }
  32733. }
  32734. };
  32735. Sound.prototype._createSpatialParameters = function () {
  32736. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32737. if (this._scene.headphone) {
  32738. this._panningModel = "HRTF";
  32739. }
  32740. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  32741. this._updateSpatialParameters();
  32742. this._soundPanner.connect(this._ouputAudioNode);
  32743. this._inputAudioNode = this._soundPanner;
  32744. }
  32745. };
  32746. Sound.prototype._updateSpatialParameters = function () {
  32747. if (this.spatialSound) {
  32748. if (this.useCustomAttenuation) {
  32749. // Tricks to disable in a way embedded Web Audio attenuation
  32750. this._soundPanner.distanceModel = "linear";
  32751. this._soundPanner.maxDistance = Number.MAX_VALUE;
  32752. this._soundPanner.refDistance = 1;
  32753. this._soundPanner.rolloffFactor = 1;
  32754. this._soundPanner.panningModel = this._panningModel;
  32755. }
  32756. else {
  32757. this._soundPanner.distanceModel = this.distanceModel;
  32758. this._soundPanner.maxDistance = this.maxDistance;
  32759. this._soundPanner.refDistance = this.refDistance;
  32760. this._soundPanner.rolloffFactor = this.rolloffFactor;
  32761. this._soundPanner.panningModel = this._panningModel;
  32762. }
  32763. }
  32764. };
  32765. Sound.prototype.switchPanningModelToHRTF = function () {
  32766. this._panningModel = "HRTF";
  32767. this._switchPanningModel();
  32768. };
  32769. Sound.prototype.switchPanningModelToEqualPower = function () {
  32770. this._panningModel = "equalpower";
  32771. this._switchPanningModel();
  32772. };
  32773. Sound.prototype._switchPanningModel = function () {
  32774. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  32775. this._soundPanner.panningModel = this._panningModel;
  32776. }
  32777. };
  32778. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  32779. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32780. if (this._isOutputConnected) {
  32781. this._ouputAudioNode.disconnect();
  32782. }
  32783. this._ouputAudioNode.connect(soundTrackAudioNode);
  32784. this._isOutputConnected = true;
  32785. }
  32786. };
  32787. /**
  32788. * Transform this sound into a directional source
  32789. * @param coneInnerAngle Size of the inner cone in degree
  32790. * @param coneOuterAngle Size of the outer cone in degree
  32791. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  32792. */
  32793. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  32794. if (coneOuterAngle < coneInnerAngle) {
  32795. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  32796. return;
  32797. }
  32798. this._coneInnerAngle = coneInnerAngle;
  32799. this._coneOuterAngle = coneOuterAngle;
  32800. this._coneOuterGain = coneOuterGain;
  32801. this._isDirectional = true;
  32802. if (this.isPlaying && this.loop) {
  32803. this.stop();
  32804. this.play();
  32805. }
  32806. };
  32807. Sound.prototype.setPosition = function (newPosition) {
  32808. this._position = newPosition;
  32809. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  32810. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  32811. }
  32812. };
  32813. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  32814. this._localDirection = newLocalDirection;
  32815. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  32816. this._updateDirection();
  32817. }
  32818. };
  32819. Sound.prototype._updateDirection = function () {
  32820. var mat = this._connectedMesh.getWorldMatrix();
  32821. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  32822. direction.normalize();
  32823. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  32824. };
  32825. Sound.prototype.updateDistanceFromListener = function () {
  32826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  32827. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  32828. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  32829. }
  32830. };
  32831. Sound.prototype.setAttenuationFunction = function (callback) {
  32832. this._customAttenuationFunction = callback;
  32833. };
  32834. /**
  32835. * Play the sound
  32836. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  32837. */
  32838. Sound.prototype.play = function (time) {
  32839. var _this = this;
  32840. if (this._isReadyToPlay && this._scene.audioEnabled) {
  32841. try {
  32842. if (this._startOffset < 0) {
  32843. time = -this._startOffset;
  32844. this._startOffset = 0;
  32845. }
  32846. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  32847. if (!this._soundSource || !this._streamingSource) {
  32848. if (this.spatialSound) {
  32849. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  32850. if (this._isDirectional) {
  32851. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  32852. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  32853. this._soundPanner.coneOuterGain = this._coneOuterGain;
  32854. if (this._connectedMesh) {
  32855. this._updateDirection();
  32856. }
  32857. else {
  32858. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  32859. }
  32860. }
  32861. }
  32862. }
  32863. if (this._streaming) {
  32864. if (!this._streamingSource) {
  32865. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  32866. this._htmlAudioElement.onended = function () { _this._onended(); };
  32867. this._htmlAudioElement.playbackRate = this._playbackRate;
  32868. }
  32869. this._streamingSource.disconnect();
  32870. this._streamingSource.connect(this._inputAudioNode);
  32871. this._htmlAudioElement.play();
  32872. }
  32873. else {
  32874. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  32875. this._soundSource.buffer = this._audioBuffer;
  32876. this._soundSource.connect(this._inputAudioNode);
  32877. this._soundSource.loop = this.loop;
  32878. this._soundSource.playbackRate.value = this._playbackRate;
  32879. this._soundSource.onended = function () { _this._onended(); };
  32880. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  32881. }
  32882. this._startTime = startTime;
  32883. this.isPlaying = true;
  32884. this.isPaused = false;
  32885. }
  32886. catch (ex) {
  32887. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  32888. }
  32889. }
  32890. };
  32891. Sound.prototype._onended = function () {
  32892. this.isPlaying = false;
  32893. if (this.onended) {
  32894. this.onended();
  32895. }
  32896. };
  32897. /**
  32898. * Stop the sound
  32899. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  32900. */
  32901. Sound.prototype.stop = function (time) {
  32902. if (this.isPlaying) {
  32903. if (this._streaming) {
  32904. this._htmlAudioElement.pause();
  32905. // Test needed for Firefox or it will generate an Invalid State Error
  32906. if (this._htmlAudioElement.currentTime > 0) {
  32907. this._htmlAudioElement.currentTime = 0;
  32908. }
  32909. }
  32910. else {
  32911. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  32912. this._soundSource.stop(stopTime);
  32913. if (!this.isPaused) {
  32914. this._startOffset = 0;
  32915. }
  32916. }
  32917. this.isPlaying = false;
  32918. }
  32919. };
  32920. Sound.prototype.pause = function () {
  32921. if (this.isPlaying) {
  32922. this.isPaused = true;
  32923. if (this._streaming) {
  32924. this._htmlAudioElement.pause();
  32925. }
  32926. else {
  32927. this.stop(0);
  32928. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  32929. }
  32930. }
  32931. };
  32932. Sound.prototype.setVolume = function (newVolume, time) {
  32933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32934. if (time) {
  32935. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  32936. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  32937. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  32938. }
  32939. else {
  32940. this._soundGain.gain.value = newVolume;
  32941. }
  32942. }
  32943. this._volume = newVolume;
  32944. };
  32945. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  32946. this._playbackRate = newPlaybackRate;
  32947. if (this.isPlaying) {
  32948. if (this._streaming) {
  32949. this._htmlAudioElement.playbackRate = this._playbackRate;
  32950. }
  32951. else {
  32952. this._soundSource.playbackRate.value = this._playbackRate;
  32953. }
  32954. }
  32955. };
  32956. Sound.prototype.getVolume = function () {
  32957. return this._volume;
  32958. };
  32959. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  32960. var _this = this;
  32961. if (this._connectedMesh) {
  32962. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32963. this._registerFunc = null;
  32964. }
  32965. this._connectedMesh = meshToConnectTo;
  32966. if (!this.spatialSound) {
  32967. this.spatialSound = true;
  32968. this._createSpatialParameters();
  32969. if (this.isPlaying && this.loop) {
  32970. this.stop();
  32971. this.play();
  32972. }
  32973. }
  32974. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  32975. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  32976. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  32977. };
  32978. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  32979. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  32980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  32981. this._updateDirection();
  32982. }
  32983. };
  32984. Sound.prototype.clone = function () {
  32985. var _this = this;
  32986. if (!this._streaming) {
  32987. var setBufferAndRun = function () {
  32988. if (_this._isReadyToPlay) {
  32989. clonedSound._audioBuffer = _this.getAudioBuffer();
  32990. clonedSound._isReadyToPlay = true;
  32991. if (clonedSound.autoplay) {
  32992. clonedSound.play();
  32993. }
  32994. }
  32995. else {
  32996. window.setTimeout(setBufferAndRun, 300);
  32997. }
  32998. };
  32999. var currentOptions = {
  33000. autoplay: this.autoplay, loop: this.loop,
  33001. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33002. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33003. refDistance: this.refDistance, distanceModel: this.distanceModel
  33004. };
  33005. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33006. if (this.useCustomAttenuation) {
  33007. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33008. }
  33009. clonedSound.setPosition(this._position);
  33010. clonedSound.setPlaybackRate(this._playbackRate);
  33011. setBufferAndRun();
  33012. return clonedSound;
  33013. }
  33014. else {
  33015. return null;
  33016. }
  33017. };
  33018. Sound.prototype.getAudioBuffer = function () {
  33019. return this._audioBuffer;
  33020. };
  33021. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33022. var soundName = parsedSound.name;
  33023. var soundUrl;
  33024. if (parsedSound.url) {
  33025. soundUrl = rootUrl + parsedSound.url;
  33026. }
  33027. else {
  33028. soundUrl = rootUrl + soundName;
  33029. }
  33030. var options = {
  33031. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33032. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33033. rolloffFactor: parsedSound.rolloffFactor,
  33034. refDistance: parsedSound.refDistance,
  33035. distanceModel: parsedSound.distanceModel,
  33036. playbackRate: parsedSound.playbackRate
  33037. };
  33038. var newSound;
  33039. if (!sourceSound) {
  33040. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33041. scene._addPendingData(newSound);
  33042. }
  33043. else {
  33044. var setBufferAndRun = function () {
  33045. if (sourceSound._isReadyToPlay) {
  33046. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33047. newSound._isReadyToPlay = true;
  33048. if (newSound.autoplay) {
  33049. newSound.play();
  33050. }
  33051. }
  33052. else {
  33053. window.setTimeout(setBufferAndRun, 300);
  33054. }
  33055. };
  33056. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33057. setBufferAndRun();
  33058. }
  33059. if (parsedSound.position) {
  33060. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33061. newSound.setPosition(soundPosition);
  33062. }
  33063. if (parsedSound.isDirectional) {
  33064. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33065. if (parsedSound.localDirectionToMesh) {
  33066. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33067. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33068. }
  33069. }
  33070. if (parsedSound.connectedMeshId) {
  33071. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33072. if (connectedMesh) {
  33073. newSound.attachToMesh(connectedMesh);
  33074. }
  33075. }
  33076. return newSound;
  33077. };
  33078. return Sound;
  33079. })();
  33080. BABYLON.Sound = Sound;
  33081. })(BABYLON || (BABYLON = {}));
  33082. var BABYLON;
  33083. (function (BABYLON) {
  33084. var SoundTrack = (function () {
  33085. function SoundTrack(scene, options) {
  33086. this.id = -1;
  33087. this._isMainTrack = false;
  33088. this._isInitialized = false;
  33089. this._scene = scene;
  33090. this.soundCollection = new Array();
  33091. this._options = options;
  33092. if (!this._isMainTrack) {
  33093. this._scene.soundTracks.push(this);
  33094. this.id = this._scene.soundTracks.length - 1;
  33095. }
  33096. }
  33097. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33098. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33099. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33100. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33101. if (this._options) {
  33102. if (this._options.volume) {
  33103. this._outputAudioNode.gain.value = this._options.volume;
  33104. }
  33105. if (this._options.mainTrack) {
  33106. this._isMainTrack = this._options.mainTrack;
  33107. }
  33108. }
  33109. this._isInitialized = true;
  33110. }
  33111. };
  33112. SoundTrack.prototype.dispose = function () {
  33113. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33114. if (this._connectedAnalyser) {
  33115. this._connectedAnalyser.stopDebugCanvas();
  33116. }
  33117. while (this.soundCollection.length) {
  33118. this.soundCollection[0].dispose();
  33119. }
  33120. if (this._outputAudioNode) {
  33121. this._outputAudioNode.disconnect();
  33122. }
  33123. this._outputAudioNode = null;
  33124. }
  33125. };
  33126. SoundTrack.prototype.AddSound = function (sound) {
  33127. if (!this._isInitialized) {
  33128. this._initializeSoundTrackAudioGraph();
  33129. }
  33130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33131. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33132. }
  33133. if (sound.soundTrackId) {
  33134. if (sound.soundTrackId === -1) {
  33135. this._scene.mainSoundTrack.RemoveSound(sound);
  33136. }
  33137. else {
  33138. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33139. }
  33140. }
  33141. this.soundCollection.push(sound);
  33142. sound.soundTrackId = this.id;
  33143. };
  33144. SoundTrack.prototype.RemoveSound = function (sound) {
  33145. var index = this.soundCollection.indexOf(sound);
  33146. if (index !== -1) {
  33147. this.soundCollection.splice(index, 1);
  33148. }
  33149. };
  33150. SoundTrack.prototype.setVolume = function (newVolume) {
  33151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33152. this._outputAudioNode.gain.value = newVolume;
  33153. }
  33154. };
  33155. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33157. for (var i = 0; i < this.soundCollection.length; i++) {
  33158. this.soundCollection[i].switchPanningModelToHRTF();
  33159. }
  33160. }
  33161. };
  33162. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33164. for (var i = 0; i < this.soundCollection.length; i++) {
  33165. this.soundCollection[i].switchPanningModelToEqualPower();
  33166. }
  33167. }
  33168. };
  33169. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33170. if (this._connectedAnalyser) {
  33171. this._connectedAnalyser.stopDebugCanvas();
  33172. }
  33173. this._connectedAnalyser = analyser;
  33174. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33175. this._outputAudioNode.disconnect();
  33176. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33177. }
  33178. };
  33179. return SoundTrack;
  33180. })();
  33181. BABYLON.SoundTrack = SoundTrack;
  33182. })(BABYLON || (BABYLON = {}));
  33183. var BABYLON;
  33184. (function (BABYLON) {
  33185. var SIMDVector3 = (function () {
  33186. function SIMDVector3() {
  33187. }
  33188. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33189. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33190. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33191. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33192. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33193. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33194. 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));
  33195. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33196. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33197. };
  33198. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33199. var v0 = SIMD.float32x4.splat(x);
  33200. var v1 = SIMD.float32x4.splat(y);
  33201. var v2 = SIMD.float32x4.splat(z);
  33202. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33203. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33204. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33205. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33206. 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));
  33207. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33208. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33209. };
  33210. return SIMDVector3;
  33211. })();
  33212. BABYLON.SIMDVector3 = SIMDVector3;
  33213. var SIMDMatrix = (function () {
  33214. function SIMDMatrix() {
  33215. }
  33216. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33217. if (offset === void 0) { offset = 0; }
  33218. var tm = this.m;
  33219. var om = other.m;
  33220. var om0 = SIMD.float32x4.load(om, 0);
  33221. var om1 = SIMD.float32x4.load(om, 4);
  33222. var om2 = SIMD.float32x4.load(om, 8);
  33223. var om3 = SIMD.float32x4.load(om, 12);
  33224. var tm0 = SIMD.float32x4.load(tm, 0);
  33225. 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)))));
  33226. var tm1 = SIMD.float32x4.load(tm, 4);
  33227. 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)))));
  33228. var tm2 = SIMD.float32x4.load(tm, 8);
  33229. 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)))));
  33230. var tm3 = SIMD.float32x4.load(tm, 12);
  33231. 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)))));
  33232. };
  33233. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33234. var src = this.m;
  33235. var dest = other.m;
  33236. var row0, row1, row2, row3;
  33237. var tmp1;
  33238. var minor0, minor1, minor2, minor3;
  33239. var det;
  33240. // Load the 4 rows
  33241. var src0 = SIMD.float32x4.load(src, 0);
  33242. var src1 = SIMD.float32x4.load(src, 4);
  33243. var src2 = SIMD.float32x4.load(src, 8);
  33244. var src3 = SIMD.float32x4.load(src, 12);
  33245. // Transpose the source matrix. Sort of. Not a true transpose operation
  33246. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33247. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33248. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33249. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33250. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33251. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33252. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33253. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33254. // This is a true transposition, but it will lead to an incorrect result
  33255. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33256. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33257. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33258. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33259. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33260. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33261. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33262. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33263. // ----
  33264. tmp1 = SIMD.float32x4.mul(row2, row3);
  33265. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33266. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33267. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33268. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33269. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33270. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33271. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33272. // ----
  33273. tmp1 = SIMD.float32x4.mul(row1, row2);
  33274. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33275. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33276. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33277. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33278. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33279. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33280. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33281. // ----
  33282. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33283. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33284. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33285. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33286. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33287. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33288. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33289. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33290. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33291. // ----
  33292. tmp1 = SIMD.float32x4.mul(row0, row1);
  33293. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33294. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33295. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33296. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33297. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33298. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33299. // ----
  33300. tmp1 = SIMD.float32x4.mul(row0, row3);
  33301. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33302. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33303. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33304. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33305. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33306. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33307. // ----
  33308. tmp1 = SIMD.float32x4.mul(row0, row2);
  33309. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33310. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33311. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33312. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33313. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33314. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33315. // Compute determinant
  33316. det = SIMD.float32x4.mul(row0, minor0);
  33317. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33318. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33319. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33320. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33321. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33322. // These shuffles aren't necessary if the faulty transposition is done
  33323. // up at the top of this function.
  33324. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33325. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33326. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33327. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33328. // Compute final values by multiplying with 1/det
  33329. minor0 = SIMD.float32x4.mul(det, minor0);
  33330. minor1 = SIMD.float32x4.mul(det, minor1);
  33331. minor2 = SIMD.float32x4.mul(det, minor2);
  33332. minor3 = SIMD.float32x4.mul(det, minor3);
  33333. SIMD.float32x4.store(dest, 0, minor0);
  33334. SIMD.float32x4.store(dest, 4, minor1);
  33335. SIMD.float32x4.store(dest, 8, minor2);
  33336. SIMD.float32x4.store(dest, 12, minor3);
  33337. return this;
  33338. };
  33339. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33340. var out = result.m;
  33341. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33342. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33343. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33344. // cc.kmVec3Subtract(f, pCenter, pEye);
  33345. var f = SIMD.float32x4.sub(center, eye);
  33346. // cc.kmVec3Normalize(f, f);
  33347. var tmp = SIMD.float32x4.mul(f, f);
  33348. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33349. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33350. // cc.kmVec3Assign(up, pUp);
  33351. // cc.kmVec3Normalize(up, up);
  33352. tmp = SIMD.float32x4.mul(up, up);
  33353. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33354. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33355. // cc.kmVec3Cross(s, f, up);
  33356. 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)));
  33357. // cc.kmVec3Normalize(s, s);
  33358. tmp = SIMD.float32x4.mul(s, s);
  33359. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33360. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33361. // cc.kmVec3Cross(u, s, f);
  33362. 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)));
  33363. // cc.kmVec3Normalize(s, s);
  33364. tmp = SIMD.float32x4.mul(s, s);
  33365. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33366. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33367. var zero = SIMD.float32x4.splat(0.0);
  33368. s = SIMD.float32x4.neg(s);
  33369. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33370. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33371. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33372. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33373. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33374. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33375. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33376. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33377. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33378. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33379. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33380. var b3 = SIMD.float32x4.neg(eye);
  33381. b3 = SIMD.float32x4.withW(b3, 1.0);
  33382. 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)))));
  33383. 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)))));
  33384. 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)))));
  33385. 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)))));
  33386. };
  33387. return SIMDMatrix;
  33388. })();
  33389. BABYLON.SIMDMatrix = SIMDMatrix;
  33390. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33391. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33392. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33393. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33394. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33395. var SIMDHelper = (function () {
  33396. function SIMDHelper() {
  33397. }
  33398. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33399. get: function () {
  33400. return SIMDHelper._isEnabled;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. SIMDHelper.DisableSIMD = function () {
  33406. // Replace functions
  33407. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33408. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33409. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33410. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33411. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33412. SIMDHelper._isEnabled = false;
  33413. };
  33414. SIMDHelper.EnableSIMD = function () {
  33415. if (window.SIMD === undefined) {
  33416. return;
  33417. }
  33418. // Replace functions
  33419. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  33420. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  33421. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  33422. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  33423. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  33424. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  33425. get: function () { return this._data[0]; },
  33426. set: function (value) {
  33427. if (!this._data) {
  33428. this._data = new Float32Array(3);
  33429. }
  33430. this._data[0] = value;
  33431. }
  33432. });
  33433. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  33434. get: function () { return this._data[1]; },
  33435. set: function (value) {
  33436. this._data[1] = value;
  33437. }
  33438. });
  33439. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  33440. get: function () { return this._data[2]; },
  33441. set: function (value) {
  33442. this._data[2] = value;
  33443. }
  33444. });
  33445. SIMDHelper._isEnabled = true;
  33446. };
  33447. SIMDHelper._isEnabled = false;
  33448. return SIMDHelper;
  33449. })();
  33450. BABYLON.SIMDHelper = SIMDHelper;
  33451. })(BABYLON || (BABYLON = {}));
  33452. var BABYLON;
  33453. (function (BABYLON) {
  33454. var ShaderMaterial = (function (_super) {
  33455. __extends(ShaderMaterial, _super);
  33456. function ShaderMaterial(name, scene, shaderPath, options) {
  33457. _super.call(this, name, scene);
  33458. this._textures = {};
  33459. this._floats = {};
  33460. this._floatsArrays = {};
  33461. this._colors3 = {};
  33462. this._colors4 = {};
  33463. this._vectors2 = {};
  33464. this._vectors3 = {};
  33465. this._vectors4 = {};
  33466. this._matrices = {};
  33467. this._matrices3x3 = {};
  33468. this._matrices2x2 = {};
  33469. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  33470. this._shaderPath = shaderPath;
  33471. options.needAlphaBlending = options.needAlphaBlending || false;
  33472. options.needAlphaTesting = options.needAlphaTesting || false;
  33473. options.attributes = options.attributes || ["position", "normal", "uv"];
  33474. options.uniforms = options.uniforms || ["worldViewProjection"];
  33475. options.samplers = options.samplers || [];
  33476. options.defines = options.defines || [];
  33477. this._options = options;
  33478. }
  33479. ShaderMaterial.prototype.needAlphaBlending = function () {
  33480. return this._options.needAlphaBlending;
  33481. };
  33482. ShaderMaterial.prototype.needAlphaTesting = function () {
  33483. return this._options.needAlphaTesting;
  33484. };
  33485. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  33486. if (this._options.uniforms.indexOf(uniformName) === -1) {
  33487. this._options.uniforms.push(uniformName);
  33488. }
  33489. };
  33490. ShaderMaterial.prototype.setTexture = function (name, texture) {
  33491. if (this._options.samplers.indexOf(name) === -1) {
  33492. this._options.samplers.push(name);
  33493. }
  33494. this._textures[name] = texture;
  33495. return this;
  33496. };
  33497. ShaderMaterial.prototype.setFloat = function (name, value) {
  33498. this._checkUniform(name);
  33499. this._floats[name] = value;
  33500. return this;
  33501. };
  33502. ShaderMaterial.prototype.setFloats = function (name, value) {
  33503. this._checkUniform(name);
  33504. this._floatsArrays[name] = value;
  33505. return this;
  33506. };
  33507. ShaderMaterial.prototype.setColor3 = function (name, value) {
  33508. this._checkUniform(name);
  33509. this._colors3[name] = value;
  33510. return this;
  33511. };
  33512. ShaderMaterial.prototype.setColor4 = function (name, value) {
  33513. this._checkUniform(name);
  33514. this._colors4[name] = value;
  33515. return this;
  33516. };
  33517. ShaderMaterial.prototype.setVector2 = function (name, value) {
  33518. this._checkUniform(name);
  33519. this._vectors2[name] = value;
  33520. return this;
  33521. };
  33522. ShaderMaterial.prototype.setVector3 = function (name, value) {
  33523. this._checkUniform(name);
  33524. this._vectors3[name] = value;
  33525. return this;
  33526. };
  33527. ShaderMaterial.prototype.setVector4 = function (name, value) {
  33528. this._checkUniform(name);
  33529. this._vectors4[name] = value;
  33530. return this;
  33531. };
  33532. ShaderMaterial.prototype.setMatrix = function (name, value) {
  33533. this._checkUniform(name);
  33534. this._matrices[name] = value;
  33535. return this;
  33536. };
  33537. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  33538. this._checkUniform(name);
  33539. this._matrices3x3[name] = value;
  33540. return this;
  33541. };
  33542. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  33543. this._checkUniform(name);
  33544. this._matrices2x2[name] = value;
  33545. return this;
  33546. };
  33547. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  33548. var scene = this.getScene();
  33549. var engine = scene.getEngine();
  33550. if (!this.checkReadyOnEveryCall) {
  33551. if (this._renderId === scene.getRenderId()) {
  33552. return true;
  33553. }
  33554. }
  33555. // Instances
  33556. var defines = [];
  33557. var fallbacks = new BABYLON.EffectFallbacks();
  33558. if (useInstances) {
  33559. defines.push("#define INSTANCES");
  33560. }
  33561. for (var index = 0; index < this._options.defines.length; index++) {
  33562. defines.push(this._options.defines[index]);
  33563. }
  33564. // Bones
  33565. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  33566. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33567. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33568. fallbacks.addCPUSkinningFallback(0, mesh);
  33569. }
  33570. // Alpha test
  33571. if (engine.getAlphaTesting()) {
  33572. defines.push("#define ALPHATEST");
  33573. }
  33574. var previousEffect = this._effect;
  33575. var join = defines.join("\n");
  33576. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  33577. if (!this._effect.isReady()) {
  33578. return false;
  33579. }
  33580. if (previousEffect !== this._effect) {
  33581. scene.resetCachedMaterial();
  33582. }
  33583. this._renderId = scene.getRenderId();
  33584. return true;
  33585. };
  33586. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  33587. var scene = this.getScene();
  33588. if (this._options.uniforms.indexOf("world") !== -1) {
  33589. this._effect.setMatrix("world", world);
  33590. }
  33591. if (this._options.uniforms.indexOf("worldView") !== -1) {
  33592. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  33593. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  33594. }
  33595. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  33596. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  33597. }
  33598. };
  33599. ShaderMaterial.prototype.bind = function (world, mesh) {
  33600. // Std values
  33601. this.bindOnlyWorldMatrix(world);
  33602. if (this.getScene().getCachedMaterial() !== this) {
  33603. if (this._options.uniforms.indexOf("view") !== -1) {
  33604. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  33605. }
  33606. if (this._options.uniforms.indexOf("projection") !== -1) {
  33607. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  33608. }
  33609. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  33610. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  33611. }
  33612. // Bones
  33613. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  33614. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33615. }
  33616. // Texture
  33617. for (var name in this._textures) {
  33618. this._effect.setTexture(name, this._textures[name]);
  33619. }
  33620. // Float
  33621. for (name in this._floats) {
  33622. this._effect.setFloat(name, this._floats[name]);
  33623. }
  33624. // Float s
  33625. for (name in this._floatsArrays) {
  33626. this._effect.setArray(name, this._floatsArrays[name]);
  33627. }
  33628. // Color3
  33629. for (name in this._colors3) {
  33630. this._effect.setColor3(name, this._colors3[name]);
  33631. }
  33632. // Color4
  33633. for (name in this._colors4) {
  33634. var color = this._colors4[name];
  33635. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  33636. }
  33637. // Vector2
  33638. for (name in this._vectors2) {
  33639. this._effect.setVector2(name, this._vectors2[name]);
  33640. }
  33641. // Vector3
  33642. for (name in this._vectors3) {
  33643. this._effect.setVector3(name, this._vectors3[name]);
  33644. }
  33645. // Vector4
  33646. for (name in this._vectors4) {
  33647. this._effect.setVector4(name, this._vectors4[name]);
  33648. }
  33649. // Matrix
  33650. for (name in this._matrices) {
  33651. this._effect.setMatrix(name, this._matrices[name]);
  33652. }
  33653. // Matrix 3x3
  33654. for (name in this._matrices3x3) {
  33655. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  33656. }
  33657. // Matrix 2x2
  33658. for (name in this._matrices2x2) {
  33659. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  33660. }
  33661. }
  33662. _super.prototype.bind.call(this, world, mesh);
  33663. };
  33664. ShaderMaterial.prototype.clone = function (name) {
  33665. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  33666. return newShaderMaterial;
  33667. };
  33668. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  33669. for (var name in this._textures) {
  33670. this._textures[name].dispose();
  33671. }
  33672. this._textures = {};
  33673. _super.prototype.dispose.call(this, forceDisposeEffect);
  33674. };
  33675. ShaderMaterial.prototype.serialize = function () {
  33676. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33677. serializationObject.customType = "BABYLON.ShaderMaterial";
  33678. serializationObject.options = this._options;
  33679. serializationObject.shaderPath = this._shaderPath;
  33680. // Texture
  33681. serializationObject.textures = {};
  33682. for (var name in this._textures) {
  33683. serializationObject.textures[name] = this._textures[name].serialize();
  33684. }
  33685. // Float
  33686. serializationObject.floats = {};
  33687. for (name in this._floats) {
  33688. serializationObject.floats[name] = this._floats[name];
  33689. }
  33690. // Float s
  33691. serializationObject.floatArrays = {};
  33692. for (name in this._floatsArrays) {
  33693. serializationObject.floatArrays[name] = this._floatsArrays[name];
  33694. }
  33695. // Color3
  33696. serializationObject.colors3 = {};
  33697. for (name in this._colors3) {
  33698. serializationObject.colors3[name] = this._colors3[name].asArray();
  33699. }
  33700. // Color4
  33701. serializationObject.colors4 = {};
  33702. for (name in this._colors4) {
  33703. serializationObject.colors4[name] = this._colors4[name].asArray();
  33704. }
  33705. // Vector2
  33706. serializationObject.vectors2 = {};
  33707. for (name in this._vectors2) {
  33708. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  33709. }
  33710. // Vector3
  33711. serializationObject.vectors3 = {};
  33712. for (name in this._vectors3) {
  33713. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  33714. }
  33715. // Vector4
  33716. serializationObject.vectors4 = {};
  33717. for (name in this._vectors4) {
  33718. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  33719. }
  33720. // Matrix
  33721. serializationObject.matrices = {};
  33722. for (name in this._matrices) {
  33723. serializationObject.matrices[name] = this._matrices[name].asArray();
  33724. }
  33725. // Matrix 3x3
  33726. serializationObject.matrices3x3 = {};
  33727. for (name in this._matrices3x3) {
  33728. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  33729. }
  33730. // Matrix 2x2
  33731. serializationObject.matrices2x2 = {};
  33732. for (name in this._matrices2x2) {
  33733. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  33734. }
  33735. return serializationObject;
  33736. };
  33737. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  33738. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  33739. // Texture
  33740. for (var name in source.textures) {
  33741. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  33742. }
  33743. // Float
  33744. for (name in source.floats) {
  33745. material.setFloat(name, source.floats[name]);
  33746. }
  33747. // Float s
  33748. for (name in source.floatsArrays) {
  33749. material.setFloats(name, source.floatsArrays[name]);
  33750. }
  33751. // Color3
  33752. for (name in source.colors3) {
  33753. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  33754. }
  33755. // Color4
  33756. for (name in source.colors4) {
  33757. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  33758. }
  33759. // Vector2
  33760. for (name in source.vectors2) {
  33761. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  33762. }
  33763. // Vector3
  33764. for (name in source.vectors3) {
  33765. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  33766. }
  33767. // Vector4
  33768. for (name in source.vectors4) {
  33769. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  33770. }
  33771. // Matrix
  33772. for (name in source.matrices) {
  33773. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  33774. }
  33775. // Matrix 3x3
  33776. for (name in source.matrices3x3) {
  33777. material.setMatrix3x3(name, source.matrices3x3[name]);
  33778. }
  33779. // Matrix 2x2
  33780. for (name in source.matrices2x2) {
  33781. material.setMatrix2x2(name, source.matrices2x2[name]);
  33782. }
  33783. return material;
  33784. };
  33785. return ShaderMaterial;
  33786. })(BABYLON.Material);
  33787. BABYLON.ShaderMaterial = ShaderMaterial;
  33788. })(BABYLON || (BABYLON = {}));
  33789. var BABYLON;
  33790. (function (BABYLON) {
  33791. var Internals;
  33792. (function (Internals) {
  33793. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33794. // All values and structures referenced from:
  33795. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33796. var DDS_MAGIC = 0x20534444;
  33797. 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;
  33798. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33799. 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;
  33800. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33801. function FourCCToInt32(value) {
  33802. return value.charCodeAt(0) +
  33803. (value.charCodeAt(1) << 8) +
  33804. (value.charCodeAt(2) << 16) +
  33805. (value.charCodeAt(3) << 24);
  33806. }
  33807. function Int32ToFourCC(value) {
  33808. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33809. }
  33810. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33811. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33812. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33813. var headerLengthInt = 31; // The header length in 32 bit ints
  33814. // Offsets into the header array
  33815. var off_magic = 0;
  33816. var off_size = 1;
  33817. var off_flags = 2;
  33818. var off_height = 3;
  33819. var off_width = 4;
  33820. var off_mipmapCount = 7;
  33821. var off_pfFlags = 20;
  33822. var off_pfFourCC = 21;
  33823. var off_RGBbpp = 22;
  33824. var off_RMask = 23;
  33825. var off_GMask = 24;
  33826. var off_BMask = 25;
  33827. var off_AMask = 26;
  33828. var off_caps1 = 27;
  33829. var off_caps2 = 28;
  33830. ;
  33831. var DDSTools = (function () {
  33832. function DDSTools() {
  33833. }
  33834. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33835. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33836. var mipmapCount = 1;
  33837. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33838. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33839. }
  33840. return {
  33841. width: header[off_width],
  33842. height: header[off_height],
  33843. mipmapCount: mipmapCount,
  33844. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33845. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33846. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33847. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33848. };
  33849. };
  33850. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33851. var byteArray = new Uint8Array(dataLength);
  33852. var srcData = new Uint8Array(arrayBuffer);
  33853. var index = 0;
  33854. for (var y = height - 1; y >= 0; y--) {
  33855. for (var x = 0; x < width; x++) {
  33856. var srcPos = dataOffset + (x + y * width) * 4;
  33857. byteArray[index + 2] = srcData[srcPos];
  33858. byteArray[index + 1] = srcData[srcPos + 1];
  33859. byteArray[index] = srcData[srcPos + 2];
  33860. byteArray[index + 3] = srcData[srcPos + 3];
  33861. index += 4;
  33862. }
  33863. }
  33864. return byteArray;
  33865. };
  33866. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33867. var byteArray = new Uint8Array(dataLength);
  33868. var srcData = new Uint8Array(arrayBuffer);
  33869. var index = 0;
  33870. for (var y = height - 1; y >= 0; y--) {
  33871. for (var x = 0; x < width; x++) {
  33872. var srcPos = dataOffset + (x + y * width) * 3;
  33873. byteArray[index + 2] = srcData[srcPos];
  33874. byteArray[index + 1] = srcData[srcPos + 1];
  33875. byteArray[index] = srcData[srcPos + 2];
  33876. index += 3;
  33877. }
  33878. }
  33879. return byteArray;
  33880. };
  33881. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33882. var byteArray = new Uint8Array(dataLength);
  33883. var srcData = new Uint8Array(arrayBuffer);
  33884. var index = 0;
  33885. for (var y = height - 1; y >= 0; y--) {
  33886. for (var x = 0; x < width; x++) {
  33887. var srcPos = dataOffset + (x + y * width);
  33888. byteArray[index] = srcData[srcPos];
  33889. index++;
  33890. }
  33891. }
  33892. return byteArray;
  33893. };
  33894. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33895. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33896. if (header[off_magic] != DDS_MAGIC) {
  33897. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33898. return;
  33899. }
  33900. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33901. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33902. return;
  33903. }
  33904. if (info.isFourCC) {
  33905. fourCC = header[off_pfFourCC];
  33906. switch (fourCC) {
  33907. case FOURCC_DXT1:
  33908. blockBytes = 8;
  33909. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33910. break;
  33911. case FOURCC_DXT3:
  33912. blockBytes = 16;
  33913. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33914. break;
  33915. case FOURCC_DXT5:
  33916. blockBytes = 16;
  33917. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33918. break;
  33919. default:
  33920. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33921. return;
  33922. }
  33923. }
  33924. mipmapCount = 1;
  33925. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33926. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33927. }
  33928. var bpp = header[off_RGBbpp];
  33929. for (var face = 0; face < faces; face++) {
  33930. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33931. width = header[off_width];
  33932. height = header[off_height];
  33933. dataOffset = header[off_size] + 4;
  33934. for (i = 0; i < mipmapCount; ++i) {
  33935. if (info.isRGB) {
  33936. if (bpp === 24) {
  33937. dataLength = width * height * 3;
  33938. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33939. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33940. }
  33941. else {
  33942. dataLength = width * height * 4;
  33943. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33944. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33945. }
  33946. }
  33947. else if (info.isLuminance) {
  33948. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33949. var unpaddedRowSize = width;
  33950. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33951. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33952. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33953. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33954. }
  33955. else {
  33956. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33957. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33958. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33959. }
  33960. dataOffset += dataLength;
  33961. width *= 0.5;
  33962. height *= 0.5;
  33963. width = Math.max(1.0, width);
  33964. height = Math.max(1.0, height);
  33965. }
  33966. }
  33967. };
  33968. return DDSTools;
  33969. })();
  33970. Internals.DDSTools = DDSTools;
  33971. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33972. })(BABYLON || (BABYLON = {}));
  33973. var BABYLON;
  33974. (function (BABYLON) {
  33975. var CannonJSPlugin = (function () {
  33976. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  33977. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  33978. if (iterations === void 0) { iterations = 10; }
  33979. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  33980. this.name = "CannonJSPlugin";
  33981. this._physicsMaterials = [];
  33982. this._fixedTimeStep = 1 / 60;
  33983. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  33984. this._currentCollisionGroup = 2;
  33985. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  33986. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  33987. this._tmpPosition = BABYLON.Vector3.Zero();
  33988. this._tmpQuaternion = new BABYLON.Quaternion();
  33989. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  33990. this._tmpDeltaRotation = new BABYLON.Quaternion();
  33991. this._tmpUnityRotation = new BABYLON.Quaternion();
  33992. if (!this.isSupported()) {
  33993. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  33994. return;
  33995. }
  33996. this.world = new CANNON.World();
  33997. this.world.broadphase = new CANNON.NaiveBroadphase();
  33998. this.world.solver.iterations = iterations;
  33999. }
  34000. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34001. this.world.gravity.copy(gravity);
  34002. };
  34003. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34004. this._fixedTimeStep = timeStep;
  34005. };
  34006. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34007. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34008. };
  34009. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34010. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34011. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34012. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34013. };
  34014. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34015. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34016. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34017. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34018. };
  34019. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34020. //parent-child relationship. Does this impostor has a parent impostor?
  34021. if (impostor.parent) {
  34022. if (impostor.physicsBody) {
  34023. this.removePhysicsBody(impostor);
  34024. //TODO is that needed?
  34025. impostor.forceUpdate();
  34026. }
  34027. return;
  34028. }
  34029. //should a new body be created for this impostor?
  34030. if (impostor.isBodyInitRequired()) {
  34031. var shape = this._createShape(impostor);
  34032. //unregister events, if body is being changed
  34033. var oldBody = impostor.physicsBody;
  34034. if (oldBody) {
  34035. this.removePhysicsBody(impostor);
  34036. }
  34037. //create the body and material
  34038. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34039. var bodyCreationObject = {
  34040. mass: impostor.getParam("mass"),
  34041. material: material
  34042. };
  34043. // A simple extend, in case native options were used.
  34044. var nativeOptions = impostor.getParam("nativeOptions");
  34045. for (var key in nativeOptions) {
  34046. if (nativeOptions.hasOwnProperty(key)) {
  34047. bodyCreationObject[key] = nativeOptions[key];
  34048. }
  34049. }
  34050. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34051. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34052. this.world.addEventListener("preStep", impostor.beforeStep);
  34053. this.world.addEventListener("postStep", impostor.afterStep);
  34054. impostor.physicsBody.addShape(shape);
  34055. this.world.add(impostor.physicsBody);
  34056. //try to keep the body moving in the right direction by taking old properties.
  34057. //Should be tested!
  34058. if (oldBody) {
  34059. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34060. impostor.physicsBody[param].copy(oldBody[param]);
  34061. });
  34062. }
  34063. this._processChildMeshes(impostor);
  34064. }
  34065. //now update the body's transformation
  34066. this._updatePhysicsBodyTransformation(impostor);
  34067. };
  34068. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34069. var _this = this;
  34070. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34071. if (meshChildren.length) {
  34072. var processMesh = function (localPosition, mesh) {
  34073. var childImpostor = mesh.getPhysicsImpostor();
  34074. if (childImpostor) {
  34075. var parent = childImpostor.parent;
  34076. if (parent !== mainImpostor) {
  34077. var localPosition = mesh.position;
  34078. if (childImpostor.physicsBody) {
  34079. _this.removePhysicsBody(childImpostor);
  34080. childImpostor.physicsBody = null;
  34081. }
  34082. childImpostor.parent = mainImpostor;
  34083. childImpostor.resetUpdateFlags();
  34084. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34085. //Add the mass of the children.
  34086. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34087. }
  34088. }
  34089. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34090. };
  34091. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34092. }
  34093. };
  34094. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34095. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34096. this.world.removeEventListener("preStep", impostor.beforeStep);
  34097. this.world.removeEventListener("postStep", impostor.afterStep);
  34098. this.world.remove(impostor.physicsBody);
  34099. };
  34100. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34101. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34102. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34103. if (!mainBody || !connectedBody) {
  34104. return;
  34105. }
  34106. var constraint;
  34107. var jointData = impostorJoint.joint.jointData;
  34108. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34109. var constraintData = {
  34110. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34111. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34112. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34113. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34114. maxForce: jointData.nativeParams.maxForce,
  34115. collideConnected: !!jointData.collision
  34116. };
  34117. //Not needed, Cannon has a collideConnected flag
  34118. /*if (!jointData.collision) {
  34119. //add 1st body to a collision group of its own, if it is not in 1
  34120. if (mainBody.collisionFilterGroup === 1) {
  34121. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34122. this._currentCollisionGroup <<= 1;
  34123. }
  34124. if (connectedBody.collisionFilterGroup === 1) {
  34125. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34126. this._currentCollisionGroup <<= 1;
  34127. }
  34128. //add their mask to the collisionFilterMask of each other:
  34129. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34130. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34131. }*/
  34132. switch (impostorJoint.joint.type) {
  34133. case BABYLON.PhysicsJoint.HingeJoint:
  34134. case BABYLON.PhysicsJoint.Hinge2Joint:
  34135. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34136. break;
  34137. case BABYLON.PhysicsJoint.DistanceJoint:
  34138. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34139. break;
  34140. case BABYLON.PhysicsJoint.SpringJoint:
  34141. var springData = jointData;
  34142. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34143. restLength: springData.length,
  34144. stiffness: springData.stiffness,
  34145. damping: springData.damping,
  34146. localAnchorA: constraintData.pivotA,
  34147. localAnchorB: constraintData.pivotB
  34148. });
  34149. break;
  34150. case BABYLON.PhysicsJoint.PointToPointJoint:
  34151. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34152. default:
  34153. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34154. break;
  34155. }
  34156. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34157. constraint.collideConnected = !!jointData.collision;
  34158. impostorJoint.joint.physicsJoint = constraint;
  34159. //don't add spring as constraint, as it is not one.
  34160. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34161. this.world.addConstraint(constraint);
  34162. }
  34163. else {
  34164. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34165. constraint.applyForce();
  34166. });
  34167. }
  34168. };
  34169. CannonJSPlugin.prototype.removeJoint = function (joint) {
  34170. //TODO
  34171. };
  34172. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34173. var index;
  34174. var mat;
  34175. for (index = 0; index < this._physicsMaterials.length; index++) {
  34176. mat = this._physicsMaterials[index];
  34177. if (mat.friction === friction && mat.restitution === restitution) {
  34178. return mat;
  34179. }
  34180. }
  34181. var currentMat = new CANNON.Material("mat");
  34182. currentMat.friction = friction;
  34183. currentMat.restitution = restitution;
  34184. this._physicsMaterials.push(currentMat);
  34185. return currentMat;
  34186. };
  34187. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34188. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34189. };
  34190. CannonJSPlugin.prototype._createShape = function (impostor) {
  34191. var object = impostor.object;
  34192. var returnValue;
  34193. var extendSize = impostor.getObjectExtendSize();
  34194. switch (impostor.type) {
  34195. case BABYLON.PhysicsEngine.SphereImpostor:
  34196. var radiusX = extendSize.x;
  34197. var radiusY = extendSize.y;
  34198. var radiusZ = extendSize.z;
  34199. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34200. break;
  34201. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34202. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34203. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34204. break;
  34205. case BABYLON.PhysicsImpostor.BoxImpostor:
  34206. var box = extendSize.scale(0.5);
  34207. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34208. break;
  34209. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34210. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34211. returnValue = new CANNON.Plane();
  34212. break;
  34213. case BABYLON.PhysicsImpostor.MeshImpostor:
  34214. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34215. var rawFaces = object.getIndices ? object.getIndices() : [];
  34216. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34217. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34218. break;
  34219. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34220. returnValue = this._createHeightmap(object);
  34221. break;
  34222. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34223. returnValue = new CANNON.Particle();
  34224. break;
  34225. }
  34226. return returnValue;
  34227. };
  34228. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34229. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34230. var matrix = [];
  34231. //For now pointDepth will not be used and will be automatically calculated.
  34232. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34233. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34234. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34235. var elementSize = dim * 2 / arraySize;
  34236. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34237. for (var i = 0; i < pos.length; i = i + 3) {
  34238. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34239. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34240. var y = pos[i + 1] + minY;
  34241. if (!matrix[x]) {
  34242. matrix[x] = [];
  34243. }
  34244. if (!matrix[x][z]) {
  34245. matrix[x][z] = y;
  34246. }
  34247. matrix[x][z] = Math.max(y, matrix[x][z]);
  34248. }
  34249. for (var x = 0; x <= arraySize; ++x) {
  34250. if (!matrix[x]) {
  34251. var loc = 1;
  34252. while (!matrix[(x + loc) % arraySize]) {
  34253. loc++;
  34254. }
  34255. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34256. }
  34257. for (var z = 0; z <= arraySize; ++z) {
  34258. if (!matrix[x][z]) {
  34259. var loc = 1;
  34260. var newValue;
  34261. while (newValue === undefined) {
  34262. newValue = matrix[x][(z + loc++) % arraySize];
  34263. }
  34264. matrix[x][z] = newValue;
  34265. }
  34266. }
  34267. }
  34268. var shape = new CANNON.Heightfield(matrix, {
  34269. elementSize: elementSize
  34270. });
  34271. //For future reference, needed for body transformation
  34272. shape.minY = minY;
  34273. return shape;
  34274. };
  34275. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34276. var object = impostor.object;
  34277. //make sure it is updated...
  34278. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34279. // The delta between the mesh position and the mesh bounding box center
  34280. var center = impostor.getObjectCenter();
  34281. var extendSize = impostor.getObjectExtendSize();
  34282. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34283. this._tmpPosition.copyFrom(center);
  34284. var quaternion = object.rotationQuaternion;
  34285. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34286. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34287. //-90 DEG in X, precalculated
  34288. quaternion = quaternion.multiply(this._minus90X);
  34289. //Invert! (Precalculated, 90 deg in X)
  34290. //No need to clone. this will never change.
  34291. impostor.setDeltaRotation(this._plus90X);
  34292. }
  34293. //If it is a heightfield, if should be centered.
  34294. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34295. var mesh = object;
  34296. //calculate the correct body position:
  34297. var rotationQuaternion = mesh.rotationQuaternion;
  34298. mesh.rotationQuaternion = this._tmpUnityRotation;
  34299. mesh.computeWorldMatrix(true);
  34300. //get original center with no rotation
  34301. var c = center.clone();
  34302. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34303. //rotation is back
  34304. mesh.rotationQuaternion = rotationQuaternion;
  34305. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34306. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34307. mesh.setPivotMatrix(p);
  34308. mesh.computeWorldMatrix(true);
  34309. //calculate the translation
  34310. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34311. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34312. //add it inverted to the delta
  34313. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34314. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34315. mesh.setPivotMatrix(oldPivot);
  34316. mesh.computeWorldMatrix(true);
  34317. }
  34318. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34319. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34320. this._tmpPosition.copyFrom(object.position);
  34321. }
  34322. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34323. //Now update the impostor object
  34324. impostor.physicsBody.position.copy(this._tmpPosition);
  34325. impostor.physicsBody.quaternion.copy(quaternion);
  34326. };
  34327. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34328. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34329. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34330. };
  34331. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34332. impostor.physicsBody.position.copy(newPosition);
  34333. impostor.physicsBody.quaternion.copy(newRotation);
  34334. };
  34335. CannonJSPlugin.prototype.isSupported = function () {
  34336. return window.CANNON !== undefined;
  34337. };
  34338. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34339. impostor.physicsBody.velocity.copy(velocity);
  34340. };
  34341. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34342. impostor.physicsBody.angularVelocity.copy(velocity);
  34343. };
  34344. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34345. var v = impostor.physicsBody.velocity;
  34346. if (!v)
  34347. return null;
  34348. return new BABYLON.Vector3(v.x, v.y, v.z);
  34349. };
  34350. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34351. var v = impostor.physicsBody.angularVelocity;
  34352. if (!v)
  34353. return null;
  34354. return new BABYLON.Vector3(v.x, v.y, v.z);
  34355. };
  34356. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34357. impostor.physicsBody.mass = mass;
  34358. impostor.physicsBody.updateMassProperties();
  34359. };
  34360. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34361. impostor.physicsBody.sleep();
  34362. };
  34363. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34364. impostor.physicsBody.wakeUp();
  34365. };
  34366. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34367. joint.physicsJoint.distance = maxDistance;
  34368. };
  34369. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34370. if (!motorIndex) {
  34371. joint.physicsJoint.enableMotor();
  34372. }
  34373. };
  34374. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34375. if (!motorIndex) {
  34376. joint.physicsJoint.disableMotor();
  34377. }
  34378. };
  34379. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34380. if (!motorIndex) {
  34381. joint.physicsJoint.enableMotor();
  34382. joint.physicsJoint.setMotorSpeed(speed);
  34383. if (maxForce) {
  34384. this.setLimit(joint, maxForce);
  34385. }
  34386. }
  34387. };
  34388. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34389. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34390. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34391. };
  34392. CannonJSPlugin.prototype.dispose = function () {
  34393. //nothing to do, actually.
  34394. };
  34395. return CannonJSPlugin;
  34396. })();
  34397. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34398. })(BABYLON || (BABYLON = {}));
  34399. var BABYLON;
  34400. (function (BABYLON) {
  34401. var OimoJSPlugin = (function () {
  34402. function OimoJSPlugin(iterations) {
  34403. this.name = "OimoJSPlugin";
  34404. this._tmpImpostorsArray = [];
  34405. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34406. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34407. this.world.clear();
  34408. //making sure no stats are calculated
  34409. this.world.isNoStat = true;
  34410. }
  34411. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34412. this.world.gravity.copy(gravity);
  34413. };
  34414. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34415. this.world.timeStep = timeStep;
  34416. };
  34417. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  34418. var _this = this;
  34419. impostors.forEach(function (impostor) {
  34420. impostor.beforeStep();
  34421. });
  34422. this.world.step();
  34423. impostors.forEach(function (impostor) {
  34424. impostor.afterStep();
  34425. //update the ordered impostors array
  34426. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  34427. });
  34428. //check for collisions
  34429. var contact = this.world.contacts;
  34430. while (contact !== null) {
  34431. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34432. contact = contact.next;
  34433. continue;
  34434. }
  34435. //is this body colliding with any other? get the impostor
  34436. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  34437. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  34438. if (!mainImpostor || !collidingImpostor) {
  34439. contact = contact.next;
  34440. continue;
  34441. }
  34442. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  34443. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  34444. contact = contact.next;
  34445. }
  34446. };
  34447. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34448. var mass = impostor.physicsBody.massInfo.mass;
  34449. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  34450. };
  34451. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34452. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  34453. this.applyImpulse(impostor, force, contactPoint);
  34454. };
  34455. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34456. var _this = this;
  34457. //parent-child relationship. Does this impostor has a parent impostor?
  34458. if (impostor.parent) {
  34459. if (impostor.physicsBody) {
  34460. this.removePhysicsBody(impostor);
  34461. //TODO is that needed?
  34462. impostor.forceUpdate();
  34463. }
  34464. return;
  34465. }
  34466. if (impostor.isBodyInitRequired()) {
  34467. var bodyConfig = {
  34468. name: impostor.uniqueId,
  34469. //Oimo must have mass, also for static objects.
  34470. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  34471. size: [],
  34472. type: [],
  34473. pos: [],
  34474. rot: [],
  34475. move: impostor.getParam("mass") !== 0,
  34476. //Supporting older versions of Oimo
  34477. world: this.world
  34478. };
  34479. var impostors = [impostor];
  34480. function addToArray(parent) {
  34481. if (!parent.getChildMeshes)
  34482. return;
  34483. parent.getChildMeshes().forEach(function (m) {
  34484. if (m.physicsImpostor) {
  34485. impostors.push(m.physicsImpostor);
  34486. m.physicsImpostor._init();
  34487. }
  34488. });
  34489. }
  34490. addToArray(impostor.object);
  34491. function checkWithEpsilon(value) {
  34492. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  34493. }
  34494. impostors.forEach(function (i) {
  34495. //get the correct bounding box
  34496. var oldQuaternion = i.object.rotationQuaternion;
  34497. var rot = new OIMO.Euler().setFromQuaternion({
  34498. x: impostor.object.rotationQuaternion.x,
  34499. y: impostor.object.rotationQuaternion.y,
  34500. z: impostor.object.rotationQuaternion.z,
  34501. s: impostor.object.rotationQuaternion.w });
  34502. var extendSize = i.getObjectExtendSize();
  34503. if (i === impostor) {
  34504. var center = impostor.getObjectCenter();
  34505. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  34506. //Can also use Array.prototype.push.apply
  34507. bodyConfig.pos.push(center.x);
  34508. bodyConfig.pos.push(center.y);
  34509. bodyConfig.pos.push(center.z);
  34510. //tmp solution
  34511. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  34512. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  34513. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  34514. }
  34515. else {
  34516. bodyConfig.pos.push(i.object.position.x);
  34517. bodyConfig.pos.push(i.object.position.y);
  34518. bodyConfig.pos.push(i.object.position.z);
  34519. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  34520. bodyConfig.rot.push(0);
  34521. bodyConfig.rot.push(0);
  34522. bodyConfig.rot.push(0);
  34523. }
  34524. // register mesh
  34525. switch (i.type) {
  34526. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34527. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  34528. case BABYLON.PhysicsImpostor.SphereImpostor:
  34529. var radiusX = extendSize.x;
  34530. var radiusY = extendSize.y;
  34531. var radiusZ = extendSize.z;
  34532. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  34533. bodyConfig.type.push('sphere');
  34534. //due to the way oimo works with compounds, add 3 times
  34535. bodyConfig.size.push(size);
  34536. bodyConfig.size.push(size);
  34537. bodyConfig.size.push(size);
  34538. break;
  34539. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34540. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  34541. var sizeY = checkWithEpsilon(extendSize.y);
  34542. bodyConfig.type.push('cylinder');
  34543. bodyConfig.size.push(sizeX);
  34544. bodyConfig.size.push(sizeY);
  34545. //due to the way oimo works with compounds, add one more value.
  34546. bodyConfig.size.push(sizeY);
  34547. break;
  34548. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34549. case BABYLON.PhysicsImpostor.BoxImpostor:
  34550. default:
  34551. var sizeX = checkWithEpsilon(extendSize.x);
  34552. var sizeY = checkWithEpsilon(extendSize.y);
  34553. var sizeZ = checkWithEpsilon(extendSize.z);
  34554. bodyConfig.type.push('box');
  34555. bodyConfig.size.push(sizeX);
  34556. bodyConfig.size.push(sizeY);
  34557. bodyConfig.size.push(sizeZ);
  34558. break;
  34559. }
  34560. //actually not needed, but hey...
  34561. i.object.rotationQuaternion = oldQuaternion;
  34562. });
  34563. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  34564. }
  34565. else {
  34566. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  34567. }
  34568. impostor.setDeltaPosition(this._tmpPositionVector);
  34569. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  34570. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  34571. };
  34572. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34573. //impostor.physicsBody.dispose();
  34574. //Same as : (older oimo versions)
  34575. this.world.removeRigidBody(impostor.physicsBody);
  34576. };
  34577. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34578. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34579. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34580. if (!mainBody || !connectedBody) {
  34581. return;
  34582. }
  34583. var jointData = impostorJoint.joint.jointData;
  34584. var options = jointData.nativeParams || {};
  34585. var type;
  34586. var nativeJointData = {
  34587. body1: mainBody,
  34588. body2: connectedBody,
  34589. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  34590. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  34591. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  34592. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  34593. min: options.min,
  34594. max: options.max,
  34595. collision: options.collision || jointData.collision,
  34596. spring: options.spring,
  34597. //supporting older version of Oimo
  34598. world: this.world
  34599. };
  34600. switch (impostorJoint.joint.type) {
  34601. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34602. type = "jointBall";
  34603. break;
  34604. case BABYLON.PhysicsJoint.SpringJoint:
  34605. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  34606. var springData = jointData;
  34607. nativeJointData.min = springData.length || nativeJointData.min;
  34608. //Max should also be set, just make sure it is at least min
  34609. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  34610. case BABYLON.PhysicsJoint.DistanceJoint:
  34611. type = "jointDistance";
  34612. nativeJointData.max = jointData.maxDistance;
  34613. break;
  34614. case BABYLON.PhysicsJoint.PrismaticJoint:
  34615. type = "jointPrisme";
  34616. break;
  34617. case BABYLON.PhysicsJoint.SliderJoint:
  34618. type = "jointSlide";
  34619. break;
  34620. case BABYLON.PhysicsJoint.WheelJoint:
  34621. type = "jointWheel";
  34622. break;
  34623. case BABYLON.PhysicsJoint.HingeJoint:
  34624. default:
  34625. type = "jointHinge";
  34626. break;
  34627. }
  34628. nativeJointData.type = type;
  34629. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  34630. };
  34631. OimoJSPlugin.prototype.removeJoint = function (joint) {
  34632. joint.joint.physicsJoint.dispose();
  34633. };
  34634. OimoJSPlugin.prototype.isSupported = function () {
  34635. return OIMO !== undefined;
  34636. };
  34637. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34638. if (!impostor.physicsBody.sleeping) {
  34639. //TODO check that
  34640. if (impostor.physicsBody.shapes.next) {
  34641. var parentShape = this._getLastShape(impostor.physicsBody);
  34642. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  34643. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  34644. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  34645. }
  34646. else {
  34647. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  34648. }
  34649. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  34650. }
  34651. };
  34652. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34653. var body = impostor.physicsBody;
  34654. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  34655. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  34656. body.syncShapes();
  34657. body.awake();
  34658. };
  34659. OimoJSPlugin.prototype._getLastShape = function (body) {
  34660. var lastShape = body.shapes;
  34661. while (lastShape.next) {
  34662. lastShape = lastShape.next;
  34663. }
  34664. return lastShape;
  34665. };
  34666. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34667. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  34668. };
  34669. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34670. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  34671. };
  34672. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34673. var v = impostor.physicsBody.linearVelocity;
  34674. if (!v)
  34675. return null;
  34676. return new BABYLON.Vector3(v.x, v.y, v.z);
  34677. };
  34678. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34679. var v = impostor.physicsBody.angularVelocity;
  34680. if (!v)
  34681. return null;
  34682. return new BABYLON.Vector3(v.x, v.y, v.z);
  34683. };
  34684. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34685. var staticBody = mass === 0;
  34686. //this will actually set the body's density and not its mass.
  34687. //But this is how oimo treats the mass variable.
  34688. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  34689. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  34690. };
  34691. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  34692. impostor.physicsBody.sleep();
  34693. };
  34694. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  34695. impostor.physicsBody.awake();
  34696. };
  34697. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34698. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  34699. if (minDistance !== void 0) {
  34700. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  34701. }
  34702. };
  34703. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34704. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  34705. if (motor) {
  34706. motor.setMotor(speed, maxForce);
  34707. }
  34708. };
  34709. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  34710. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  34711. if (motor) {
  34712. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  34713. }
  34714. };
  34715. OimoJSPlugin.prototype.dispose = function () {
  34716. this.world.clear();
  34717. };
  34718. return OimoJSPlugin;
  34719. })();
  34720. BABYLON.OimoJSPlugin = OimoJSPlugin;
  34721. })(BABYLON || (BABYLON = {}));
  34722. var BABYLON;
  34723. (function (BABYLON) {
  34724. var DisplayPassPostProcess = (function (_super) {
  34725. __extends(DisplayPassPostProcess, _super);
  34726. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34727. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  34728. }
  34729. return DisplayPassPostProcess;
  34730. })(BABYLON.PostProcess);
  34731. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  34732. })(BABYLON || (BABYLON = {}));
  34733. var BABYLON;
  34734. (function (BABYLON) {
  34735. var SimplificationSettings = (function () {
  34736. function SimplificationSettings(quality, distance, optimizeMesh) {
  34737. this.quality = quality;
  34738. this.distance = distance;
  34739. this.optimizeMesh = optimizeMesh;
  34740. }
  34741. return SimplificationSettings;
  34742. })();
  34743. BABYLON.SimplificationSettings = SimplificationSettings;
  34744. var SimplificationQueue = (function () {
  34745. function SimplificationQueue() {
  34746. this.running = false;
  34747. this._simplificationArray = [];
  34748. }
  34749. SimplificationQueue.prototype.addTask = function (task) {
  34750. this._simplificationArray.push(task);
  34751. };
  34752. SimplificationQueue.prototype.executeNext = function () {
  34753. var task = this._simplificationArray.pop();
  34754. if (task) {
  34755. this.running = true;
  34756. this.runSimplification(task);
  34757. }
  34758. else {
  34759. this.running = false;
  34760. }
  34761. };
  34762. SimplificationQueue.prototype.runSimplification = function (task) {
  34763. var _this = this;
  34764. if (task.parallelProcessing) {
  34765. //parallel simplifier
  34766. task.settings.forEach(function (setting) {
  34767. var simplifier = _this.getSimplifier(task);
  34768. simplifier.simplify(setting, function (newMesh) {
  34769. task.mesh.addLODLevel(setting.distance, newMesh);
  34770. newMesh.isVisible = true;
  34771. //check if it is the last
  34772. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  34773. //all done, run the success callback.
  34774. task.successCallback();
  34775. }
  34776. _this.executeNext();
  34777. });
  34778. });
  34779. }
  34780. else {
  34781. //single simplifier.
  34782. var simplifier = this.getSimplifier(task);
  34783. var runDecimation = function (setting, callback) {
  34784. simplifier.simplify(setting, function (newMesh) {
  34785. task.mesh.addLODLevel(setting.distance, newMesh);
  34786. newMesh.isVisible = true;
  34787. //run the next quality level
  34788. callback();
  34789. });
  34790. };
  34791. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  34792. runDecimation(task.settings[loop.index], function () {
  34793. loop.executeNext();
  34794. });
  34795. }, function () {
  34796. //execution ended, run the success callback.
  34797. if (task.successCallback) {
  34798. task.successCallback();
  34799. }
  34800. _this.executeNext();
  34801. });
  34802. }
  34803. };
  34804. SimplificationQueue.prototype.getSimplifier = function (task) {
  34805. switch (task.simplificationType) {
  34806. case SimplificationType.QUADRATIC:
  34807. default:
  34808. return new QuadraticErrorSimplification(task.mesh);
  34809. }
  34810. };
  34811. return SimplificationQueue;
  34812. })();
  34813. BABYLON.SimplificationQueue = SimplificationQueue;
  34814. /**
  34815. * The implemented types of simplification.
  34816. * At the moment only Quadratic Error Decimation is implemented.
  34817. */
  34818. (function (SimplificationType) {
  34819. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  34820. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  34821. var SimplificationType = BABYLON.SimplificationType;
  34822. var DecimationTriangle = (function () {
  34823. function DecimationTriangle(vertices) {
  34824. this.vertices = vertices;
  34825. this.error = new Array(4);
  34826. this.deleted = false;
  34827. this.isDirty = false;
  34828. this.deletePending = false;
  34829. this.borderFactor = 0;
  34830. }
  34831. return DecimationTriangle;
  34832. })();
  34833. BABYLON.DecimationTriangle = DecimationTriangle;
  34834. var DecimationVertex = (function () {
  34835. function DecimationVertex(position, id) {
  34836. this.position = position;
  34837. this.id = id;
  34838. this.isBorder = true;
  34839. this.q = new QuadraticMatrix();
  34840. this.triangleCount = 0;
  34841. this.triangleStart = 0;
  34842. this.originalOffsets = [];
  34843. }
  34844. DecimationVertex.prototype.updatePosition = function (newPosition) {
  34845. this.position.copyFrom(newPosition);
  34846. };
  34847. return DecimationVertex;
  34848. })();
  34849. BABYLON.DecimationVertex = DecimationVertex;
  34850. var QuadraticMatrix = (function () {
  34851. function QuadraticMatrix(data) {
  34852. this.data = new Array(10);
  34853. for (var i = 0; i < 10; ++i) {
  34854. if (data && data[i]) {
  34855. this.data[i] = data[i];
  34856. }
  34857. else {
  34858. this.data[i] = 0;
  34859. }
  34860. }
  34861. }
  34862. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  34863. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  34864. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  34865. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  34866. return det;
  34867. };
  34868. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  34869. for (var i = 0; i < 10; ++i) {
  34870. this.data[i] += matrix.data[i];
  34871. }
  34872. };
  34873. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  34874. for (var i = 0; i < 10; ++i) {
  34875. this.data[i] += data[i];
  34876. }
  34877. };
  34878. QuadraticMatrix.prototype.add = function (matrix) {
  34879. var m = new QuadraticMatrix();
  34880. for (var i = 0; i < 10; ++i) {
  34881. m.data[i] = this.data[i] + matrix.data[i];
  34882. }
  34883. return m;
  34884. };
  34885. QuadraticMatrix.FromData = function (a, b, c, d) {
  34886. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  34887. };
  34888. //returning an array to avoid garbage collection
  34889. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  34890. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  34891. };
  34892. return QuadraticMatrix;
  34893. })();
  34894. BABYLON.QuadraticMatrix = QuadraticMatrix;
  34895. var Reference = (function () {
  34896. function Reference(vertexId, triangleId) {
  34897. this.vertexId = vertexId;
  34898. this.triangleId = triangleId;
  34899. }
  34900. return Reference;
  34901. })();
  34902. BABYLON.Reference = Reference;
  34903. /**
  34904. * An implementation of the Quadratic Error simplification algorithm.
  34905. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  34906. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  34907. * @author RaananW
  34908. */
  34909. var QuadraticErrorSimplification = (function () {
  34910. function QuadraticErrorSimplification(_mesh) {
  34911. this._mesh = _mesh;
  34912. this.initialized = false;
  34913. this.syncIterations = 5000;
  34914. this.aggressiveness = 7;
  34915. this.decimationIterations = 100;
  34916. this.boundingBoxEpsilon = BABYLON.Epsilon;
  34917. }
  34918. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  34919. var _this = this;
  34920. this.initDecimatedMesh();
  34921. //iterating through the submeshes array, one after the other.
  34922. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  34923. _this.initWithMesh(loop.index, function () {
  34924. _this.runDecimation(settings, loop.index, function () {
  34925. loop.executeNext();
  34926. });
  34927. }, settings.optimizeMesh);
  34928. }, function () {
  34929. setTimeout(function () {
  34930. successCallback(_this._reconstructedMesh);
  34931. }, 0);
  34932. });
  34933. };
  34934. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  34935. var _this = this;
  34936. var gCount = 0;
  34937. triangle.vertices.forEach(function (vertex) {
  34938. var count = 0;
  34939. var vPos = vertex.position;
  34940. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  34941. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  34942. ++count;
  34943. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  34944. ++count;
  34945. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  34946. ++count;
  34947. if (count > 1) {
  34948. ++gCount;
  34949. }
  34950. ;
  34951. });
  34952. if (gCount > 1) {
  34953. console.log(triangle, gCount);
  34954. }
  34955. return gCount > 1;
  34956. };
  34957. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  34958. var _this = this;
  34959. var targetCount = ~~(this.triangles.length * settings.quality);
  34960. var deletedTriangles = 0;
  34961. var triangleCount = this.triangles.length;
  34962. var iterationFunction = function (iteration, callback) {
  34963. setTimeout(function () {
  34964. if (iteration % 5 === 0) {
  34965. _this.updateMesh(iteration === 0);
  34966. }
  34967. for (var i = 0; i < _this.triangles.length; ++i) {
  34968. _this.triangles[i].isDirty = false;
  34969. }
  34970. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  34971. var trianglesIterator = function (i) {
  34972. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  34973. var t = _this.triangles[tIdx];
  34974. if (!t)
  34975. return;
  34976. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  34977. return;
  34978. }
  34979. for (var j = 0; j < 3; ++j) {
  34980. if (t.error[j] < threshold) {
  34981. var deleted0 = [];
  34982. var deleted1 = [];
  34983. var v0 = t.vertices[j];
  34984. var v1 = t.vertices[(j + 1) % 3];
  34985. if (v0.isBorder !== v1.isBorder)
  34986. continue;
  34987. var p = BABYLON.Vector3.Zero();
  34988. var n = BABYLON.Vector3.Zero();
  34989. var uv = BABYLON.Vector2.Zero();
  34990. var color = new BABYLON.Color4(0, 0, 0, 1);
  34991. _this.calculateError(v0, v1, p, n, uv, color);
  34992. var delTr = [];
  34993. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  34994. continue;
  34995. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  34996. continue;
  34997. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  34998. continue;
  34999. var uniqueArray = [];
  35000. delTr.forEach(function (deletedT) {
  35001. if (uniqueArray.indexOf(deletedT) === -1) {
  35002. deletedT.deletePending = true;
  35003. uniqueArray.push(deletedT);
  35004. }
  35005. });
  35006. if (uniqueArray.length % 2 !== 0) {
  35007. continue;
  35008. }
  35009. v0.q = v1.q.add(v0.q);
  35010. v0.updatePosition(p);
  35011. var tStart = _this.references.length;
  35012. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35013. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35014. var tCount = _this.references.length - tStart;
  35015. if (tCount <= v0.triangleCount) {
  35016. if (tCount) {
  35017. for (var c = 0; c < tCount; c++) {
  35018. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35019. }
  35020. }
  35021. }
  35022. else {
  35023. v0.triangleStart = tStart;
  35024. }
  35025. v0.triangleCount = tCount;
  35026. break;
  35027. }
  35028. }
  35029. };
  35030. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35031. }, 0);
  35032. };
  35033. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35034. if (triangleCount - deletedTriangles <= targetCount)
  35035. loop.breakLoop();
  35036. else {
  35037. iterationFunction(loop.index, function () {
  35038. loop.executeNext();
  35039. });
  35040. }
  35041. }, function () {
  35042. setTimeout(function () {
  35043. //reconstruct this part of the mesh
  35044. _this.reconstructMesh(submeshIndex);
  35045. successCallback();
  35046. }, 0);
  35047. });
  35048. };
  35049. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35050. var _this = this;
  35051. this.vertices = [];
  35052. this.triangles = [];
  35053. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35054. var indices = this._mesh.getIndices();
  35055. var submesh = this._mesh.subMeshes[submeshIndex];
  35056. var findInVertices = function (positionToSearch) {
  35057. if (optimizeMesh) {
  35058. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35059. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35060. return _this.vertices[ii];
  35061. }
  35062. }
  35063. }
  35064. return null;
  35065. };
  35066. var vertexReferences = [];
  35067. var vertexInit = function (i) {
  35068. var offset = i + submesh.verticesStart;
  35069. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35070. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35071. vertex.originalOffsets.push(offset);
  35072. if (vertex.id === _this.vertices.length) {
  35073. _this.vertices.push(vertex);
  35074. }
  35075. vertexReferences.push(vertex.id);
  35076. };
  35077. //var totalVertices = mesh.getTotalVertices();
  35078. var totalVertices = submesh.verticesCount;
  35079. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35080. var indicesInit = function (i) {
  35081. var offset = (submesh.indexStart / 3) + i;
  35082. var pos = (offset * 3);
  35083. var i0 = indices[pos + 0];
  35084. var i1 = indices[pos + 1];
  35085. var i2 = indices[pos + 2];
  35086. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35087. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35088. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35089. var triangle = new DecimationTriangle([v0, v1, v2]);
  35090. triangle.originalOffset = pos;
  35091. _this.triangles.push(triangle);
  35092. };
  35093. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35094. _this.init(callback);
  35095. });
  35096. });
  35097. };
  35098. QuadraticErrorSimplification.prototype.init = function (callback) {
  35099. var _this = this;
  35100. var triangleInit1 = function (i) {
  35101. var t = _this.triangles[i];
  35102. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35103. for (var j = 0; j < 3; j++) {
  35104. 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))));
  35105. }
  35106. };
  35107. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35108. var triangleInit2 = function (i) {
  35109. var t = _this.triangles[i];
  35110. for (var j = 0; j < 3; ++j) {
  35111. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35112. }
  35113. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35114. };
  35115. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35116. _this.initialized = true;
  35117. callback();
  35118. });
  35119. });
  35120. };
  35121. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35122. var newTriangles = [];
  35123. var i;
  35124. for (i = 0; i < this.vertices.length; ++i) {
  35125. this.vertices[i].triangleCount = 0;
  35126. }
  35127. var t;
  35128. var j;
  35129. for (i = 0; i < this.triangles.length; ++i) {
  35130. if (!this.triangles[i].deleted) {
  35131. t = this.triangles[i];
  35132. for (j = 0; j < 3; ++j) {
  35133. t.vertices[j].triangleCount = 1;
  35134. }
  35135. newTriangles.push(t);
  35136. }
  35137. }
  35138. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35139. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35140. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35141. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35142. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35143. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35144. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35145. var vertexCount = 0;
  35146. for (i = 0; i < this.vertices.length; ++i) {
  35147. var vertex = this.vertices[i];
  35148. vertex.id = vertexCount;
  35149. if (vertex.triangleCount) {
  35150. vertex.originalOffsets.forEach(function (originalOffset) {
  35151. newPositionData.push(vertex.position.x);
  35152. newPositionData.push(vertex.position.y);
  35153. newPositionData.push(vertex.position.z);
  35154. newNormalData.push(normalData[originalOffset * 3]);
  35155. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35156. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35157. if (uvs && uvs.length) {
  35158. newUVsData.push(uvs[(originalOffset * 2)]);
  35159. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35160. }
  35161. else if (colorsData && colorsData.length) {
  35162. newColorsData.push(colorsData[(originalOffset * 4)]);
  35163. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35164. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35165. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35166. }
  35167. ++vertexCount;
  35168. });
  35169. }
  35170. }
  35171. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35172. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35173. var submeshesArray = this._reconstructedMesh.subMeshes;
  35174. this._reconstructedMesh.subMeshes = [];
  35175. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35176. var originalIndices = this._mesh.getIndices();
  35177. for (i = 0; i < newTriangles.length; ++i) {
  35178. t = newTriangles[i]; //now get the new referencing point for each vertex
  35179. [0, 1, 2].forEach(function (idx) {
  35180. var id = originalIndices[t.originalOffset + idx];
  35181. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35182. if (offset < 0)
  35183. offset = 0;
  35184. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35185. });
  35186. }
  35187. //overwriting the old vertex buffers and indices.
  35188. this._reconstructedMesh.setIndices(newIndicesArray);
  35189. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35190. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35191. if (newUVsData.length > 0)
  35192. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35193. if (newColorsData.length > 0)
  35194. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35195. //create submesh
  35196. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35197. if (submeshIndex > 0) {
  35198. this._reconstructedMesh.subMeshes = [];
  35199. submeshesArray.forEach(function (submesh) {
  35200. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35201. });
  35202. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35203. }
  35204. };
  35205. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35206. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35207. this._reconstructedMesh.material = this._mesh.material;
  35208. this._reconstructedMesh.parent = this._mesh.parent;
  35209. this._reconstructedMesh.isVisible = false;
  35210. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35211. };
  35212. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35213. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35214. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35215. if (t.deleted)
  35216. continue;
  35217. var s = this.references[vertex1.triangleStart + i].vertexId;
  35218. var v1 = t.vertices[(s + 1) % 3];
  35219. var v2 = t.vertices[(s + 2) % 3];
  35220. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35221. deletedArray[i] = true;
  35222. delTr.push(t);
  35223. continue;
  35224. }
  35225. var d1 = v1.position.subtract(point);
  35226. d1 = d1.normalize();
  35227. var d2 = v2.position.subtract(point);
  35228. d2 = d2.normalize();
  35229. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35230. return true;
  35231. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35232. deletedArray[i] = false;
  35233. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35234. return true;
  35235. }
  35236. return false;
  35237. };
  35238. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35239. var newDeleted = deletedTriangles;
  35240. for (var i = 0; i < vertex.triangleCount; ++i) {
  35241. var ref = this.references[vertex.triangleStart + i];
  35242. var t = this.triangles[ref.triangleId];
  35243. if (t.deleted)
  35244. continue;
  35245. if (deletedArray[i] && t.deletePending) {
  35246. t.deleted = true;
  35247. newDeleted++;
  35248. continue;
  35249. }
  35250. t.vertices[ref.vertexId] = origVertex;
  35251. t.isDirty = true;
  35252. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35253. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35254. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35255. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35256. this.references.push(ref);
  35257. }
  35258. return newDeleted;
  35259. };
  35260. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35261. for (var i = 0; i < this.vertices.length; ++i) {
  35262. var vCount = [];
  35263. var vId = [];
  35264. var v = this.vertices[i];
  35265. var j;
  35266. for (j = 0; j < v.triangleCount; ++j) {
  35267. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35268. for (var ii = 0; ii < 3; ii++) {
  35269. var ofs = 0;
  35270. var vv = triangle.vertices[ii];
  35271. while (ofs < vCount.length) {
  35272. if (vId[ofs] === vv.id)
  35273. break;
  35274. ++ofs;
  35275. }
  35276. if (ofs === vCount.length) {
  35277. vCount.push(1);
  35278. vId.push(vv.id);
  35279. }
  35280. else {
  35281. vCount[ofs]++;
  35282. }
  35283. }
  35284. }
  35285. for (j = 0; j < vCount.length; ++j) {
  35286. if (vCount[j] === 1) {
  35287. this.vertices[vId[j]].isBorder = true;
  35288. }
  35289. else {
  35290. this.vertices[vId[j]].isBorder = false;
  35291. }
  35292. }
  35293. }
  35294. };
  35295. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35296. if (identifyBorders === void 0) { identifyBorders = false; }
  35297. var i;
  35298. if (!identifyBorders) {
  35299. var newTrianglesVector = [];
  35300. for (i = 0; i < this.triangles.length; ++i) {
  35301. if (!this.triangles[i].deleted) {
  35302. newTrianglesVector.push(this.triangles[i]);
  35303. }
  35304. }
  35305. this.triangles = newTrianglesVector;
  35306. }
  35307. for (i = 0; i < this.vertices.length; ++i) {
  35308. this.vertices[i].triangleCount = 0;
  35309. this.vertices[i].triangleStart = 0;
  35310. }
  35311. var t;
  35312. var j;
  35313. var v;
  35314. for (i = 0; i < this.triangles.length; ++i) {
  35315. t = this.triangles[i];
  35316. for (j = 0; j < 3; ++j) {
  35317. v = t.vertices[j];
  35318. v.triangleCount++;
  35319. }
  35320. }
  35321. var tStart = 0;
  35322. for (i = 0; i < this.vertices.length; ++i) {
  35323. this.vertices[i].triangleStart = tStart;
  35324. tStart += this.vertices[i].triangleCount;
  35325. this.vertices[i].triangleCount = 0;
  35326. }
  35327. var newReferences = new Array(this.triangles.length * 3);
  35328. for (i = 0; i < this.triangles.length; ++i) {
  35329. t = this.triangles[i];
  35330. for (j = 0; j < 3; ++j) {
  35331. v = t.vertices[j];
  35332. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35333. v.triangleCount++;
  35334. }
  35335. }
  35336. this.references = newReferences;
  35337. if (identifyBorders) {
  35338. this.identifyBorder();
  35339. }
  35340. };
  35341. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35342. var x = point.x;
  35343. var y = point.y;
  35344. var z = point.z;
  35345. 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
  35346. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35347. };
  35348. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35349. var q = vertex1.q.add(vertex2.q);
  35350. var border = vertex1.isBorder && vertex2.isBorder;
  35351. var error = 0;
  35352. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35353. if (qDet !== 0 && !border) {
  35354. if (!pointResult) {
  35355. pointResult = BABYLON.Vector3.Zero();
  35356. }
  35357. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35358. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35359. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35360. error = this.vertexError(q, pointResult);
  35361. }
  35362. else {
  35363. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35364. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35365. var error1 = this.vertexError(q, vertex1.position);
  35366. var error2 = this.vertexError(q, vertex2.position);
  35367. var error3 = this.vertexError(q, p3);
  35368. error = Math.min(error1, error2, error3);
  35369. if (error === error1) {
  35370. if (pointResult) {
  35371. pointResult.copyFrom(vertex1.position);
  35372. }
  35373. }
  35374. else if (error === error2) {
  35375. if (pointResult) {
  35376. pointResult.copyFrom(vertex2.position);
  35377. }
  35378. }
  35379. else {
  35380. if (pointResult) {
  35381. pointResult.copyFrom(p3);
  35382. }
  35383. }
  35384. }
  35385. return error;
  35386. };
  35387. return QuadraticErrorSimplification;
  35388. })();
  35389. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35390. })(BABYLON || (BABYLON = {}));
  35391. var BABYLON;
  35392. (function (BABYLON) {
  35393. var serializedGeometries = [];
  35394. var serializeGeometry = function (geometry, serializationGeometries) {
  35395. if (serializedGeometries[geometry.id]) {
  35396. return;
  35397. }
  35398. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35399. serializationGeometries.boxes.push(geometry.serialize());
  35400. }
  35401. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35402. serializationGeometries.spheres.push(geometry.serialize());
  35403. }
  35404. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35405. serializationGeometries.cylinders.push(geometry.serialize());
  35406. }
  35407. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35408. serializationGeometries.toruses.push(geometry.serialize());
  35409. }
  35410. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35411. serializationGeometries.grounds.push(geometry.serialize());
  35412. }
  35413. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35414. serializationGeometries.planes.push(geometry.serialize());
  35415. }
  35416. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  35417. serializationGeometries.torusKnots.push(geometry.serialize());
  35418. }
  35419. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  35420. throw new Error("Unknown primitive type");
  35421. }
  35422. else {
  35423. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  35424. }
  35425. serializedGeometries[geometry.id] = true;
  35426. };
  35427. var serializeMesh = function (mesh, serializationScene) {
  35428. var serializationObject = {};
  35429. serializationObject.name = mesh.name;
  35430. serializationObject.id = mesh.id;
  35431. if (BABYLON.Tags.HasTags(mesh)) {
  35432. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  35433. }
  35434. serializationObject.position = mesh.position.asArray();
  35435. if (mesh.rotationQuaternion) {
  35436. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  35437. }
  35438. else if (mesh.rotation) {
  35439. serializationObject.rotation = mesh.rotation.asArray();
  35440. }
  35441. serializationObject.scaling = mesh.scaling.asArray();
  35442. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  35443. serializationObject.isEnabled = mesh.isEnabled();
  35444. serializationObject.isVisible = mesh.isVisible;
  35445. serializationObject.infiniteDistance = mesh.infiniteDistance;
  35446. serializationObject.pickable = mesh.isPickable;
  35447. serializationObject.receiveShadows = mesh.receiveShadows;
  35448. serializationObject.billboardMode = mesh.billboardMode;
  35449. serializationObject.visibility = mesh.visibility;
  35450. serializationObject.checkCollisions = mesh.checkCollisions;
  35451. // Parent
  35452. if (mesh.parent) {
  35453. serializationObject.parentId = mesh.parent.id;
  35454. }
  35455. // Geometry
  35456. var geometry = mesh._geometry;
  35457. if (geometry) {
  35458. var geometryId = geometry.id;
  35459. serializationObject.geometryId = geometryId;
  35460. if (!mesh.getScene().getGeometryByID(geometryId)) {
  35461. // 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
  35462. serializeGeometry(geometry, serializationScene.geometries);
  35463. }
  35464. // SubMeshes
  35465. serializationObject.subMeshes = [];
  35466. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35467. var subMesh = mesh.subMeshes[subIndex];
  35468. serializationObject.subMeshes.push({
  35469. materialIndex: subMesh.materialIndex,
  35470. verticesStart: subMesh.verticesStart,
  35471. verticesCount: subMesh.verticesCount,
  35472. indexStart: subMesh.indexStart,
  35473. indexCount: subMesh.indexCount
  35474. });
  35475. }
  35476. }
  35477. // Material
  35478. if (mesh.material) {
  35479. serializationObject.materialId = mesh.material.id;
  35480. }
  35481. else {
  35482. mesh.material = null;
  35483. }
  35484. // Skeleton
  35485. if (mesh.skeleton) {
  35486. serializationObject.skeletonId = mesh.skeleton.id;
  35487. }
  35488. // Physics
  35489. //TODO implement correct serialization for physics impostors.
  35490. if (mesh.getPhysicsImpostor()) {
  35491. serializationObject.physicsMass = mesh.getPhysicsMass();
  35492. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  35493. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  35494. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  35495. }
  35496. // Instances
  35497. serializationObject.instances = [];
  35498. for (var index = 0; index < mesh.instances.length; index++) {
  35499. var instance = mesh.instances[index];
  35500. var serializationInstance = {
  35501. name: instance.name,
  35502. position: instance.position.asArray(),
  35503. scaling: instance.scaling.asArray()
  35504. };
  35505. if (instance.rotationQuaternion) {
  35506. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  35507. }
  35508. else if (instance.rotation) {
  35509. serializationInstance.rotation = instance.rotation.asArray();
  35510. }
  35511. serializationObject.instances.push(serializationInstance);
  35512. // Animations
  35513. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  35514. serializationInstance.ranges = instance.serializeAnimationRanges();
  35515. }
  35516. // Animations
  35517. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  35518. serializationObject.ranges = mesh.serializeAnimationRanges();
  35519. // Layer mask
  35520. serializationObject.layerMask = mesh.layerMask;
  35521. return serializationObject;
  35522. };
  35523. var finalizeSingleMesh = function (mesh, serializationObject) {
  35524. //only works if the mesh is already loaded
  35525. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  35526. //serialize material
  35527. if (mesh.material) {
  35528. if (mesh.material instanceof BABYLON.StandardMaterial) {
  35529. serializationObject.materials = serializationObject.materials || [];
  35530. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35531. serializationObject.materials.push(mesh.material.serialize());
  35532. }
  35533. }
  35534. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  35535. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  35536. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35537. serializationObject.multiMaterials.push(mesh.material.serialize());
  35538. }
  35539. }
  35540. }
  35541. //serialize geometry
  35542. var geometry = mesh._geometry;
  35543. if (geometry) {
  35544. if (!serializationObject.geometries) {
  35545. serializationObject.geometries = {};
  35546. serializationObject.geometries.boxes = [];
  35547. serializationObject.geometries.spheres = [];
  35548. serializationObject.geometries.cylinders = [];
  35549. serializationObject.geometries.toruses = [];
  35550. serializationObject.geometries.grounds = [];
  35551. serializationObject.geometries.planes = [];
  35552. serializationObject.geometries.torusKnots = [];
  35553. serializationObject.geometries.vertexData = [];
  35554. }
  35555. serializeGeometry(geometry, serializationObject.geometries);
  35556. }
  35557. // Skeletons
  35558. if (mesh.skeleton) {
  35559. serializationObject.skeletons = serializationObject.skeletons || [];
  35560. serializationObject.skeletons.push(mesh.skeleton.serialize());
  35561. }
  35562. //serialize the actual mesh
  35563. serializationObject.meshes = serializationObject.meshes || [];
  35564. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  35565. }
  35566. };
  35567. var SceneSerializer = (function () {
  35568. function SceneSerializer() {
  35569. }
  35570. SceneSerializer.ClearCache = function () {
  35571. serializedGeometries = [];
  35572. };
  35573. SceneSerializer.Serialize = function (scene) {
  35574. var serializationObject = {};
  35575. // Scene
  35576. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  35577. serializationObject.autoClear = scene.autoClear;
  35578. serializationObject.clearColor = scene.clearColor.asArray();
  35579. serializationObject.ambientColor = scene.ambientColor.asArray();
  35580. serializationObject.gravity = scene.gravity.asArray();
  35581. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  35582. serializationObject.workerCollisions = scene.workerCollisions;
  35583. // Fog
  35584. if (scene.fogMode && scene.fogMode !== 0) {
  35585. serializationObject.fogMode = scene.fogMode;
  35586. serializationObject.fogColor = scene.fogColor.asArray();
  35587. serializationObject.fogStart = scene.fogStart;
  35588. serializationObject.fogEnd = scene.fogEnd;
  35589. serializationObject.fogDensity = scene.fogDensity;
  35590. }
  35591. //Physics
  35592. if (scene.isPhysicsEnabled()) {
  35593. serializationObject.physicsEnabled = true;
  35594. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  35595. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  35596. }
  35597. // Lights
  35598. serializationObject.lights = [];
  35599. var index;
  35600. var light;
  35601. for (index = 0; index < scene.lights.length; index++) {
  35602. light = scene.lights[index];
  35603. serializationObject.lights.push(light.serialize());
  35604. }
  35605. // Cameras
  35606. serializationObject.cameras = [];
  35607. for (index = 0; index < scene.cameras.length; index++) {
  35608. var camera = scene.cameras[index];
  35609. serializationObject.cameras.push(camera.serialize());
  35610. }
  35611. if (scene.activeCamera) {
  35612. serializationObject.activeCameraID = scene.activeCamera.id;
  35613. }
  35614. // Animations
  35615. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  35616. // Materials
  35617. serializationObject.materials = [];
  35618. serializationObject.multiMaterials = [];
  35619. var material;
  35620. for (index = 0; index < scene.materials.length; index++) {
  35621. material = scene.materials[index];
  35622. serializationObject.materials.push(material.serialize());
  35623. }
  35624. // MultiMaterials
  35625. serializationObject.multiMaterials = [];
  35626. for (index = 0; index < scene.multiMaterials.length; index++) {
  35627. var multiMaterial = scene.multiMaterials[index];
  35628. serializationObject.multiMaterials.push(multiMaterial.serialize());
  35629. }
  35630. // Skeletons
  35631. serializationObject.skeletons = [];
  35632. for (index = 0; index < scene.skeletons.length; index++) {
  35633. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  35634. }
  35635. // Geometries
  35636. serializationObject.geometries = {};
  35637. serializationObject.geometries.boxes = [];
  35638. serializationObject.geometries.spheres = [];
  35639. serializationObject.geometries.cylinders = [];
  35640. serializationObject.geometries.toruses = [];
  35641. serializationObject.geometries.grounds = [];
  35642. serializationObject.geometries.planes = [];
  35643. serializationObject.geometries.torusKnots = [];
  35644. serializationObject.geometries.vertexData = [];
  35645. serializedGeometries = [];
  35646. var geometries = scene.getGeometries();
  35647. for (index = 0; index < geometries.length; index++) {
  35648. var geometry = geometries[index];
  35649. if (geometry.isReady()) {
  35650. serializeGeometry(geometry, serializationObject.geometries);
  35651. }
  35652. }
  35653. // Meshes
  35654. serializationObject.meshes = [];
  35655. for (index = 0; index < scene.meshes.length; index++) {
  35656. var abstractMesh = scene.meshes[index];
  35657. if (abstractMesh instanceof BABYLON.Mesh) {
  35658. var mesh = abstractMesh;
  35659. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  35660. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  35661. }
  35662. }
  35663. }
  35664. // Particles Systems
  35665. serializationObject.particleSystems = [];
  35666. for (index = 0; index < scene.particleSystems.length; index++) {
  35667. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  35668. }
  35669. // Lens flares
  35670. serializationObject.lensFlareSystems = [];
  35671. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  35672. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  35673. }
  35674. // Shadows
  35675. serializationObject.shadowGenerators = [];
  35676. for (index = 0; index < scene.lights.length; index++) {
  35677. light = scene.lights[index];
  35678. if (light.getShadowGenerator()) {
  35679. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  35680. }
  35681. }
  35682. return serializationObject;
  35683. };
  35684. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  35685. if (withParents === void 0) { withParents = false; }
  35686. if (withChildren === void 0) { withChildren = false; }
  35687. var serializationObject = {};
  35688. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  35689. if (withParents || withChildren) {
  35690. //deliberate for loop! not for each, appended should be processed as well.
  35691. for (var i = 0; i < toSerialize.length; ++i) {
  35692. if (withChildren) {
  35693. toSerialize[i].getDescendants().forEach(function (node) {
  35694. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  35695. toSerialize.push(node);
  35696. }
  35697. });
  35698. }
  35699. //make sure the array doesn't contain the object already
  35700. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  35701. toSerialize.push(toSerialize[i].parent);
  35702. }
  35703. }
  35704. }
  35705. toSerialize.forEach(function (mesh) {
  35706. finalizeSingleMesh(mesh, serializationObject);
  35707. });
  35708. return serializationObject;
  35709. };
  35710. return SceneSerializer;
  35711. })();
  35712. BABYLON.SceneSerializer = SceneSerializer;
  35713. })(BABYLON || (BABYLON = {}));
  35714. var BABYLON;
  35715. (function (BABYLON) {
  35716. // Unique ID when we import meshes from Babylon to CSG
  35717. var currentCSGMeshId = 0;
  35718. // # class Vertex
  35719. // Represents a vertex of a polygon. Use your own vertex class instead of this
  35720. // one to provide additional features like texture coordinates and vertex
  35721. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  35722. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  35723. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  35724. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  35725. // is not used anywhere else.
  35726. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  35727. var Vertex = (function () {
  35728. function Vertex(pos, normal, uv) {
  35729. this.pos = pos;
  35730. this.normal = normal;
  35731. this.uv = uv;
  35732. }
  35733. Vertex.prototype.clone = function () {
  35734. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  35735. };
  35736. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  35737. // orientation of a polygon is flipped.
  35738. Vertex.prototype.flip = function () {
  35739. this.normal = this.normal.scale(-1);
  35740. };
  35741. // Create a new vertex between this vertex and `other` by linearly
  35742. // interpolating all properties using a parameter of `t`. Subclasses should
  35743. // override this to interpolate additional properties.
  35744. Vertex.prototype.interpolate = function (other, t) {
  35745. 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));
  35746. };
  35747. return Vertex;
  35748. })();
  35749. // # class Plane
  35750. // Represents a plane in 3D space.
  35751. var Plane = (function () {
  35752. function Plane(normal, w) {
  35753. this.normal = normal;
  35754. this.w = w;
  35755. }
  35756. Plane.FromPoints = function (a, b, c) {
  35757. var v0 = c.subtract(a);
  35758. var v1 = b.subtract(a);
  35759. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  35760. return null;
  35761. }
  35762. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  35763. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  35764. };
  35765. Plane.prototype.clone = function () {
  35766. return new Plane(this.normal.clone(), this.w);
  35767. };
  35768. Plane.prototype.flip = function () {
  35769. this.normal.scaleInPlace(-1);
  35770. this.w = -this.w;
  35771. };
  35772. // Split `polygon` by this plane if needed, then put the polygon or polygon
  35773. // fragments in the appropriate lists. Coplanar polygons go into either
  35774. // `coplanarFront` or `coplanarBack` depending on their orientation with
  35775. // respect to this plane. Polygons in front or in back of this plane go into
  35776. // either `front` or `back`.
  35777. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  35778. var COPLANAR = 0;
  35779. var FRONT = 1;
  35780. var BACK = 2;
  35781. var SPANNING = 3;
  35782. // Classify each point as well as the entire polygon into one of the above
  35783. // four classes.
  35784. var polygonType = 0;
  35785. var types = [];
  35786. var i;
  35787. var t;
  35788. for (i = 0; i < polygon.vertices.length; i++) {
  35789. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  35790. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  35791. polygonType |= type;
  35792. types.push(type);
  35793. }
  35794. // Put the polygon in the correct list, splitting it when necessary.
  35795. switch (polygonType) {
  35796. case COPLANAR:
  35797. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  35798. break;
  35799. case FRONT:
  35800. front.push(polygon);
  35801. break;
  35802. case BACK:
  35803. back.push(polygon);
  35804. break;
  35805. case SPANNING:
  35806. var f = [], b = [];
  35807. for (i = 0; i < polygon.vertices.length; i++) {
  35808. var j = (i + 1) % polygon.vertices.length;
  35809. var ti = types[i], tj = types[j];
  35810. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  35811. if (ti !== BACK)
  35812. f.push(vi);
  35813. if (ti !== FRONT)
  35814. b.push(ti !== BACK ? vi.clone() : vi);
  35815. if ((ti | tj) === SPANNING) {
  35816. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  35817. var v = vi.interpolate(vj, t);
  35818. f.push(v);
  35819. b.push(v.clone());
  35820. }
  35821. }
  35822. var poly;
  35823. if (f.length >= 3) {
  35824. poly = new Polygon(f, polygon.shared);
  35825. if (poly.plane)
  35826. front.push(poly);
  35827. }
  35828. if (b.length >= 3) {
  35829. poly = new Polygon(b, polygon.shared);
  35830. if (poly.plane)
  35831. back.push(poly);
  35832. }
  35833. break;
  35834. }
  35835. };
  35836. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  35837. // point is on the plane.
  35838. Plane.EPSILON = 1e-5;
  35839. return Plane;
  35840. })();
  35841. // # class Polygon
  35842. // Represents a convex polygon. The vertices used to initialize a polygon must
  35843. // be coplanar and form a convex loop.
  35844. //
  35845. // Each convex polygon has a `shared` property, which is shared between all
  35846. // polygons that are clones of each other or were split from the same polygon.
  35847. // This can be used to define per-polygon properties (such as surface color).
  35848. var Polygon = (function () {
  35849. function Polygon(vertices, shared) {
  35850. this.vertices = vertices;
  35851. this.shared = shared;
  35852. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  35853. }
  35854. Polygon.prototype.clone = function () {
  35855. var vertices = this.vertices.map(function (v) { return v.clone(); });
  35856. return new Polygon(vertices, this.shared);
  35857. };
  35858. Polygon.prototype.flip = function () {
  35859. this.vertices.reverse().map(function (v) { v.flip(); });
  35860. this.plane.flip();
  35861. };
  35862. return Polygon;
  35863. })();
  35864. // # class Node
  35865. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  35866. // by picking a polygon to split along. That polygon (and all other coplanar
  35867. // polygons) are added directly to that node and the other polygons are added to
  35868. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  35869. // no distinction between internal and leaf nodes.
  35870. var Node = (function () {
  35871. function Node(polygons) {
  35872. this.plane = null;
  35873. this.front = null;
  35874. this.back = null;
  35875. this.polygons = [];
  35876. if (polygons) {
  35877. this.build(polygons);
  35878. }
  35879. }
  35880. Node.prototype.clone = function () {
  35881. var node = new Node();
  35882. node.plane = this.plane && this.plane.clone();
  35883. node.front = this.front && this.front.clone();
  35884. node.back = this.back && this.back.clone();
  35885. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  35886. return node;
  35887. };
  35888. // Convert solid space to empty space and empty space to solid space.
  35889. Node.prototype.invert = function () {
  35890. for (var i = 0; i < this.polygons.length; i++) {
  35891. this.polygons[i].flip();
  35892. }
  35893. if (this.plane) {
  35894. this.plane.flip();
  35895. }
  35896. if (this.front) {
  35897. this.front.invert();
  35898. }
  35899. if (this.back) {
  35900. this.back.invert();
  35901. }
  35902. var temp = this.front;
  35903. this.front = this.back;
  35904. this.back = temp;
  35905. };
  35906. // Recursively remove all polygons in `polygons` that are inside this BSP
  35907. // tree.
  35908. Node.prototype.clipPolygons = function (polygons) {
  35909. if (!this.plane)
  35910. return polygons.slice();
  35911. var front = [], back = [];
  35912. for (var i = 0; i < polygons.length; i++) {
  35913. this.plane.splitPolygon(polygons[i], front, back, front, back);
  35914. }
  35915. if (this.front) {
  35916. front = this.front.clipPolygons(front);
  35917. }
  35918. if (this.back) {
  35919. back = this.back.clipPolygons(back);
  35920. }
  35921. else {
  35922. back = [];
  35923. }
  35924. return front.concat(back);
  35925. };
  35926. // Remove all polygons in this BSP tree that are inside the other BSP tree
  35927. // `bsp`.
  35928. Node.prototype.clipTo = function (bsp) {
  35929. this.polygons = bsp.clipPolygons(this.polygons);
  35930. if (this.front)
  35931. this.front.clipTo(bsp);
  35932. if (this.back)
  35933. this.back.clipTo(bsp);
  35934. };
  35935. // Return a list of all polygons in this BSP tree.
  35936. Node.prototype.allPolygons = function () {
  35937. var polygons = this.polygons.slice();
  35938. if (this.front)
  35939. polygons = polygons.concat(this.front.allPolygons());
  35940. if (this.back)
  35941. polygons = polygons.concat(this.back.allPolygons());
  35942. return polygons;
  35943. };
  35944. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  35945. // new polygons are filtered down to the bottom of the tree and become new
  35946. // nodes there. Each set of polygons is partitioned using the first polygon
  35947. // (no heuristic is used to pick a good split).
  35948. Node.prototype.build = function (polygons) {
  35949. if (!polygons.length)
  35950. return;
  35951. if (!this.plane)
  35952. this.plane = polygons[0].plane.clone();
  35953. var front = [], back = [];
  35954. for (var i = 0; i < polygons.length; i++) {
  35955. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  35956. }
  35957. if (front.length) {
  35958. if (!this.front)
  35959. this.front = new Node();
  35960. this.front.build(front);
  35961. }
  35962. if (back.length) {
  35963. if (!this.back)
  35964. this.back = new Node();
  35965. this.back.build(back);
  35966. }
  35967. };
  35968. return Node;
  35969. })();
  35970. var CSG = (function () {
  35971. function CSG() {
  35972. this.polygons = new Array();
  35973. }
  35974. // Convert BABYLON.Mesh to BABYLON.CSG
  35975. CSG.FromMesh = function (mesh) {
  35976. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  35977. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  35978. if (mesh instanceof BABYLON.Mesh) {
  35979. mesh.computeWorldMatrix(true);
  35980. matrix = mesh.getWorldMatrix();
  35981. meshPosition = mesh.position.clone();
  35982. meshRotation = mesh.rotation.clone();
  35983. if (mesh.rotationQuaternion) {
  35984. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  35985. }
  35986. meshScaling = mesh.scaling.clone();
  35987. }
  35988. else {
  35989. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  35990. }
  35991. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35992. var subMeshes = mesh.subMeshes;
  35993. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  35994. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  35995. vertices = [];
  35996. for (var j = 0; j < 3; j++) {
  35997. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  35998. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  35999. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36000. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36001. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36002. vertex = new Vertex(position, normal, uv);
  36003. vertices.push(vertex);
  36004. }
  36005. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36006. // To handle the case of degenerated triangle
  36007. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36008. if (polygon.plane)
  36009. polygons.push(polygon);
  36010. }
  36011. }
  36012. var csg = CSG.FromPolygons(polygons);
  36013. csg.matrix = matrix;
  36014. csg.position = meshPosition;
  36015. csg.rotation = meshRotation;
  36016. csg.scaling = meshScaling;
  36017. csg.rotationQuaternion = meshRotationQuaternion;
  36018. currentCSGMeshId++;
  36019. return csg;
  36020. };
  36021. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36022. CSG.FromPolygons = function (polygons) {
  36023. var csg = new CSG();
  36024. csg.polygons = polygons;
  36025. return csg;
  36026. };
  36027. CSG.prototype.clone = function () {
  36028. var csg = new CSG();
  36029. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36030. csg.copyTransformAttributes(this);
  36031. return csg;
  36032. };
  36033. CSG.prototype.toPolygons = function () {
  36034. return this.polygons;
  36035. };
  36036. CSG.prototype.union = function (csg) {
  36037. var a = new Node(this.clone().polygons);
  36038. var b = new Node(csg.clone().polygons);
  36039. a.clipTo(b);
  36040. b.clipTo(a);
  36041. b.invert();
  36042. b.clipTo(a);
  36043. b.invert();
  36044. a.build(b.allPolygons());
  36045. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36046. };
  36047. CSG.prototype.unionInPlace = function (csg) {
  36048. var a = new Node(this.polygons);
  36049. var b = new Node(csg.polygons);
  36050. a.clipTo(b);
  36051. b.clipTo(a);
  36052. b.invert();
  36053. b.clipTo(a);
  36054. b.invert();
  36055. a.build(b.allPolygons());
  36056. this.polygons = a.allPolygons();
  36057. };
  36058. CSG.prototype.subtract = function (csg) {
  36059. var a = new Node(this.clone().polygons);
  36060. var b = new Node(csg.clone().polygons);
  36061. a.invert();
  36062. a.clipTo(b);
  36063. b.clipTo(a);
  36064. b.invert();
  36065. b.clipTo(a);
  36066. b.invert();
  36067. a.build(b.allPolygons());
  36068. a.invert();
  36069. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36070. };
  36071. CSG.prototype.subtractInPlace = function (csg) {
  36072. var a = new Node(this.polygons);
  36073. var b = new Node(csg.polygons);
  36074. a.invert();
  36075. a.clipTo(b);
  36076. b.clipTo(a);
  36077. b.invert();
  36078. b.clipTo(a);
  36079. b.invert();
  36080. a.build(b.allPolygons());
  36081. a.invert();
  36082. this.polygons = a.allPolygons();
  36083. };
  36084. CSG.prototype.intersect = function (csg) {
  36085. var a = new Node(this.clone().polygons);
  36086. var b = new Node(csg.clone().polygons);
  36087. a.invert();
  36088. b.clipTo(a);
  36089. b.invert();
  36090. a.clipTo(b);
  36091. b.clipTo(a);
  36092. a.build(b.allPolygons());
  36093. a.invert();
  36094. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36095. };
  36096. CSG.prototype.intersectInPlace = function (csg) {
  36097. var a = new Node(this.polygons);
  36098. var b = new Node(csg.polygons);
  36099. a.invert();
  36100. b.clipTo(a);
  36101. b.invert();
  36102. a.clipTo(b);
  36103. b.clipTo(a);
  36104. a.build(b.allPolygons());
  36105. a.invert();
  36106. this.polygons = a.allPolygons();
  36107. };
  36108. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36109. // not modified.
  36110. CSG.prototype.inverse = function () {
  36111. var csg = this.clone();
  36112. csg.inverseInPlace();
  36113. return csg;
  36114. };
  36115. CSG.prototype.inverseInPlace = function () {
  36116. this.polygons.map(function (p) { p.flip(); });
  36117. };
  36118. // This is used to keep meshes transformations so they can be restored
  36119. // when we build back a Babylon Mesh
  36120. // NB : All CSG operations are performed in world coordinates
  36121. CSG.prototype.copyTransformAttributes = function (csg) {
  36122. this.matrix = csg.matrix;
  36123. this.position = csg.position;
  36124. this.rotation = csg.rotation;
  36125. this.scaling = csg.scaling;
  36126. this.rotationQuaternion = csg.rotationQuaternion;
  36127. return this;
  36128. };
  36129. // Build Raw mesh from CSG
  36130. // Coordinates here are in world space
  36131. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36132. var matrix = this.matrix.clone();
  36133. matrix.invert();
  36134. 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;
  36135. if (keepSubMeshes) {
  36136. // Sort Polygons, since subMeshes are indices range
  36137. polygons.sort(function (a, b) {
  36138. if (a.shared.meshId === b.shared.meshId) {
  36139. return a.shared.subMeshId - b.shared.subMeshId;
  36140. }
  36141. else {
  36142. return a.shared.meshId - b.shared.meshId;
  36143. }
  36144. });
  36145. }
  36146. for (var i = 0, il = polygons.length; i < il; i++) {
  36147. polygon = polygons[i];
  36148. // Building SubMeshes
  36149. if (!subMesh_dict[polygon.shared.meshId]) {
  36150. subMesh_dict[polygon.shared.meshId] = {};
  36151. }
  36152. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36153. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36154. indexStart: +Infinity,
  36155. indexEnd: -Infinity,
  36156. materialIndex: polygon.shared.materialIndex
  36157. };
  36158. }
  36159. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36160. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36161. polygonIndices[0] = 0;
  36162. polygonIndices[1] = j - 1;
  36163. polygonIndices[2] = j;
  36164. for (var k = 0; k < 3; k++) {
  36165. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36166. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36167. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36168. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36169. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36170. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36171. // Check if 2 points can be merged
  36172. if (!(typeof vertex_idx !== 'undefined' &&
  36173. normals[vertex_idx * 3] === localNormal.x &&
  36174. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36175. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36176. uvs[vertex_idx * 2] === uv.x &&
  36177. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36178. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36179. uvs.push(uv.x, uv.y);
  36180. normals.push(normal.x, normal.y, normal.z);
  36181. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36182. }
  36183. indices.push(vertex_idx);
  36184. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36185. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36186. currentIndex++;
  36187. }
  36188. }
  36189. }
  36190. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36191. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36192. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36193. mesh.setIndices(indices);
  36194. if (keepSubMeshes) {
  36195. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36196. var materialIndexOffset = 0, materialMaxIndex;
  36197. mesh.subMeshes = new Array();
  36198. for (var m in subMesh_dict) {
  36199. materialMaxIndex = -1;
  36200. for (var sm in subMesh_dict[m]) {
  36201. subMesh_obj = subMesh_dict[m][sm];
  36202. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36203. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36204. }
  36205. materialIndexOffset += ++materialMaxIndex;
  36206. }
  36207. }
  36208. return mesh;
  36209. };
  36210. // Build Mesh from CSG taking material and transforms into account
  36211. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36212. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36213. mesh.material = material;
  36214. mesh.position.copyFrom(this.position);
  36215. mesh.rotation.copyFrom(this.rotation);
  36216. if (this.rotationQuaternion) {
  36217. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36218. }
  36219. mesh.scaling.copyFrom(this.scaling);
  36220. mesh.computeWorldMatrix(true);
  36221. return mesh;
  36222. };
  36223. return CSG;
  36224. })();
  36225. BABYLON.CSG = CSG;
  36226. })(BABYLON || (BABYLON = {}));
  36227. var BABYLON;
  36228. (function (BABYLON) {
  36229. var VRDistortionCorrectionPostProcess = (function (_super) {
  36230. __extends(VRDistortionCorrectionPostProcess, _super);
  36231. //ANY
  36232. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36233. var _this = this;
  36234. _super.call(this, name, "vrDistortionCorrection", [
  36235. 'LensCenter',
  36236. 'Scale',
  36237. 'ScaleIn',
  36238. 'HmdWarpParam'
  36239. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36240. this._isRightEye = isRightEye;
  36241. this._distortionFactors = vrMetrics.distortionK;
  36242. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36243. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36244. this.onSizeChanged = function () {
  36245. _this.aspectRatio = _this.width * .5 / _this.height;
  36246. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36247. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36248. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36249. };
  36250. this.onApply = function (effect) {
  36251. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36252. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36253. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36254. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36255. };
  36256. }
  36257. return VRDistortionCorrectionPostProcess;
  36258. })(BABYLON.PostProcess);
  36259. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36260. })(BABYLON || (BABYLON = {}));
  36261. // Mainly based on these 2 articles :
  36262. // 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
  36263. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36264. var BABYLON;
  36265. (function (BABYLON) {
  36266. (function (JoystickAxis) {
  36267. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36268. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36269. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36270. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36271. var JoystickAxis = BABYLON.JoystickAxis;
  36272. var VirtualJoystick = (function () {
  36273. function VirtualJoystick(leftJoystick) {
  36274. var _this = this;
  36275. if (leftJoystick) {
  36276. this._leftJoystick = true;
  36277. }
  36278. else {
  36279. this._leftJoystick = false;
  36280. }
  36281. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36282. VirtualJoystick._globalJoystickIndex++;
  36283. // By default left & right arrow keys are moving the X
  36284. // and up & down keys are moving the Y
  36285. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36286. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36287. this.reverseLeftRight = false;
  36288. this.reverseUpDown = false;
  36289. // collections of pointers
  36290. this._touches = new BABYLON.SmartCollection();
  36291. this.deltaPosition = BABYLON.Vector3.Zero();
  36292. this._joystickSensibility = 25;
  36293. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36294. this._rotationSpeed = 25;
  36295. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36296. this._rotateOnAxisRelativeToMesh = false;
  36297. this._onResize = function (evt) {
  36298. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36299. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36300. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36301. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36302. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36303. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36304. };
  36305. // injecting a canvas element on top of the canvas 3D game
  36306. if (!VirtualJoystick.vjCanvas) {
  36307. window.addEventListener("resize", this._onResize, false);
  36308. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36309. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36310. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36311. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36312. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36313. VirtualJoystick.vjCanvas.style.width = "100%";
  36314. VirtualJoystick.vjCanvas.style.height = "100%";
  36315. VirtualJoystick.vjCanvas.style.position = "absolute";
  36316. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36317. VirtualJoystick.vjCanvas.style.top = "0px";
  36318. VirtualJoystick.vjCanvas.style.left = "0px";
  36319. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36320. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36321. // Support for jQuery PEP polyfill
  36322. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36323. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36324. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36325. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36326. document.body.appendChild(VirtualJoystick.vjCanvas);
  36327. }
  36328. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36329. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36330. this.pressed = false;
  36331. // default joystick color
  36332. this._joystickColor = "cyan";
  36333. this._joystickPointerID = -1;
  36334. // current joystick position
  36335. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36336. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36337. // origin joystick position
  36338. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36339. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36340. this._onPointerDownHandlerRef = function (evt) {
  36341. _this._onPointerDown(evt);
  36342. };
  36343. this._onPointerMoveHandlerRef = function (evt) {
  36344. _this._onPointerMove(evt);
  36345. };
  36346. this._onPointerOutHandlerRef = function (evt) {
  36347. _this._onPointerUp(evt);
  36348. };
  36349. this._onPointerUpHandlerRef = function (evt) {
  36350. _this._onPointerUp(evt);
  36351. };
  36352. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36353. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36354. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36355. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36356. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36357. evt.preventDefault(); // Disables system menu
  36358. }, false);
  36359. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36360. }
  36361. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36362. this._joystickSensibility = newJoystickSensibility;
  36363. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36364. };
  36365. VirtualJoystick.prototype._onPointerDown = function (e) {
  36366. var positionOnScreenCondition;
  36367. e.preventDefault();
  36368. if (this._leftJoystick === true) {
  36369. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36370. }
  36371. else {
  36372. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36373. }
  36374. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36375. // First contact will be dedicated to the virtual joystick
  36376. this._joystickPointerID = e.pointerId;
  36377. this._joystickPointerStartPos.x = e.clientX;
  36378. this._joystickPointerStartPos.y = e.clientY;
  36379. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36380. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36381. this._deltaJoystickVector.x = 0;
  36382. this._deltaJoystickVector.y = 0;
  36383. this.pressed = true;
  36384. this._touches.add(e.pointerId.toString(), e);
  36385. }
  36386. else {
  36387. // You can only trigger the action buttons with a joystick declared
  36388. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36389. this._action();
  36390. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36391. }
  36392. }
  36393. };
  36394. VirtualJoystick.prototype._onPointerMove = function (e) {
  36395. // If the current pointer is the one associated to the joystick (first touch contact)
  36396. if (this._joystickPointerID == e.pointerId) {
  36397. this._joystickPointerPos.x = e.clientX;
  36398. this._joystickPointerPos.y = e.clientY;
  36399. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36400. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36401. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36402. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36403. switch (this._axisTargetedByLeftAndRight) {
  36404. case JoystickAxis.X:
  36405. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36406. break;
  36407. case JoystickAxis.Y:
  36408. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36409. break;
  36410. case JoystickAxis.Z:
  36411. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36412. break;
  36413. }
  36414. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36415. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36416. switch (this._axisTargetedByUpAndDown) {
  36417. case JoystickAxis.X:
  36418. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  36419. break;
  36420. case JoystickAxis.Y:
  36421. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  36422. break;
  36423. case JoystickAxis.Z:
  36424. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  36425. break;
  36426. }
  36427. }
  36428. else {
  36429. if (this._touches.item(e.pointerId.toString())) {
  36430. this._touches.item(e.pointerId.toString()).x = e.clientX;
  36431. this._touches.item(e.pointerId.toString()).y = e.clientY;
  36432. }
  36433. }
  36434. };
  36435. VirtualJoystick.prototype._onPointerUp = function (e) {
  36436. if (this._joystickPointerID == e.pointerId) {
  36437. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  36438. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  36439. this._joystickPointerID = -1;
  36440. this.pressed = false;
  36441. }
  36442. else {
  36443. var touch = this._touches.item(e.pointerId.toString());
  36444. if (touch) {
  36445. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36446. }
  36447. }
  36448. this._deltaJoystickVector.x = 0;
  36449. this._deltaJoystickVector.y = 0;
  36450. this._touches.remove(e.pointerId.toString());
  36451. };
  36452. /**
  36453. * Change the color of the virtual joystick
  36454. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  36455. */
  36456. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  36457. this._joystickColor = newColor;
  36458. };
  36459. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  36460. this._action = action;
  36461. };
  36462. // Define which axis you'd like to control for left & right
  36463. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  36464. switch (axis) {
  36465. case JoystickAxis.X:
  36466. case JoystickAxis.Y:
  36467. case JoystickAxis.Z:
  36468. this._axisTargetedByLeftAndRight = axis;
  36469. break;
  36470. default:
  36471. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36472. break;
  36473. }
  36474. };
  36475. // Define which axis you'd like to control for up & down
  36476. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  36477. switch (axis) {
  36478. case JoystickAxis.X:
  36479. case JoystickAxis.Y:
  36480. case JoystickAxis.Z:
  36481. this._axisTargetedByUpAndDown = axis;
  36482. break;
  36483. default:
  36484. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36485. break;
  36486. }
  36487. };
  36488. VirtualJoystick.prototype._clearCanvas = function () {
  36489. if (this._leftJoystick) {
  36490. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  36491. }
  36492. else {
  36493. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  36494. }
  36495. };
  36496. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  36497. var _this = this;
  36498. if (this.pressed) {
  36499. this._touches.forEach(function (touch) {
  36500. if (touch.pointerId === _this._joystickPointerID) {
  36501. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  36502. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  36503. VirtualJoystick.vjCanvasContext.beginPath();
  36504. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36505. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36506. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  36507. VirtualJoystick.vjCanvasContext.stroke();
  36508. VirtualJoystick.vjCanvasContext.closePath();
  36509. VirtualJoystick.vjCanvasContext.beginPath();
  36510. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36511. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36512. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  36513. VirtualJoystick.vjCanvasContext.stroke();
  36514. VirtualJoystick.vjCanvasContext.closePath();
  36515. VirtualJoystick.vjCanvasContext.beginPath();
  36516. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36517. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  36518. VirtualJoystick.vjCanvasContext.stroke();
  36519. VirtualJoystick.vjCanvasContext.closePath();
  36520. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  36521. }
  36522. else {
  36523. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36524. VirtualJoystick.vjCanvasContext.beginPath();
  36525. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  36526. VirtualJoystick.vjCanvasContext.beginPath();
  36527. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  36528. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36529. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  36530. VirtualJoystick.vjCanvasContext.stroke();
  36531. VirtualJoystick.vjCanvasContext.closePath();
  36532. touch.prevX = touch.x;
  36533. touch.prevY = touch.y;
  36534. }
  36535. ;
  36536. });
  36537. }
  36538. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36539. };
  36540. VirtualJoystick.prototype.releaseCanvas = function () {
  36541. if (VirtualJoystick.vjCanvas) {
  36542. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  36543. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  36544. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  36545. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  36546. window.removeEventListener("resize", this._onResize);
  36547. document.body.removeChild(VirtualJoystick.vjCanvas);
  36548. VirtualJoystick.vjCanvas = null;
  36549. }
  36550. };
  36551. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  36552. VirtualJoystick._globalJoystickIndex = 0;
  36553. return VirtualJoystick;
  36554. })();
  36555. BABYLON.VirtualJoystick = VirtualJoystick;
  36556. })(BABYLON || (BABYLON = {}));
  36557. var BABYLON;
  36558. (function (BABYLON) {
  36559. // We're mainly based on the logic defined into the FreeCamera code
  36560. var VirtualJoysticksCamera = (function (_super) {
  36561. __extends(VirtualJoysticksCamera, _super);
  36562. function VirtualJoysticksCamera(name, position, scene) {
  36563. _super.call(this, name, position, scene);
  36564. this.inputs.addVirtualJoystick();
  36565. }
  36566. return VirtualJoysticksCamera;
  36567. })(BABYLON.FreeCamera);
  36568. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  36569. })(BABYLON || (BABYLON = {}));
  36570. var BABYLON;
  36571. (function (BABYLON) {
  36572. var AnaglyphPostProcess = (function (_super) {
  36573. __extends(AnaglyphPostProcess, _super);
  36574. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36575. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  36576. }
  36577. return AnaglyphPostProcess;
  36578. })(BABYLON.PostProcess);
  36579. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  36580. })(BABYLON || (BABYLON = {}));
  36581. var BABYLON;
  36582. (function (BABYLON) {
  36583. var OutlineRenderer = (function () {
  36584. function OutlineRenderer(scene) {
  36585. this._scene = scene;
  36586. }
  36587. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  36588. var _this = this;
  36589. if (useOverlay === void 0) { useOverlay = false; }
  36590. var scene = this._scene;
  36591. var engine = this._scene.getEngine();
  36592. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  36593. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  36594. return;
  36595. }
  36596. var mesh = subMesh.getRenderingMesh();
  36597. var material = subMesh.getMaterial();
  36598. engine.enableEffect(this._effect);
  36599. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  36600. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  36601. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  36602. // Bones
  36603. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36604. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36605. }
  36606. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  36607. // Alpha test
  36608. if (material && material.needAlphaTesting()) {
  36609. var alphaTexture = material.getAlphaTestTexture();
  36610. this._effect.setTexture("diffuseSampler", alphaTexture);
  36611. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36612. }
  36613. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  36614. };
  36615. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  36616. var defines = [];
  36617. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  36618. var mesh = subMesh.getMesh();
  36619. var material = subMesh.getMaterial();
  36620. // Alpha test
  36621. if (material && material.needAlphaTesting()) {
  36622. defines.push("#define ALPHATEST");
  36623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36624. attribs.push(BABYLON.VertexBuffer.UVKind);
  36625. defines.push("#define UV1");
  36626. }
  36627. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36628. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36629. defines.push("#define UV2");
  36630. }
  36631. }
  36632. // Bones
  36633. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36634. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36635. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36636. if (mesh.numBoneInfluencers > 4) {
  36637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36639. }
  36640. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36641. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36642. }
  36643. else {
  36644. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36645. }
  36646. // Instances
  36647. if (useInstances) {
  36648. defines.push("#define INSTANCES");
  36649. attribs.push("world0");
  36650. attribs.push("world1");
  36651. attribs.push("world2");
  36652. attribs.push("world3");
  36653. }
  36654. // Get correct effect
  36655. var join = defines.join("\n");
  36656. if (this._cachedDefines !== join) {
  36657. this._cachedDefines = join;
  36658. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  36659. }
  36660. return this._effect.isReady();
  36661. };
  36662. return OutlineRenderer;
  36663. })();
  36664. BABYLON.OutlineRenderer = OutlineRenderer;
  36665. })(BABYLON || (BABYLON = {}));
  36666. var BABYLON;
  36667. (function (BABYLON) {
  36668. var MeshAssetTask = (function () {
  36669. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  36670. this.name = name;
  36671. this.meshesNames = meshesNames;
  36672. this.rootUrl = rootUrl;
  36673. this.sceneFilename = sceneFilename;
  36674. this.isCompleted = false;
  36675. }
  36676. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  36677. var _this = this;
  36678. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  36679. _this.loadedMeshes = meshes;
  36680. _this.loadedParticleSystems = particleSystems;
  36681. _this.loadedSkeletons = skeletons;
  36682. _this.isCompleted = true;
  36683. if (_this.onSuccess) {
  36684. _this.onSuccess(_this);
  36685. }
  36686. onSuccess();
  36687. }, null, function () {
  36688. if (_this.onError) {
  36689. _this.onError(_this);
  36690. }
  36691. onError();
  36692. });
  36693. };
  36694. return MeshAssetTask;
  36695. })();
  36696. BABYLON.MeshAssetTask = MeshAssetTask;
  36697. var TextFileAssetTask = (function () {
  36698. function TextFileAssetTask(name, url) {
  36699. this.name = name;
  36700. this.url = url;
  36701. this.isCompleted = false;
  36702. }
  36703. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  36704. var _this = this;
  36705. BABYLON.Tools.LoadFile(this.url, function (data) {
  36706. _this.text = data;
  36707. _this.isCompleted = true;
  36708. if (_this.onSuccess) {
  36709. _this.onSuccess(_this);
  36710. }
  36711. onSuccess();
  36712. }, null, scene.database, false, function () {
  36713. if (_this.onError) {
  36714. _this.onError(_this);
  36715. }
  36716. onError();
  36717. });
  36718. };
  36719. return TextFileAssetTask;
  36720. })();
  36721. BABYLON.TextFileAssetTask = TextFileAssetTask;
  36722. var BinaryFileAssetTask = (function () {
  36723. function BinaryFileAssetTask(name, url) {
  36724. this.name = name;
  36725. this.url = url;
  36726. this.isCompleted = false;
  36727. }
  36728. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  36729. var _this = this;
  36730. BABYLON.Tools.LoadFile(this.url, function (data) {
  36731. _this.data = data;
  36732. _this.isCompleted = true;
  36733. if (_this.onSuccess) {
  36734. _this.onSuccess(_this);
  36735. }
  36736. onSuccess();
  36737. }, null, scene.database, true, function () {
  36738. if (_this.onError) {
  36739. _this.onError(_this);
  36740. }
  36741. onError();
  36742. });
  36743. };
  36744. return BinaryFileAssetTask;
  36745. })();
  36746. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  36747. var ImageAssetTask = (function () {
  36748. function ImageAssetTask(name, url) {
  36749. this.name = name;
  36750. this.url = url;
  36751. this.isCompleted = false;
  36752. }
  36753. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  36754. var _this = this;
  36755. var img = new Image();
  36756. img.onload = function () {
  36757. _this.image = img;
  36758. _this.isCompleted = true;
  36759. if (_this.onSuccess) {
  36760. _this.onSuccess(_this);
  36761. }
  36762. onSuccess();
  36763. };
  36764. img.onerror = function () {
  36765. if (_this.onError) {
  36766. _this.onError(_this);
  36767. }
  36768. onError();
  36769. };
  36770. img.src = this.url;
  36771. };
  36772. return ImageAssetTask;
  36773. })();
  36774. BABYLON.ImageAssetTask = ImageAssetTask;
  36775. var TextureAssetTask = (function () {
  36776. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  36777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36778. this.name = name;
  36779. this.url = url;
  36780. this.noMipmap = noMipmap;
  36781. this.invertY = invertY;
  36782. this.samplingMode = samplingMode;
  36783. this.isCompleted = false;
  36784. }
  36785. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  36786. var _this = this;
  36787. var onload = function () {
  36788. _this.isCompleted = true;
  36789. if (_this.onSuccess) {
  36790. _this.onSuccess(_this);
  36791. }
  36792. onSuccess();
  36793. };
  36794. var onerror = function () {
  36795. if (_this.onError) {
  36796. _this.onError(_this);
  36797. }
  36798. onError();
  36799. };
  36800. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  36801. };
  36802. return TextureAssetTask;
  36803. })();
  36804. BABYLON.TextureAssetTask = TextureAssetTask;
  36805. var AssetsManager = (function () {
  36806. function AssetsManager(scene) {
  36807. this._tasks = new Array();
  36808. this._waitingTasksCount = 0;
  36809. this.useDefaultLoadingScreen = true;
  36810. this._scene = scene;
  36811. }
  36812. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  36813. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  36814. this._tasks.push(task);
  36815. return task;
  36816. };
  36817. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  36818. var task = new TextFileAssetTask(taskName, url);
  36819. this._tasks.push(task);
  36820. return task;
  36821. };
  36822. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  36823. var task = new BinaryFileAssetTask(taskName, url);
  36824. this._tasks.push(task);
  36825. return task;
  36826. };
  36827. AssetsManager.prototype.addImageTask = function (taskName, url) {
  36828. var task = new ImageAssetTask(taskName, url);
  36829. this._tasks.push(task);
  36830. return task;
  36831. };
  36832. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  36833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36834. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  36835. this._tasks.push(task);
  36836. return task;
  36837. };
  36838. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  36839. this._waitingTasksCount--;
  36840. if (this._waitingTasksCount === 0) {
  36841. if (this.onFinish) {
  36842. this.onFinish(this._tasks);
  36843. }
  36844. this._scene.getEngine().hideLoadingUI();
  36845. }
  36846. };
  36847. AssetsManager.prototype._runTask = function (task) {
  36848. var _this = this;
  36849. task.run(this._scene, function () {
  36850. if (_this.onTaskSuccess) {
  36851. _this.onTaskSuccess(task);
  36852. }
  36853. _this._decreaseWaitingTasksCount();
  36854. }, function () {
  36855. if (_this.onTaskError) {
  36856. _this.onTaskError(task);
  36857. }
  36858. _this._decreaseWaitingTasksCount();
  36859. });
  36860. };
  36861. AssetsManager.prototype.reset = function () {
  36862. this._tasks = new Array();
  36863. return this;
  36864. };
  36865. AssetsManager.prototype.load = function () {
  36866. this._waitingTasksCount = this._tasks.length;
  36867. if (this._waitingTasksCount === 0) {
  36868. if (this.onFinish) {
  36869. this.onFinish(this._tasks);
  36870. }
  36871. return this;
  36872. }
  36873. if (this.useDefaultLoadingScreen) {
  36874. this._scene.getEngine().displayLoadingUI();
  36875. }
  36876. for (var index = 0; index < this._tasks.length; index++) {
  36877. var task = this._tasks[index];
  36878. this._runTask(task);
  36879. }
  36880. return this;
  36881. };
  36882. return AssetsManager;
  36883. })();
  36884. BABYLON.AssetsManager = AssetsManager;
  36885. })(BABYLON || (BABYLON = {}));
  36886. var BABYLON;
  36887. (function (BABYLON) {
  36888. var VRCameraMetrics = (function () {
  36889. function VRCameraMetrics() {
  36890. this.compensateDistortion = true;
  36891. }
  36892. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  36893. get: function () {
  36894. return this.hResolution / (2 * this.vResolution);
  36895. },
  36896. enumerable: true,
  36897. configurable: true
  36898. });
  36899. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  36900. get: function () {
  36901. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  36902. },
  36903. enumerable: true,
  36904. configurable: true
  36905. });
  36906. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  36907. get: function () {
  36908. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  36909. var h = (4 * meters) / this.hScreenSize;
  36910. return BABYLON.Matrix.Translation(h, 0, 0);
  36911. },
  36912. enumerable: true,
  36913. configurable: true
  36914. });
  36915. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  36916. get: function () {
  36917. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  36918. var h = (4 * meters) / this.hScreenSize;
  36919. return BABYLON.Matrix.Translation(-h, 0, 0);
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  36925. get: function () {
  36926. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  36932. get: function () {
  36933. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  36934. },
  36935. enumerable: true,
  36936. configurable: true
  36937. });
  36938. VRCameraMetrics.GetDefault = function () {
  36939. var result = new VRCameraMetrics();
  36940. result.hResolution = 1280;
  36941. result.vResolution = 800;
  36942. result.hScreenSize = 0.149759993;
  36943. result.vScreenSize = 0.0935999975;
  36944. result.vScreenCenter = 0.0467999987,
  36945. result.eyeToScreenDistance = 0.0410000011;
  36946. result.lensSeparationDistance = 0.0635000020;
  36947. result.interpupillaryDistance = 0.0640000030;
  36948. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  36949. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  36950. result.postProcessScaleFactor = 1.714605507808412;
  36951. result.lensCenterOffset = 0.151976421;
  36952. return result;
  36953. };
  36954. return VRCameraMetrics;
  36955. })();
  36956. BABYLON.VRCameraMetrics = VRCameraMetrics;
  36957. })(BABYLON || (BABYLON = {}));
  36958. var BABYLON;
  36959. (function (BABYLON) {
  36960. var VRDeviceOrientationFreeCamera = (function (_super) {
  36961. __extends(VRDeviceOrientationFreeCamera, _super);
  36962. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  36963. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36964. _super.call(this, name, position, scene);
  36965. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36966. metrics.compensateDistortion = compensateDistortion;
  36967. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36968. this.inputs.addVRDeviceOrientation();
  36969. }
  36970. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  36971. return "VRDeviceOrientationFreeCamera";
  36972. };
  36973. return VRDeviceOrientationFreeCamera;
  36974. })(BABYLON.FreeCamera);
  36975. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  36976. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  36977. __extends(VRDeviceOrientationArcRotateCamera, _super);
  36978. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  36979. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36980. _super.call(this, name, alpha, beta, radius, target, scene);
  36981. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  36982. metrics.compensateDistortion = compensateDistortion;
  36983. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  36984. this.inputs.addVRDeviceOrientation();
  36985. }
  36986. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  36987. return "VRDeviceOrientationArcRotateCamera";
  36988. };
  36989. return VRDeviceOrientationArcRotateCamera;
  36990. })(BABYLON.ArcRotateCamera);
  36991. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  36992. })(BABYLON || (BABYLON = {}));
  36993. var BABYLON;
  36994. (function (BABYLON) {
  36995. var WebVRFreeCamera = (function (_super) {
  36996. __extends(WebVRFreeCamera, _super);
  36997. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  36998. if (compensateDistortion === void 0) { compensateDistortion = true; }
  36999. _super.call(this, name, position, scene);
  37000. this._hmdDevice = null;
  37001. this._sensorDevice = null;
  37002. this._cacheState = null;
  37003. this._cacheQuaternion = new BABYLON.Quaternion();
  37004. this._cacheRotation = BABYLON.Vector3.Zero();
  37005. this._vrEnabled = false;
  37006. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37007. metrics.compensateDistortion = compensateDistortion;
  37008. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37009. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37010. }
  37011. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37012. var size = devices.length;
  37013. var i = 0;
  37014. // Reset devices.
  37015. this._sensorDevice = null;
  37016. this._hmdDevice = null;
  37017. // Search for a HmdDevice.
  37018. while (i < size && this._hmdDevice === null) {
  37019. if (devices[i] instanceof HMDVRDevice) {
  37020. this._hmdDevice = devices[i];
  37021. }
  37022. i++;
  37023. }
  37024. i = 0;
  37025. while (i < size && this._sensorDevice === null) {
  37026. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37027. this._sensorDevice = devices[i];
  37028. }
  37029. i++;
  37030. }
  37031. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37032. };
  37033. WebVRFreeCamera.prototype._checkInputs = function () {
  37034. if (this._vrEnabled) {
  37035. this._cacheState = this._sensorDevice.getState();
  37036. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37037. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37038. this.rotation.x = -this._cacheRotation.x;
  37039. this.rotation.y = -this._cacheRotation.y;
  37040. this.rotation.z = this._cacheRotation.z;
  37041. }
  37042. _super.prototype._checkInputs.call(this);
  37043. };
  37044. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37045. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37046. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37047. if (navigator.getVRDevices) {
  37048. navigator.getVRDevices().then(this._getWebVRDevices);
  37049. }
  37050. else if (navigator.mozGetVRDevices) {
  37051. navigator.mozGetVRDevices(this._getWebVRDevices);
  37052. }
  37053. };
  37054. WebVRFreeCamera.prototype.detachControl = function (element) {
  37055. _super.prototype.detachControl.call(this, element);
  37056. this._vrEnabled = false;
  37057. };
  37058. WebVRFreeCamera.prototype.getTypeName = function () {
  37059. return "WebVRFreeCamera";
  37060. };
  37061. return WebVRFreeCamera;
  37062. })(BABYLON.FreeCamera);
  37063. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37064. })(BABYLON || (BABYLON = {}));
  37065. var BABYLON;
  37066. (function (BABYLON) {
  37067. // Standard optimizations
  37068. var SceneOptimization = (function () {
  37069. function SceneOptimization(priority) {
  37070. if (priority === void 0) { priority = 0; }
  37071. this.priority = priority;
  37072. this.apply = function (scene) {
  37073. return true; // Return true if everything that can be done was applied
  37074. };
  37075. }
  37076. return SceneOptimization;
  37077. })();
  37078. BABYLON.SceneOptimization = SceneOptimization;
  37079. var TextureOptimization = (function (_super) {
  37080. __extends(TextureOptimization, _super);
  37081. function TextureOptimization(priority, maximumSize) {
  37082. var _this = this;
  37083. if (priority === void 0) { priority = 0; }
  37084. if (maximumSize === void 0) { maximumSize = 1024; }
  37085. _super.call(this, priority);
  37086. this.priority = priority;
  37087. this.maximumSize = maximumSize;
  37088. this.apply = function (scene) {
  37089. var allDone = true;
  37090. for (var index = 0; index < scene.textures.length; index++) {
  37091. var texture = scene.textures[index];
  37092. if (!texture.canRescale) {
  37093. continue;
  37094. }
  37095. var currentSize = texture.getSize();
  37096. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37097. if (maxDimension > _this.maximumSize) {
  37098. texture.scale(0.5);
  37099. allDone = false;
  37100. }
  37101. }
  37102. return allDone;
  37103. };
  37104. }
  37105. return TextureOptimization;
  37106. })(SceneOptimization);
  37107. BABYLON.TextureOptimization = TextureOptimization;
  37108. var HardwareScalingOptimization = (function (_super) {
  37109. __extends(HardwareScalingOptimization, _super);
  37110. function HardwareScalingOptimization(priority, maximumScale) {
  37111. var _this = this;
  37112. if (priority === void 0) { priority = 0; }
  37113. if (maximumScale === void 0) { maximumScale = 2; }
  37114. _super.call(this, priority);
  37115. this.priority = priority;
  37116. this.maximumScale = maximumScale;
  37117. this._currentScale = 1;
  37118. this.apply = function (scene) {
  37119. _this._currentScale++;
  37120. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37121. return _this._currentScale >= _this.maximumScale;
  37122. };
  37123. }
  37124. return HardwareScalingOptimization;
  37125. })(SceneOptimization);
  37126. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37127. var ShadowsOptimization = (function (_super) {
  37128. __extends(ShadowsOptimization, _super);
  37129. function ShadowsOptimization() {
  37130. _super.apply(this, arguments);
  37131. this.apply = function (scene) {
  37132. scene.shadowsEnabled = false;
  37133. return true;
  37134. };
  37135. }
  37136. return ShadowsOptimization;
  37137. })(SceneOptimization);
  37138. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37139. var PostProcessesOptimization = (function (_super) {
  37140. __extends(PostProcessesOptimization, _super);
  37141. function PostProcessesOptimization() {
  37142. _super.apply(this, arguments);
  37143. this.apply = function (scene) {
  37144. scene.postProcessesEnabled = false;
  37145. return true;
  37146. };
  37147. }
  37148. return PostProcessesOptimization;
  37149. })(SceneOptimization);
  37150. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37151. var LensFlaresOptimization = (function (_super) {
  37152. __extends(LensFlaresOptimization, _super);
  37153. function LensFlaresOptimization() {
  37154. _super.apply(this, arguments);
  37155. this.apply = function (scene) {
  37156. scene.lensFlaresEnabled = false;
  37157. return true;
  37158. };
  37159. }
  37160. return LensFlaresOptimization;
  37161. })(SceneOptimization);
  37162. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37163. var ParticlesOptimization = (function (_super) {
  37164. __extends(ParticlesOptimization, _super);
  37165. function ParticlesOptimization() {
  37166. _super.apply(this, arguments);
  37167. this.apply = function (scene) {
  37168. scene.particlesEnabled = false;
  37169. return true;
  37170. };
  37171. }
  37172. return ParticlesOptimization;
  37173. })(SceneOptimization);
  37174. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37175. var RenderTargetsOptimization = (function (_super) {
  37176. __extends(RenderTargetsOptimization, _super);
  37177. function RenderTargetsOptimization() {
  37178. _super.apply(this, arguments);
  37179. this.apply = function (scene) {
  37180. scene.renderTargetsEnabled = false;
  37181. return true;
  37182. };
  37183. }
  37184. return RenderTargetsOptimization;
  37185. })(SceneOptimization);
  37186. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37187. var MergeMeshesOptimization = (function (_super) {
  37188. __extends(MergeMeshesOptimization, _super);
  37189. function MergeMeshesOptimization() {
  37190. var _this = this;
  37191. _super.apply(this, arguments);
  37192. this._canBeMerged = function (abstractMesh) {
  37193. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37194. return false;
  37195. }
  37196. var mesh = abstractMesh;
  37197. if (!mesh.isVisible || !mesh.isEnabled()) {
  37198. return false;
  37199. }
  37200. if (mesh.instances.length > 0) {
  37201. return false;
  37202. }
  37203. if (mesh.skeleton || mesh.hasLODLevels) {
  37204. return false;
  37205. }
  37206. if (mesh.parent) {
  37207. return false;
  37208. }
  37209. return true;
  37210. };
  37211. this.apply = function (scene, updateSelectionTree) {
  37212. var globalPool = scene.meshes.slice(0);
  37213. var globalLength = globalPool.length;
  37214. for (var index = 0; index < globalLength; index++) {
  37215. var currentPool = new Array();
  37216. var current = globalPool[index];
  37217. // Checks
  37218. if (!_this._canBeMerged(current)) {
  37219. continue;
  37220. }
  37221. currentPool.push(current);
  37222. // Find compatible meshes
  37223. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37224. var otherMesh = globalPool[subIndex];
  37225. if (!_this._canBeMerged(otherMesh)) {
  37226. continue;
  37227. }
  37228. if (otherMesh.material !== current.material) {
  37229. continue;
  37230. }
  37231. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37232. continue;
  37233. }
  37234. currentPool.push(otherMesh);
  37235. globalLength--;
  37236. globalPool.splice(subIndex, 1);
  37237. subIndex--;
  37238. }
  37239. if (currentPool.length < 2) {
  37240. continue;
  37241. }
  37242. // Merge meshes
  37243. BABYLON.Mesh.MergeMeshes(currentPool);
  37244. }
  37245. if (updateSelectionTree != undefined) {
  37246. if (updateSelectionTree) {
  37247. scene.createOrUpdateSelectionOctree();
  37248. }
  37249. }
  37250. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37251. scene.createOrUpdateSelectionOctree();
  37252. }
  37253. return true;
  37254. };
  37255. }
  37256. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37257. get: function () {
  37258. return MergeMeshesOptimization._UpdateSelectionTree;
  37259. },
  37260. set: function (value) {
  37261. MergeMeshesOptimization._UpdateSelectionTree = value;
  37262. },
  37263. enumerable: true,
  37264. configurable: true
  37265. });
  37266. MergeMeshesOptimization._UpdateSelectionTree = false;
  37267. return MergeMeshesOptimization;
  37268. })(SceneOptimization);
  37269. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37270. // Options
  37271. var SceneOptimizerOptions = (function () {
  37272. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37273. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37274. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37275. this.targetFrameRate = targetFrameRate;
  37276. this.trackerDuration = trackerDuration;
  37277. this.optimizations = new Array();
  37278. }
  37279. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37280. var result = new SceneOptimizerOptions(targetFrameRate);
  37281. var priority = 0;
  37282. result.optimizations.push(new MergeMeshesOptimization(priority));
  37283. result.optimizations.push(new ShadowsOptimization(priority));
  37284. result.optimizations.push(new LensFlaresOptimization(priority));
  37285. // Next priority
  37286. priority++;
  37287. result.optimizations.push(new PostProcessesOptimization(priority));
  37288. result.optimizations.push(new ParticlesOptimization(priority));
  37289. // Next priority
  37290. priority++;
  37291. result.optimizations.push(new TextureOptimization(priority, 1024));
  37292. return result;
  37293. };
  37294. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37295. var result = new SceneOptimizerOptions(targetFrameRate);
  37296. var priority = 0;
  37297. result.optimizations.push(new MergeMeshesOptimization(priority));
  37298. result.optimizations.push(new ShadowsOptimization(priority));
  37299. result.optimizations.push(new LensFlaresOptimization(priority));
  37300. // Next priority
  37301. priority++;
  37302. result.optimizations.push(new PostProcessesOptimization(priority));
  37303. result.optimizations.push(new ParticlesOptimization(priority));
  37304. // Next priority
  37305. priority++;
  37306. result.optimizations.push(new TextureOptimization(priority, 512));
  37307. // Next priority
  37308. priority++;
  37309. result.optimizations.push(new RenderTargetsOptimization(priority));
  37310. // Next priority
  37311. priority++;
  37312. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37313. return result;
  37314. };
  37315. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37316. var result = new SceneOptimizerOptions(targetFrameRate);
  37317. var priority = 0;
  37318. result.optimizations.push(new MergeMeshesOptimization(priority));
  37319. result.optimizations.push(new ShadowsOptimization(priority));
  37320. result.optimizations.push(new LensFlaresOptimization(priority));
  37321. // Next priority
  37322. priority++;
  37323. result.optimizations.push(new PostProcessesOptimization(priority));
  37324. result.optimizations.push(new ParticlesOptimization(priority));
  37325. // Next priority
  37326. priority++;
  37327. result.optimizations.push(new TextureOptimization(priority, 256));
  37328. // Next priority
  37329. priority++;
  37330. result.optimizations.push(new RenderTargetsOptimization(priority));
  37331. // Next priority
  37332. priority++;
  37333. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37334. return result;
  37335. };
  37336. return SceneOptimizerOptions;
  37337. })();
  37338. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37339. // Scene optimizer tool
  37340. var SceneOptimizer = (function () {
  37341. function SceneOptimizer() {
  37342. }
  37343. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37344. // TODO: add an epsilon
  37345. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37346. if (onSuccess) {
  37347. onSuccess();
  37348. }
  37349. return;
  37350. }
  37351. // Apply current level of optimizations
  37352. var allDone = true;
  37353. var noOptimizationApplied = true;
  37354. for (var index = 0; index < options.optimizations.length; index++) {
  37355. var optimization = options.optimizations[index];
  37356. if (optimization.priority === currentPriorityLevel) {
  37357. noOptimizationApplied = false;
  37358. allDone = allDone && optimization.apply(scene);
  37359. }
  37360. }
  37361. // If no optimization was applied, this is a failure :(
  37362. if (noOptimizationApplied) {
  37363. if (onFailure) {
  37364. onFailure();
  37365. }
  37366. return;
  37367. }
  37368. // If all optimizations were done, move to next level
  37369. if (allDone) {
  37370. currentPriorityLevel++;
  37371. }
  37372. // Let's the system running for a specific amount of time before checking FPS
  37373. scene.executeWhenReady(function () {
  37374. setTimeout(function () {
  37375. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37376. }, options.trackerDuration);
  37377. });
  37378. };
  37379. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37380. if (!options) {
  37381. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37382. }
  37383. // Let's the system running for a specific amount of time before checking FPS
  37384. scene.executeWhenReady(function () {
  37385. setTimeout(function () {
  37386. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37387. }, options.trackerDuration);
  37388. });
  37389. };
  37390. return SceneOptimizer;
  37391. })();
  37392. BABYLON.SceneOptimizer = SceneOptimizer;
  37393. })(BABYLON || (BABYLON = {}));
  37394. var BABYLON;
  37395. (function (BABYLON) {
  37396. var Internals;
  37397. (function (Internals) {
  37398. var MeshLODLevel = (function () {
  37399. function MeshLODLevel(distance, mesh) {
  37400. this.distance = distance;
  37401. this.mesh = mesh;
  37402. }
  37403. return MeshLODLevel;
  37404. })();
  37405. Internals.MeshLODLevel = MeshLODLevel;
  37406. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37407. })(BABYLON || (BABYLON = {}));
  37408. var BABYLON;
  37409. (function (BABYLON) {
  37410. var RawTexture = (function (_super) {
  37411. __extends(RawTexture, _super);
  37412. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37413. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37414. if (invertY === void 0) { invertY = false; }
  37415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37416. _super.call(this, null, scene, !generateMipMaps, invertY);
  37417. this.format = format;
  37418. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  37419. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37420. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37421. }
  37422. RawTexture.prototype.update = function (data) {
  37423. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  37424. };
  37425. // Statics
  37426. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37427. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37428. if (invertY === void 0) { invertY = false; }
  37429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37430. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  37431. };
  37432. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37433. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37434. if (invertY === void 0) { invertY = false; }
  37435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37436. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37437. };
  37438. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37440. if (invertY === void 0) { invertY = false; }
  37441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37442. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37443. };
  37444. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37446. if (invertY === void 0) { invertY = false; }
  37447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37448. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  37449. };
  37450. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37452. if (invertY === void 0) { invertY = false; }
  37453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37454. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  37455. };
  37456. return RawTexture;
  37457. })(BABYLON.Texture);
  37458. BABYLON.RawTexture = RawTexture;
  37459. })(BABYLON || (BABYLON = {}));
  37460. var BABYLON;
  37461. (function (BABYLON) {
  37462. var IndexedVector2 = (function (_super) {
  37463. __extends(IndexedVector2, _super);
  37464. function IndexedVector2(original, index) {
  37465. _super.call(this, original.x, original.y);
  37466. this.index = index;
  37467. }
  37468. return IndexedVector2;
  37469. })(BABYLON.Vector2);
  37470. var PolygonPoints = (function () {
  37471. function PolygonPoints() {
  37472. this.elements = new Array();
  37473. }
  37474. PolygonPoints.prototype.add = function (originalPoints) {
  37475. var _this = this;
  37476. var result = new Array();
  37477. originalPoints.forEach(function (point) {
  37478. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  37479. var newPoint = new IndexedVector2(point, _this.elements.length);
  37480. result.push(newPoint);
  37481. _this.elements.push(newPoint);
  37482. }
  37483. });
  37484. return result;
  37485. };
  37486. PolygonPoints.prototype.computeBounds = function () {
  37487. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37488. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37489. this.elements.forEach(function (point) {
  37490. // x
  37491. if (point.x < lmin.x) {
  37492. lmin.x = point.x;
  37493. }
  37494. else if (point.x > lmax.x) {
  37495. lmax.x = point.x;
  37496. }
  37497. // y
  37498. if (point.y < lmin.y) {
  37499. lmin.y = point.y;
  37500. }
  37501. else if (point.y > lmax.y) {
  37502. lmax.y = point.y;
  37503. }
  37504. });
  37505. return {
  37506. min: lmin,
  37507. max: lmax,
  37508. width: lmax.x - lmin.x,
  37509. height: lmax.y - lmin.y
  37510. };
  37511. };
  37512. return PolygonPoints;
  37513. })();
  37514. var Polygon = (function () {
  37515. function Polygon() {
  37516. }
  37517. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  37518. return [
  37519. new BABYLON.Vector2(xmin, ymin),
  37520. new BABYLON.Vector2(xmax, ymin),
  37521. new BABYLON.Vector2(xmax, ymax),
  37522. new BABYLON.Vector2(xmin, ymax)
  37523. ];
  37524. };
  37525. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  37526. if (cx === void 0) { cx = 0; }
  37527. if (cy === void 0) { cy = 0; }
  37528. if (numberOfSides === void 0) { numberOfSides = 32; }
  37529. var result = new Array();
  37530. var angle = 0;
  37531. var increment = (Math.PI * 2) / numberOfSides;
  37532. for (var i = 0; i < numberOfSides; i++) {
  37533. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  37534. angle -= increment;
  37535. }
  37536. return result;
  37537. };
  37538. Polygon.Parse = function (input) {
  37539. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  37540. var i, result = [];
  37541. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  37542. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  37543. }
  37544. return result;
  37545. };
  37546. Polygon.StartingAt = function (x, y) {
  37547. return BABYLON.Path2.StartingAt(x, y);
  37548. };
  37549. return Polygon;
  37550. })();
  37551. BABYLON.Polygon = Polygon;
  37552. var PolygonMeshBuilder = (function () {
  37553. function PolygonMeshBuilder(name, contours, scene) {
  37554. this._points = new PolygonPoints();
  37555. this._outlinepoints = new PolygonPoints();
  37556. this._holes = [];
  37557. if (!("poly2tri" in window)) {
  37558. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  37559. }
  37560. this._name = name;
  37561. this._scene = scene;
  37562. var points;
  37563. if (contours instanceof BABYLON.Path2) {
  37564. points = contours.getPoints();
  37565. }
  37566. else {
  37567. points = contours;
  37568. }
  37569. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  37570. this._outlinepoints.add(points);
  37571. }
  37572. PolygonMeshBuilder.prototype.addHole = function (hole) {
  37573. this._swctx.addHole(this._points.add(hole));
  37574. var holepoints = new PolygonPoints();
  37575. holepoints.add(hole);
  37576. this._holes.push(holepoints);
  37577. return this;
  37578. };
  37579. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  37580. var _this = this;
  37581. if (updatable === void 0) { updatable = false; }
  37582. var result = new BABYLON.Mesh(this._name, this._scene);
  37583. var normals = [];
  37584. var positions = [];
  37585. var uvs = [];
  37586. var bounds = this._points.computeBounds();
  37587. this._points.elements.forEach(function (p) {
  37588. normals.push(0, 1.0, 0);
  37589. positions.push(p.x, 0, p.y);
  37590. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  37591. });
  37592. var indices = [];
  37593. this._swctx.triangulate();
  37594. this._swctx.getTriangles().forEach(function (triangle) {
  37595. triangle.getPoints().forEach(function (point) {
  37596. indices.push(point.index);
  37597. });
  37598. });
  37599. if (depth > 0) {
  37600. var positionscount = (positions.length / 3); //get the current pointcount
  37601. this._points.elements.forEach(function (p) {
  37602. normals.push(0, -1.0, 0);
  37603. positions.push(p.x, -depth, p.y);
  37604. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  37605. });
  37606. var p1; //we need to change order of point so the triangles are made in the rigth way.
  37607. var p2;
  37608. var poscounter = 0;
  37609. this._swctx.getTriangles().forEach(function (triangle) {
  37610. triangle.getPoints().forEach(function (point) {
  37611. switch (poscounter) {
  37612. case 0:
  37613. p1 = point;
  37614. break;
  37615. case 1:
  37616. p2 = point;
  37617. break;
  37618. case 2:
  37619. indices.push(point.index + positionscount);
  37620. indices.push(p2.index + positionscount);
  37621. indices.push(p1.index + positionscount);
  37622. poscounter = -1;
  37623. break;
  37624. }
  37625. poscounter++;
  37626. //indices.push((<IndexedVector2>point).index + positionscount);
  37627. });
  37628. });
  37629. //Add the sides
  37630. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  37631. this._holes.forEach(function (hole) {
  37632. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  37633. });
  37634. }
  37635. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  37636. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  37637. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  37638. result.setIndices(indices);
  37639. return result;
  37640. };
  37641. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  37642. var StartIndex = positions.length / 3;
  37643. var ulength = 0;
  37644. for (var i = 0; i < points.elements.length; i++) {
  37645. var p = points.elements[i];
  37646. var p1;
  37647. if ((i + 1) > points.elements.length - 1) {
  37648. p1 = points.elements[0];
  37649. }
  37650. else {
  37651. p1 = points.elements[i + 1];
  37652. }
  37653. positions.push(p.x, 0, p.y);
  37654. positions.push(p.x, -depth, p.y);
  37655. positions.push(p1.x, 0, p1.y);
  37656. positions.push(p1.x, -depth, p1.y);
  37657. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  37658. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  37659. var v3 = v2.subtract(v1);
  37660. var v4 = new BABYLON.Vector3(0, 1, 0);
  37661. var vn = BABYLON.Vector3.Cross(v3, v4);
  37662. vn = vn.normalize();
  37663. uvs.push(ulength / bounds.width, 0);
  37664. uvs.push(ulength / bounds.width, 1);
  37665. ulength += v3.length();
  37666. uvs.push((ulength / bounds.width), 0);
  37667. uvs.push((ulength / bounds.width), 1);
  37668. if (!flip) {
  37669. normals.push(-vn.x, -vn.y, -vn.z);
  37670. normals.push(-vn.x, -vn.y, -vn.z);
  37671. normals.push(-vn.x, -vn.y, -vn.z);
  37672. normals.push(-vn.x, -vn.y, -vn.z);
  37673. indices.push(StartIndex);
  37674. indices.push(StartIndex + 1);
  37675. indices.push(StartIndex + 2);
  37676. indices.push(StartIndex + 1);
  37677. indices.push(StartIndex + 3);
  37678. indices.push(StartIndex + 2);
  37679. }
  37680. else {
  37681. normals.push(vn.x, vn.y, vn.z);
  37682. normals.push(vn.x, vn.y, vn.z);
  37683. normals.push(vn.x, vn.y, vn.z);
  37684. normals.push(vn.x, vn.y, vn.z);
  37685. indices.push(StartIndex);
  37686. indices.push(StartIndex + 2);
  37687. indices.push(StartIndex + 1);
  37688. indices.push(StartIndex + 1);
  37689. indices.push(StartIndex + 2);
  37690. indices.push(StartIndex + 3);
  37691. }
  37692. StartIndex += 4;
  37693. }
  37694. ;
  37695. };
  37696. return PolygonMeshBuilder;
  37697. })();
  37698. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  37699. })(BABYLON || (BABYLON = {}));
  37700. var BABYLON;
  37701. (function (BABYLON) {
  37702. var Octree = (function () {
  37703. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  37704. if (maxDepth === void 0) { maxDepth = 2; }
  37705. this.maxDepth = maxDepth;
  37706. this.dynamicContent = new Array();
  37707. this._maxBlockCapacity = maxBlockCapacity || 64;
  37708. this._selectionContent = new BABYLON.SmartArray(1024);
  37709. this._creationFunc = creationFunc;
  37710. }
  37711. // Methods
  37712. Octree.prototype.update = function (worldMin, worldMax, entries) {
  37713. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  37714. };
  37715. Octree.prototype.addMesh = function (entry) {
  37716. for (var index = 0; index < this.blocks.length; index++) {
  37717. var block = this.blocks[index];
  37718. block.addEntry(entry);
  37719. }
  37720. };
  37721. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  37722. this._selectionContent.reset();
  37723. for (var index = 0; index < this.blocks.length; index++) {
  37724. var block = this.blocks[index];
  37725. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  37726. }
  37727. if (allowDuplicate) {
  37728. this._selectionContent.concat(this.dynamicContent);
  37729. }
  37730. else {
  37731. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  37732. }
  37733. return this._selectionContent;
  37734. };
  37735. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  37736. this._selectionContent.reset();
  37737. for (var index = 0; index < this.blocks.length; index++) {
  37738. var block = this.blocks[index];
  37739. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  37740. }
  37741. if (allowDuplicate) {
  37742. this._selectionContent.concat(this.dynamicContent);
  37743. }
  37744. else {
  37745. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  37746. }
  37747. return this._selectionContent;
  37748. };
  37749. Octree.prototype.intersectsRay = function (ray) {
  37750. this._selectionContent.reset();
  37751. for (var index = 0; index < this.blocks.length; index++) {
  37752. var block = this.blocks[index];
  37753. block.intersectsRay(ray, this._selectionContent);
  37754. }
  37755. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  37756. return this._selectionContent;
  37757. };
  37758. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  37759. target.blocks = new Array();
  37760. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  37761. // Segmenting space
  37762. for (var x = 0; x < 2; x++) {
  37763. for (var y = 0; y < 2; y++) {
  37764. for (var z = 0; z < 2; z++) {
  37765. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  37766. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  37767. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  37768. block.addEntries(entries);
  37769. target.blocks.push(block);
  37770. }
  37771. }
  37772. }
  37773. };
  37774. Octree.CreationFuncForMeshes = function (entry, block) {
  37775. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  37776. block.entries.push(entry);
  37777. }
  37778. };
  37779. Octree.CreationFuncForSubMeshes = function (entry, block) {
  37780. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  37781. block.entries.push(entry);
  37782. }
  37783. };
  37784. return Octree;
  37785. })();
  37786. BABYLON.Octree = Octree;
  37787. })(BABYLON || (BABYLON = {}));
  37788. var BABYLON;
  37789. (function (BABYLON) {
  37790. var OctreeBlock = (function () {
  37791. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  37792. this.entries = new Array();
  37793. this._boundingVectors = new Array();
  37794. this._capacity = capacity;
  37795. this._depth = depth;
  37796. this._maxDepth = maxDepth;
  37797. this._creationFunc = creationFunc;
  37798. this._minPoint = minPoint;
  37799. this._maxPoint = maxPoint;
  37800. this._boundingVectors.push(minPoint.clone());
  37801. this._boundingVectors.push(maxPoint.clone());
  37802. this._boundingVectors.push(minPoint.clone());
  37803. this._boundingVectors[2].x = maxPoint.x;
  37804. this._boundingVectors.push(minPoint.clone());
  37805. this._boundingVectors[3].y = maxPoint.y;
  37806. this._boundingVectors.push(minPoint.clone());
  37807. this._boundingVectors[4].z = maxPoint.z;
  37808. this._boundingVectors.push(maxPoint.clone());
  37809. this._boundingVectors[5].z = minPoint.z;
  37810. this._boundingVectors.push(maxPoint.clone());
  37811. this._boundingVectors[6].x = minPoint.x;
  37812. this._boundingVectors.push(maxPoint.clone());
  37813. this._boundingVectors[7].y = minPoint.y;
  37814. }
  37815. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  37816. // Property
  37817. get: function () {
  37818. return this._capacity;
  37819. },
  37820. enumerable: true,
  37821. configurable: true
  37822. });
  37823. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  37824. get: function () {
  37825. return this._minPoint;
  37826. },
  37827. enumerable: true,
  37828. configurable: true
  37829. });
  37830. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  37831. get: function () {
  37832. return this._maxPoint;
  37833. },
  37834. enumerable: true,
  37835. configurable: true
  37836. });
  37837. // Methods
  37838. OctreeBlock.prototype.addEntry = function (entry) {
  37839. if (this.blocks) {
  37840. for (var index = 0; index < this.blocks.length; index++) {
  37841. var block = this.blocks[index];
  37842. block.addEntry(entry);
  37843. }
  37844. return;
  37845. }
  37846. this._creationFunc(entry, this);
  37847. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  37848. this.createInnerBlocks();
  37849. }
  37850. };
  37851. OctreeBlock.prototype.addEntries = function (entries) {
  37852. for (var index = 0; index < entries.length; index++) {
  37853. var mesh = entries[index];
  37854. this.addEntry(mesh);
  37855. }
  37856. };
  37857. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  37858. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  37859. if (this.blocks) {
  37860. for (var index = 0; index < this.blocks.length; index++) {
  37861. var block = this.blocks[index];
  37862. block.select(frustumPlanes, selection, allowDuplicate);
  37863. }
  37864. return;
  37865. }
  37866. if (allowDuplicate) {
  37867. selection.concat(this.entries);
  37868. }
  37869. else {
  37870. selection.concatWithNoDuplicate(this.entries);
  37871. }
  37872. }
  37873. };
  37874. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  37875. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  37876. if (this.blocks) {
  37877. for (var index = 0; index < this.blocks.length; index++) {
  37878. var block = this.blocks[index];
  37879. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  37880. }
  37881. return;
  37882. }
  37883. if (allowDuplicate) {
  37884. selection.concat(this.entries);
  37885. }
  37886. else {
  37887. selection.concatWithNoDuplicate(this.entries);
  37888. }
  37889. }
  37890. };
  37891. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  37892. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  37893. if (this.blocks) {
  37894. for (var index = 0; index < this.blocks.length; index++) {
  37895. var block = this.blocks[index];
  37896. block.intersectsRay(ray, selection);
  37897. }
  37898. return;
  37899. }
  37900. selection.concatWithNoDuplicate(this.entries);
  37901. }
  37902. };
  37903. OctreeBlock.prototype.createInnerBlocks = function () {
  37904. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  37905. };
  37906. return OctreeBlock;
  37907. })();
  37908. BABYLON.OctreeBlock = OctreeBlock;
  37909. })(BABYLON || (BABYLON = {}));
  37910. var BABYLON;
  37911. (function (BABYLON) {
  37912. var BlurPostProcess = (function (_super) {
  37913. __extends(BlurPostProcess, _super);
  37914. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  37915. var _this = this;
  37916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37917. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  37918. this.direction = direction;
  37919. this.blurWidth = blurWidth;
  37920. this.onApply = function (effect) {
  37921. effect.setFloat2("screenSize", _this.width, _this.height);
  37922. effect.setVector2("direction", _this.direction);
  37923. effect.setFloat("blurWidth", _this.blurWidth);
  37924. };
  37925. }
  37926. return BlurPostProcess;
  37927. })(BABYLON.PostProcess);
  37928. BABYLON.BlurPostProcess = BlurPostProcess;
  37929. })(BABYLON || (BABYLON = {}));
  37930. var BABYLON;
  37931. (function (BABYLON) {
  37932. var RefractionPostProcess = (function (_super) {
  37933. __extends(RefractionPostProcess, _super);
  37934. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  37935. var _this = this;
  37936. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  37937. this.color = color;
  37938. this.depth = depth;
  37939. this.colorLevel = colorLevel;
  37940. this.onActivate = function (cam) {
  37941. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  37942. };
  37943. this.onApply = function (effect) {
  37944. effect.setColor3("baseColor", _this.color);
  37945. effect.setFloat("depth", _this.depth);
  37946. effect.setFloat("colorLevel", _this.colorLevel);
  37947. effect.setTexture("refractionSampler", _this._refRexture);
  37948. };
  37949. }
  37950. // Methods
  37951. RefractionPostProcess.prototype.dispose = function (camera) {
  37952. if (this._refRexture) {
  37953. this._refRexture.dispose();
  37954. }
  37955. _super.prototype.dispose.call(this, camera);
  37956. };
  37957. return RefractionPostProcess;
  37958. })(BABYLON.PostProcess);
  37959. BABYLON.RefractionPostProcess = RefractionPostProcess;
  37960. })(BABYLON || (BABYLON = {}));
  37961. var BABYLON;
  37962. (function (BABYLON) {
  37963. var BlackAndWhitePostProcess = (function (_super) {
  37964. __extends(BlackAndWhitePostProcess, _super);
  37965. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37966. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  37967. }
  37968. return BlackAndWhitePostProcess;
  37969. })(BABYLON.PostProcess);
  37970. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  37971. })(BABYLON || (BABYLON = {}));
  37972. var BABYLON;
  37973. (function (BABYLON) {
  37974. var ConvolutionPostProcess = (function (_super) {
  37975. __extends(ConvolutionPostProcess, _super);
  37976. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  37977. var _this = this;
  37978. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  37979. this.kernel = kernel;
  37980. this.onApply = function (effect) {
  37981. effect.setFloat2("screenSize", _this.width, _this.height);
  37982. effect.setArray("kernel", _this.kernel);
  37983. };
  37984. }
  37985. // Statics
  37986. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  37987. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  37988. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  37989. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  37990. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  37991. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  37992. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  37993. return ConvolutionPostProcess;
  37994. })(BABYLON.PostProcess);
  37995. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  37996. })(BABYLON || (BABYLON = {}));
  37997. var BABYLON;
  37998. (function (BABYLON) {
  37999. var FilterPostProcess = (function (_super) {
  38000. __extends(FilterPostProcess, _super);
  38001. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38002. var _this = this;
  38003. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38004. this.kernelMatrix = kernelMatrix;
  38005. this.onApply = function (effect) {
  38006. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38007. };
  38008. }
  38009. return FilterPostProcess;
  38010. })(BABYLON.PostProcess);
  38011. BABYLON.FilterPostProcess = FilterPostProcess;
  38012. })(BABYLON || (BABYLON = {}));
  38013. var BABYLON;
  38014. (function (BABYLON) {
  38015. var FxaaPostProcess = (function (_super) {
  38016. __extends(FxaaPostProcess, _super);
  38017. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38018. var _this = this;
  38019. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38020. this.onSizeChanged = function () {
  38021. _this.texelWidth = 1.0 / _this.width;
  38022. _this.texelHeight = 1.0 / _this.height;
  38023. };
  38024. this.onApply = function (effect) {
  38025. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38026. };
  38027. }
  38028. return FxaaPostProcess;
  38029. })(BABYLON.PostProcess);
  38030. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38031. })(BABYLON || (BABYLON = {}));
  38032. var BABYLON;
  38033. (function (BABYLON) {
  38034. var StereoscopicInterlacePostProcess = (function (_super) {
  38035. __extends(StereoscopicInterlacePostProcess, _super);
  38036. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38037. var _this = this;
  38038. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38039. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38040. this.onSizeChanged = function () {
  38041. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38042. };
  38043. this.onApply = function (effect) {
  38044. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38045. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38046. };
  38047. }
  38048. return StereoscopicInterlacePostProcess;
  38049. })(BABYLON.PostProcess);
  38050. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38051. })(BABYLON || (BABYLON = {}));
  38052. var BABYLON;
  38053. (function (BABYLON) {
  38054. var LensFlare = (function () {
  38055. function LensFlare(size, position, color, imgUrl, system) {
  38056. this.size = size;
  38057. this.position = position;
  38058. this.dispose = function () {
  38059. if (this.texture) {
  38060. this.texture.dispose();
  38061. }
  38062. // Remove from scene
  38063. var index = this._system.lensFlares.indexOf(this);
  38064. this._system.lensFlares.splice(index, 1);
  38065. };
  38066. this.color = color || new BABYLON.Color3(1, 1, 1);
  38067. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38068. this._system = system;
  38069. system.lensFlares.push(this);
  38070. }
  38071. return LensFlare;
  38072. })();
  38073. BABYLON.LensFlare = LensFlare;
  38074. })(BABYLON || (BABYLON = {}));
  38075. var BABYLON;
  38076. (function (BABYLON) {
  38077. var LensFlareSystem = (function () {
  38078. function LensFlareSystem(name, emitter, scene) {
  38079. this.name = name;
  38080. this.lensFlares = new Array();
  38081. this.borderLimit = 300;
  38082. this.layerMask = 0x0FFFFFFF;
  38083. this._vertexDeclaration = [2];
  38084. this._vertexStrideSize = 2 * 4;
  38085. this._isEnabled = true;
  38086. this._scene = scene;
  38087. this._emitter = emitter;
  38088. scene.lensFlareSystems.push(this);
  38089. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38090. // VBO
  38091. var vertices = [];
  38092. vertices.push(1, 1);
  38093. vertices.push(-1, 1);
  38094. vertices.push(-1, -1);
  38095. vertices.push(1, -1);
  38096. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38097. // Indices
  38098. var indices = [];
  38099. indices.push(0);
  38100. indices.push(1);
  38101. indices.push(2);
  38102. indices.push(0);
  38103. indices.push(2);
  38104. indices.push(3);
  38105. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38106. // Effects
  38107. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38108. }
  38109. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38110. get: function () {
  38111. return this._isEnabled;
  38112. },
  38113. set: function (value) {
  38114. this._isEnabled = value;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. LensFlareSystem.prototype.getScene = function () {
  38120. return this._scene;
  38121. };
  38122. LensFlareSystem.prototype.getEmitter = function () {
  38123. return this._emitter;
  38124. };
  38125. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38126. this._emitter = newEmitter;
  38127. };
  38128. LensFlareSystem.prototype.getEmitterPosition = function () {
  38129. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38130. };
  38131. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38132. var position = this.getEmitterPosition();
  38133. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38134. this._positionX = position.x;
  38135. this._positionY = position.y;
  38136. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38137. if (position.z > 0) {
  38138. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38139. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38140. return true;
  38141. }
  38142. }
  38143. return false;
  38144. };
  38145. LensFlareSystem.prototype._isVisible = function () {
  38146. if (!this._isEnabled) {
  38147. return false;
  38148. }
  38149. var emitterPosition = this.getEmitterPosition();
  38150. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38151. var distance = direction.length();
  38152. direction.normalize();
  38153. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38154. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38155. return !pickInfo.hit || pickInfo.distance > distance;
  38156. };
  38157. LensFlareSystem.prototype.render = function () {
  38158. if (!this._effect.isReady())
  38159. return false;
  38160. var engine = this._scene.getEngine();
  38161. var viewport = this._scene.activeCamera.viewport;
  38162. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38163. // Position
  38164. if (!this.computeEffectivePosition(globalViewport)) {
  38165. return false;
  38166. }
  38167. // Visibility
  38168. if (!this._isVisible()) {
  38169. return false;
  38170. }
  38171. // Intensity
  38172. var awayX;
  38173. var awayY;
  38174. if (this._positionX < this.borderLimit + globalViewport.x) {
  38175. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38176. }
  38177. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38178. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38179. }
  38180. else {
  38181. awayX = 0;
  38182. }
  38183. if (this._positionY < this.borderLimit + globalViewport.y) {
  38184. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38185. }
  38186. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38187. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38188. }
  38189. else {
  38190. awayY = 0;
  38191. }
  38192. var away = (awayX > awayY) ? awayX : awayY;
  38193. if (away > this.borderLimit) {
  38194. away = this.borderLimit;
  38195. }
  38196. var intensity = 1.0 - (away / this.borderLimit);
  38197. if (intensity < 0) {
  38198. return false;
  38199. }
  38200. if (intensity > 1.0) {
  38201. intensity = 1.0;
  38202. }
  38203. // Position
  38204. var centerX = globalViewport.x + globalViewport.width / 2;
  38205. var centerY = globalViewport.y + globalViewport.height / 2;
  38206. var distX = centerX - this._positionX;
  38207. var distY = centerY - this._positionY;
  38208. // Effects
  38209. engine.enableEffect(this._effect);
  38210. engine.setState(false);
  38211. engine.setDepthBuffer(false);
  38212. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38213. // VBOs
  38214. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38215. // Flares
  38216. for (var index = 0; index < this.lensFlares.length; index++) {
  38217. var flare = this.lensFlares[index];
  38218. var x = centerX - (distX * flare.position);
  38219. var y = centerY - (distY * flare.position);
  38220. var cw = flare.size;
  38221. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38222. var cx = 2 * (x / globalViewport.width) - 1.0;
  38223. var cy = 1.0 - 2 * (y / globalViewport.height);
  38224. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38225. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38226. // Texture
  38227. this._effect.setTexture("textureSampler", flare.texture);
  38228. // Color
  38229. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38230. // Draw order
  38231. engine.draw(true, 0, 6);
  38232. }
  38233. engine.setDepthBuffer(true);
  38234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38235. return true;
  38236. };
  38237. LensFlareSystem.prototype.dispose = function () {
  38238. if (this._vertexBuffer) {
  38239. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38240. this._vertexBuffer = null;
  38241. }
  38242. if (this._indexBuffer) {
  38243. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38244. this._indexBuffer = null;
  38245. }
  38246. while (this.lensFlares.length) {
  38247. this.lensFlares[0].dispose();
  38248. }
  38249. // Remove from scene
  38250. var index = this._scene.lensFlareSystems.indexOf(this);
  38251. this._scene.lensFlareSystems.splice(index, 1);
  38252. };
  38253. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38254. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38255. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  38256. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38257. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38258. var parsedFlare = parsedLensFlareSystem.flares[index];
  38259. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38260. }
  38261. return lensFlareSystem;
  38262. };
  38263. LensFlareSystem.prototype.serialize = function () {
  38264. var serializationObject = {};
  38265. serializationObject.emitterId = this.getEmitter().id;
  38266. serializationObject.borderLimit = this.borderLimit;
  38267. serializationObject.flares = [];
  38268. for (var index = 0; index < this.lensFlares.length; index++) {
  38269. var flare = this.lensFlares[index];
  38270. serializationObject.flares.push({
  38271. size: flare.size,
  38272. position: flare.position,
  38273. color: flare.color.asArray(),
  38274. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38275. });
  38276. }
  38277. return serializationObject;
  38278. };
  38279. return LensFlareSystem;
  38280. })();
  38281. BABYLON.LensFlareSystem = LensFlareSystem;
  38282. })(BABYLON || (BABYLON = {}));
  38283. var BABYLON;
  38284. (function (BABYLON) {
  38285. // We're mainly based on the logic defined into the FreeCamera code
  38286. var DeviceOrientationCamera = (function (_super) {
  38287. __extends(DeviceOrientationCamera, _super);
  38288. //-- end properties for backward compatibility for inputs
  38289. function DeviceOrientationCamera(name, position, scene) {
  38290. _super.call(this, name, position, scene);
  38291. this.inputs.addDeviceOrientation();
  38292. }
  38293. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38294. //-- Begin properties for backward compatibility for inputs
  38295. get: function () {
  38296. var gamepad = this.inputs.attached["deviceOrientation"];
  38297. if (gamepad)
  38298. return gamepad.angularSensibility;
  38299. },
  38300. set: function (value) {
  38301. var gamepad = this.inputs.attached["deviceOrientation"];
  38302. if (gamepad)
  38303. gamepad.angularSensibility = value;
  38304. },
  38305. enumerable: true,
  38306. configurable: true
  38307. });
  38308. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38309. get: function () {
  38310. var gamepad = this.inputs.attached["deviceOrientation"];
  38311. if (gamepad)
  38312. return gamepad.moveSensibility;
  38313. },
  38314. set: function (value) {
  38315. var gamepad = this.inputs.attached["deviceOrientation"];
  38316. if (gamepad)
  38317. gamepad.moveSensibility = value;
  38318. },
  38319. enumerable: true,
  38320. configurable: true
  38321. });
  38322. DeviceOrientationCamera.prototype.getTypeName = function () {
  38323. return "DeviceOrientationCamera";
  38324. };
  38325. return DeviceOrientationCamera;
  38326. })(BABYLON.FreeCamera);
  38327. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38328. })(BABYLON || (BABYLON = {}));
  38329. var BABYLON;
  38330. (function (BABYLON) {
  38331. // We're mainly based on the logic defined into the FreeCamera code
  38332. var UniversalCamera = (function (_super) {
  38333. __extends(UniversalCamera, _super);
  38334. //-- end properties for backward compatibility for inputs
  38335. function UniversalCamera(name, position, scene) {
  38336. _super.call(this, name, position, scene);
  38337. this.inputs.addGamepad();
  38338. }
  38339. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38340. //-- Begin properties for backward compatibility for inputs
  38341. get: function () {
  38342. var gamepad = this.inputs.attached["gamepad"];
  38343. if (gamepad)
  38344. return gamepad.gamepadAngularSensibility;
  38345. },
  38346. set: function (value) {
  38347. var gamepad = this.inputs.attached["gamepad"];
  38348. if (gamepad)
  38349. gamepad.gamepadAngularSensibility = value;
  38350. },
  38351. enumerable: true,
  38352. configurable: true
  38353. });
  38354. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38355. get: function () {
  38356. var gamepad = this.inputs.attached["gamepad"];
  38357. if (gamepad)
  38358. return gamepad.gamepadMoveSensibility;
  38359. },
  38360. set: function (value) {
  38361. var gamepad = this.inputs.attached["gamepad"];
  38362. if (gamepad)
  38363. gamepad.gamepadMoveSensibility = value;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. UniversalCamera.prototype.getTypeName = function () {
  38369. return "UniversalCamera";
  38370. };
  38371. return UniversalCamera;
  38372. })(BABYLON.TouchCamera);
  38373. BABYLON.UniversalCamera = UniversalCamera;
  38374. })(BABYLON || (BABYLON = {}));
  38375. var BABYLON;
  38376. (function (BABYLON) {
  38377. var Gamepads = (function () {
  38378. function Gamepads(ongamedpadconnected) {
  38379. var _this = this;
  38380. this.babylonGamepads = [];
  38381. this.oneGamepadConnected = false;
  38382. this.isMonitoring = false;
  38383. this.gamepadEventSupported = 'GamepadEvent' in window;
  38384. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38385. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38386. this._callbackGamepadConnected = ongamedpadconnected;
  38387. if (this.gamepadSupportAvailable) {
  38388. // Checking if the gamepad connected event is supported (like in Firefox)
  38389. if (this.gamepadEventSupported) {
  38390. this._onGamepadConnectedEvent = function (evt) {
  38391. _this._onGamepadConnected(evt);
  38392. };
  38393. this._onGamepadDisonnectedEvent = function (evt) {
  38394. _this._onGamepadDisconnected(evt);
  38395. };
  38396. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38397. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38398. }
  38399. else {
  38400. this._startMonitoringGamepads();
  38401. }
  38402. }
  38403. }
  38404. Gamepads.prototype.dispose = function () {
  38405. if (Gamepads.gamepadDOMInfo) {
  38406. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38407. }
  38408. if (this._onGamepadConnectedEvent) {
  38409. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38410. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38411. this._onGamepadConnectedEvent = null;
  38412. this._onGamepadDisonnectedEvent = null;
  38413. }
  38414. };
  38415. Gamepads.prototype._onGamepadConnected = function (evt) {
  38416. var newGamepad = this._addNewGamepad(evt.gamepad);
  38417. if (this._callbackGamepadConnected)
  38418. this._callbackGamepadConnected(newGamepad);
  38419. this._startMonitoringGamepads();
  38420. };
  38421. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38422. if (!this.oneGamepadConnected) {
  38423. this.oneGamepadConnected = true;
  38424. if (Gamepads.gamepadDOMInfo) {
  38425. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38426. Gamepads.gamepadDOMInfo = null;
  38427. }
  38428. }
  38429. var newGamepad;
  38430. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38431. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38432. }
  38433. else {
  38434. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38435. }
  38436. this.babylonGamepads.push(newGamepad);
  38437. return newGamepad;
  38438. };
  38439. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38440. // Remove the gamepad from the list of gamepads to monitor.
  38441. for (var i in this.babylonGamepads) {
  38442. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38443. this.babylonGamepads.splice(+i, 1);
  38444. break;
  38445. }
  38446. }
  38447. // If no gamepads are left, stop the polling loop.
  38448. if (this.babylonGamepads.length == 0) {
  38449. this._stopMonitoringGamepads();
  38450. }
  38451. };
  38452. Gamepads.prototype._startMonitoringGamepads = function () {
  38453. if (!this.isMonitoring) {
  38454. this.isMonitoring = true;
  38455. this._checkGamepadsStatus();
  38456. }
  38457. };
  38458. Gamepads.prototype._stopMonitoringGamepads = function () {
  38459. this.isMonitoring = false;
  38460. };
  38461. Gamepads.prototype._checkGamepadsStatus = function () {
  38462. var _this = this;
  38463. // updating gamepad objects
  38464. this._updateGamepadObjects();
  38465. for (var i in this.babylonGamepads) {
  38466. this.babylonGamepads[i].update();
  38467. }
  38468. if (this.isMonitoring) {
  38469. if (window.requestAnimationFrame) {
  38470. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38471. }
  38472. else if (window.mozRequestAnimationFrame) {
  38473. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38474. }
  38475. else if (window.webkitRequestAnimationFrame) {
  38476. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38477. }
  38478. }
  38479. };
  38480. // This function is called only on Chrome, which does not yet support
  38481. // connection/disconnection events, but requires you to monitor
  38482. // an array for changes.
  38483. Gamepads.prototype._updateGamepadObjects = function () {
  38484. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38485. for (var i = 0; i < gamepads.length; i++) {
  38486. if (gamepads[i]) {
  38487. if (!(gamepads[i].index in this.babylonGamepads)) {
  38488. var newGamepad = this._addNewGamepad(gamepads[i]);
  38489. if (this._callbackGamepadConnected) {
  38490. this._callbackGamepadConnected(newGamepad);
  38491. }
  38492. }
  38493. else {
  38494. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38495. }
  38496. }
  38497. }
  38498. };
  38499. return Gamepads;
  38500. })();
  38501. BABYLON.Gamepads = Gamepads;
  38502. var StickValues = (function () {
  38503. function StickValues(x, y) {
  38504. this.x = x;
  38505. this.y = y;
  38506. }
  38507. return StickValues;
  38508. })();
  38509. BABYLON.StickValues = StickValues;
  38510. var Gamepad = (function () {
  38511. function Gamepad(id, index, browserGamepad) {
  38512. this.id = id;
  38513. this.index = index;
  38514. this.browserGamepad = browserGamepad;
  38515. if (this.browserGamepad.axes.length >= 2) {
  38516. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38517. }
  38518. if (this.browserGamepad.axes.length >= 4) {
  38519. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38520. }
  38521. }
  38522. Gamepad.prototype.onleftstickchanged = function (callback) {
  38523. this._onleftstickchanged = callback;
  38524. };
  38525. Gamepad.prototype.onrightstickchanged = function (callback) {
  38526. this._onrightstickchanged = callback;
  38527. };
  38528. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38529. get: function () {
  38530. return this._leftStick;
  38531. },
  38532. set: function (newValues) {
  38533. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38534. this._onleftstickchanged(newValues);
  38535. }
  38536. this._leftStick = newValues;
  38537. },
  38538. enumerable: true,
  38539. configurable: true
  38540. });
  38541. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38542. get: function () {
  38543. return this._rightStick;
  38544. },
  38545. set: function (newValues) {
  38546. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38547. this._onrightstickchanged(newValues);
  38548. }
  38549. this._rightStick = newValues;
  38550. },
  38551. enumerable: true,
  38552. configurable: true
  38553. });
  38554. Gamepad.prototype.update = function () {
  38555. if (this._leftStick) {
  38556. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38557. }
  38558. if (this._rightStick) {
  38559. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38560. }
  38561. };
  38562. return Gamepad;
  38563. })();
  38564. BABYLON.Gamepad = Gamepad;
  38565. var GenericPad = (function (_super) {
  38566. __extends(GenericPad, _super);
  38567. function GenericPad(id, index, gamepad) {
  38568. _super.call(this, id, index, gamepad);
  38569. this.id = id;
  38570. this.index = index;
  38571. this.gamepad = gamepad;
  38572. this._buttons = new Array(gamepad.buttons.length);
  38573. }
  38574. GenericPad.prototype.onbuttondown = function (callback) {
  38575. this._onbuttondown = callback;
  38576. };
  38577. GenericPad.prototype.onbuttonup = function (callback) {
  38578. this._onbuttonup = callback;
  38579. };
  38580. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38581. if (newValue !== currentValue) {
  38582. if (this._onbuttondown && newValue === 1) {
  38583. this._onbuttondown(buttonIndex);
  38584. }
  38585. if (this._onbuttonup && newValue === 0) {
  38586. this._onbuttonup(buttonIndex);
  38587. }
  38588. }
  38589. return newValue;
  38590. };
  38591. GenericPad.prototype.update = function () {
  38592. _super.prototype.update.call(this);
  38593. for (var index = 0; index < this._buttons.length; index++) {
  38594. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38595. }
  38596. };
  38597. return GenericPad;
  38598. })(Gamepad);
  38599. BABYLON.GenericPad = GenericPad;
  38600. (function (Xbox360Button) {
  38601. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38602. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38603. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38604. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38605. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38606. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38607. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38608. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38609. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38610. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38611. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38612. var Xbox360Button = BABYLON.Xbox360Button;
  38613. (function (Xbox360Dpad) {
  38614. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38615. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38616. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38617. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38618. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38619. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38620. var Xbox360Pad = (function (_super) {
  38621. __extends(Xbox360Pad, _super);
  38622. function Xbox360Pad() {
  38623. _super.apply(this, arguments);
  38624. this._leftTrigger = 0;
  38625. this._rightTrigger = 0;
  38626. this._buttonA = 0;
  38627. this._buttonB = 0;
  38628. this._buttonX = 0;
  38629. this._buttonY = 0;
  38630. this._buttonBack = 0;
  38631. this._buttonStart = 0;
  38632. this._buttonLB = 0;
  38633. this._buttonRB = 0;
  38634. this._buttonLeftStick = 0;
  38635. this._buttonRightStick = 0;
  38636. this._dPadUp = 0;
  38637. this._dPadDown = 0;
  38638. this._dPadLeft = 0;
  38639. this._dPadRight = 0;
  38640. }
  38641. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38642. this._onlefttriggerchanged = callback;
  38643. };
  38644. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38645. this._onrighttriggerchanged = callback;
  38646. };
  38647. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38648. get: function () {
  38649. return this._leftTrigger;
  38650. },
  38651. set: function (newValue) {
  38652. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38653. this._onlefttriggerchanged(newValue);
  38654. }
  38655. this._leftTrigger = newValue;
  38656. },
  38657. enumerable: true,
  38658. configurable: true
  38659. });
  38660. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38661. get: function () {
  38662. return this._rightTrigger;
  38663. },
  38664. set: function (newValue) {
  38665. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38666. this._onrighttriggerchanged(newValue);
  38667. }
  38668. this._rightTrigger = newValue;
  38669. },
  38670. enumerable: true,
  38671. configurable: true
  38672. });
  38673. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38674. this._onbuttondown = callback;
  38675. };
  38676. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38677. this._onbuttonup = callback;
  38678. };
  38679. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38680. this._ondpaddown = callback;
  38681. };
  38682. Xbox360Pad.prototype.ondpadup = function (callback) {
  38683. this._ondpadup = callback;
  38684. };
  38685. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38686. if (newValue !== currentValue) {
  38687. if (this._onbuttondown && newValue === 1) {
  38688. this._onbuttondown(buttonType);
  38689. }
  38690. if (this._onbuttonup && newValue === 0) {
  38691. this._onbuttonup(buttonType);
  38692. }
  38693. }
  38694. return newValue;
  38695. };
  38696. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38697. if (newValue !== currentValue) {
  38698. if (this._ondpaddown && newValue === 1) {
  38699. this._ondpaddown(buttonType);
  38700. }
  38701. if (this._ondpadup && newValue === 0) {
  38702. this._ondpadup(buttonType);
  38703. }
  38704. }
  38705. return newValue;
  38706. };
  38707. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38708. get: function () {
  38709. return this._buttonA;
  38710. },
  38711. set: function (value) {
  38712. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38713. },
  38714. enumerable: true,
  38715. configurable: true
  38716. });
  38717. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38718. get: function () {
  38719. return this._buttonB;
  38720. },
  38721. set: function (value) {
  38722. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38723. },
  38724. enumerable: true,
  38725. configurable: true
  38726. });
  38727. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38728. get: function () {
  38729. return this._buttonX;
  38730. },
  38731. set: function (value) {
  38732. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38733. },
  38734. enumerable: true,
  38735. configurable: true
  38736. });
  38737. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38738. get: function () {
  38739. return this._buttonY;
  38740. },
  38741. set: function (value) {
  38742. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38743. },
  38744. enumerable: true,
  38745. configurable: true
  38746. });
  38747. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38748. get: function () {
  38749. return this._buttonStart;
  38750. },
  38751. set: function (value) {
  38752. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38753. },
  38754. enumerable: true,
  38755. configurable: true
  38756. });
  38757. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38758. get: function () {
  38759. return this._buttonBack;
  38760. },
  38761. set: function (value) {
  38762. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38763. },
  38764. enumerable: true,
  38765. configurable: true
  38766. });
  38767. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38768. get: function () {
  38769. return this._buttonLB;
  38770. },
  38771. set: function (value) {
  38772. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38778. get: function () {
  38779. return this._buttonRB;
  38780. },
  38781. set: function (value) {
  38782. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38783. },
  38784. enumerable: true,
  38785. configurable: true
  38786. });
  38787. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38788. get: function () {
  38789. return this._buttonLeftStick;
  38790. },
  38791. set: function (value) {
  38792. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38793. },
  38794. enumerable: true,
  38795. configurable: true
  38796. });
  38797. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38798. get: function () {
  38799. return this._buttonRightStick;
  38800. },
  38801. set: function (value) {
  38802. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38803. },
  38804. enumerable: true,
  38805. configurable: true
  38806. });
  38807. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38808. get: function () {
  38809. return this._dPadUp;
  38810. },
  38811. set: function (value) {
  38812. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38813. },
  38814. enumerable: true,
  38815. configurable: true
  38816. });
  38817. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38818. get: function () {
  38819. return this._dPadDown;
  38820. },
  38821. set: function (value) {
  38822. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38823. },
  38824. enumerable: true,
  38825. configurable: true
  38826. });
  38827. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38828. get: function () {
  38829. return this._dPadLeft;
  38830. },
  38831. set: function (value) {
  38832. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38833. },
  38834. enumerable: true,
  38835. configurable: true
  38836. });
  38837. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38838. get: function () {
  38839. return this._dPadRight;
  38840. },
  38841. set: function (value) {
  38842. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38843. },
  38844. enumerable: true,
  38845. configurable: true
  38846. });
  38847. Xbox360Pad.prototype.update = function () {
  38848. _super.prototype.update.call(this);
  38849. this.buttonA = this.browserGamepad.buttons[0].value;
  38850. this.buttonB = this.browserGamepad.buttons[1].value;
  38851. this.buttonX = this.browserGamepad.buttons[2].value;
  38852. this.buttonY = this.browserGamepad.buttons[3].value;
  38853. this.buttonLB = this.browserGamepad.buttons[4].value;
  38854. this.buttonRB = this.browserGamepad.buttons[5].value;
  38855. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38856. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38857. this.buttonBack = this.browserGamepad.buttons[8].value;
  38858. this.buttonStart = this.browserGamepad.buttons[9].value;
  38859. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38860. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38861. this.dPadUp = this.browserGamepad.buttons[12].value;
  38862. this.dPadDown = this.browserGamepad.buttons[13].value;
  38863. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38864. this.dPadRight = this.browserGamepad.buttons[15].value;
  38865. };
  38866. return Xbox360Pad;
  38867. })(Gamepad);
  38868. BABYLON.Xbox360Pad = Xbox360Pad;
  38869. })(BABYLON || (BABYLON = {}));
  38870. var BABYLON;
  38871. (function (BABYLON) {
  38872. // We're mainly based on the logic defined into the FreeCamera code
  38873. var GamepadCamera = (function (_super) {
  38874. __extends(GamepadCamera, _super);
  38875. //-- end properties for backward compatibility for inputs
  38876. function GamepadCamera(name, position, scene) {
  38877. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38878. _super.call(this, name, position, scene);
  38879. }
  38880. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  38881. //-- Begin properties for backward compatibility for inputs
  38882. get: function () {
  38883. var gamepad = this.inputs.attached["gamepad"];
  38884. if (gamepad)
  38885. return gamepad.gamepadAngularSensibility;
  38886. },
  38887. set: function (value) {
  38888. var gamepad = this.inputs.attached["gamepad"];
  38889. if (gamepad)
  38890. gamepad.gamepadAngularSensibility = value;
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  38896. get: function () {
  38897. var gamepad = this.inputs.attached["gamepad"];
  38898. if (gamepad)
  38899. return gamepad.gamepadMoveSensibility;
  38900. },
  38901. set: function (value) {
  38902. var gamepad = this.inputs.attached["gamepad"];
  38903. if (gamepad)
  38904. gamepad.gamepadMoveSensibility = value;
  38905. },
  38906. enumerable: true,
  38907. configurable: true
  38908. });
  38909. GamepadCamera.prototype.getTypeName = function () {
  38910. return "GamepadCamera";
  38911. };
  38912. return GamepadCamera;
  38913. })(BABYLON.UniversalCamera);
  38914. BABYLON.GamepadCamera = GamepadCamera;
  38915. })(BABYLON || (BABYLON = {}));
  38916. var BABYLON;
  38917. (function (BABYLON) {
  38918. var Analyser = (function () {
  38919. function Analyser(scene) {
  38920. this.SMOOTHING = 0.75;
  38921. this.FFT_SIZE = 512;
  38922. this.BARGRAPHAMPLITUDE = 256;
  38923. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  38924. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  38925. this._scene = scene;
  38926. this._audioEngine = BABYLON.Engine.audioEngine;
  38927. if (this._audioEngine.canUseWebAudio) {
  38928. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  38929. this._webAudioAnalyser.minDecibels = -140;
  38930. this._webAudioAnalyser.maxDecibels = 0;
  38931. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  38932. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  38933. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  38934. }
  38935. }
  38936. Analyser.prototype.getFrequencyBinCount = function () {
  38937. if (this._audioEngine.canUseWebAudio) {
  38938. return this._webAudioAnalyser.frequencyBinCount;
  38939. }
  38940. else {
  38941. return 0;
  38942. }
  38943. };
  38944. Analyser.prototype.getByteFrequencyData = function () {
  38945. if (this._audioEngine.canUseWebAudio) {
  38946. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38947. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38948. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  38949. }
  38950. return this._byteFreqs;
  38951. };
  38952. Analyser.prototype.getByteTimeDomainData = function () {
  38953. if (this._audioEngine.canUseWebAudio) {
  38954. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38955. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38956. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  38957. }
  38958. return this._byteTime;
  38959. };
  38960. Analyser.prototype.getFloatFrequencyData = function () {
  38961. if (this._audioEngine.canUseWebAudio) {
  38962. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  38963. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  38964. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  38965. }
  38966. return this._floatFreqs;
  38967. };
  38968. Analyser.prototype.drawDebugCanvas = function () {
  38969. var _this = this;
  38970. if (this._audioEngine.canUseWebAudio) {
  38971. if (!this._debugCanvas) {
  38972. this._debugCanvas = document.createElement("canvas");
  38973. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  38974. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  38975. this._debugCanvas.style.position = "absolute";
  38976. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  38977. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  38978. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  38979. document.body.appendChild(this._debugCanvas);
  38980. this._registerFunc = function () {
  38981. _this.drawDebugCanvas();
  38982. };
  38983. this._scene.registerBeforeRender(this._registerFunc);
  38984. }
  38985. if (this._registerFunc) {
  38986. var workingArray = this.getByteFrequencyData();
  38987. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  38988. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  38989. // Draw the frequency domain chart.
  38990. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  38991. var value = workingArray[i];
  38992. var percent = value / this.BARGRAPHAMPLITUDE;
  38993. var height = this.DEBUGCANVASSIZE.height * percent;
  38994. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  38995. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  38996. var hue = i / this.getFrequencyBinCount() * 360;
  38997. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  38998. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  38999. }
  39000. }
  39001. }
  39002. };
  39003. Analyser.prototype.stopDebugCanvas = function () {
  39004. if (this._debugCanvas) {
  39005. this._scene.unregisterBeforeRender(this._registerFunc);
  39006. this._registerFunc = null;
  39007. document.body.removeChild(this._debugCanvas);
  39008. this._debugCanvas = null;
  39009. this._debugCanvasContext = null;
  39010. }
  39011. };
  39012. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39013. if (this._audioEngine.canUseWebAudio) {
  39014. inputAudioNode.connect(this._webAudioAnalyser);
  39015. this._webAudioAnalyser.connect(outputAudioNode);
  39016. }
  39017. };
  39018. Analyser.prototype.dispose = function () {
  39019. if (this._audioEngine.canUseWebAudio) {
  39020. this._webAudioAnalyser.disconnect();
  39021. }
  39022. };
  39023. return Analyser;
  39024. })();
  39025. BABYLON.Analyser = Analyser;
  39026. })(BABYLON || (BABYLON = {}));
  39027. var BABYLON;
  39028. (function (BABYLON) {
  39029. var DepthRenderer = (function () {
  39030. function DepthRenderer(scene, type) {
  39031. var _this = this;
  39032. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39033. this._viewMatrix = BABYLON.Matrix.Zero();
  39034. this._projectionMatrix = BABYLON.Matrix.Zero();
  39035. this._transformMatrix = BABYLON.Matrix.Zero();
  39036. this._worldViewProjection = BABYLON.Matrix.Zero();
  39037. this._scene = scene;
  39038. var engine = scene.getEngine();
  39039. // Render target
  39040. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39041. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39042. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39043. this._depthMap.refreshRate = 1;
  39044. this._depthMap.renderParticles = false;
  39045. this._depthMap.renderList = null;
  39046. // set default depth value to 1.0 (far away)
  39047. this._depthMap.onClear = function (engine) {
  39048. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39049. };
  39050. // Custom render function
  39051. var renderSubMesh = function (subMesh) {
  39052. var mesh = subMesh.getRenderingMesh();
  39053. var scene = _this._scene;
  39054. var engine = scene.getEngine();
  39055. // Culling
  39056. engine.setState(subMesh.getMaterial().backFaceCulling);
  39057. // Managing instances
  39058. var batch = mesh._getInstancesRenderList(subMesh._id);
  39059. if (batch.mustReturn) {
  39060. return;
  39061. }
  39062. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39063. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39064. engine.enableEffect(_this._effect);
  39065. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39066. var material = subMesh.getMaterial();
  39067. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39068. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39069. // Alpha test
  39070. if (material && material.needAlphaTesting()) {
  39071. var alphaTexture = material.getAlphaTestTexture();
  39072. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39073. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39074. }
  39075. // Bones
  39076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39077. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39078. }
  39079. // Draw
  39080. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39081. }
  39082. };
  39083. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39084. var index;
  39085. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39086. renderSubMesh(opaqueSubMeshes.data[index]);
  39087. }
  39088. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39089. renderSubMesh(alphaTestSubMeshes.data[index]);
  39090. }
  39091. };
  39092. }
  39093. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39094. var material = subMesh.getMaterial();
  39095. if (material.disableDepthWrite) {
  39096. return false;
  39097. }
  39098. var defines = [];
  39099. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39100. var mesh = subMesh.getMesh();
  39101. var scene = mesh.getScene();
  39102. // Alpha test
  39103. if (material && material.needAlphaTesting()) {
  39104. defines.push("#define ALPHATEST");
  39105. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39106. attribs.push(BABYLON.VertexBuffer.UVKind);
  39107. defines.push("#define UV1");
  39108. }
  39109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39110. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39111. defines.push("#define UV2");
  39112. }
  39113. }
  39114. // Bones
  39115. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39116. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39117. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39118. if (mesh.numBoneInfluencers > 4) {
  39119. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39120. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39121. }
  39122. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39123. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39124. }
  39125. else {
  39126. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39127. }
  39128. // Instances
  39129. if (useInstances) {
  39130. defines.push("#define INSTANCES");
  39131. attribs.push("world0");
  39132. attribs.push("world1");
  39133. attribs.push("world2");
  39134. attribs.push("world3");
  39135. }
  39136. // Get correct effect
  39137. var join = defines.join("\n");
  39138. if (this._cachedDefines !== join) {
  39139. this._cachedDefines = join;
  39140. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39141. }
  39142. return this._effect.isReady();
  39143. };
  39144. DepthRenderer.prototype.getDepthMap = function () {
  39145. return this._depthMap;
  39146. };
  39147. // Methods
  39148. DepthRenderer.prototype.dispose = function () {
  39149. this._depthMap.dispose();
  39150. };
  39151. return DepthRenderer;
  39152. })();
  39153. BABYLON.DepthRenderer = DepthRenderer;
  39154. })(BABYLON || (BABYLON = {}));
  39155. var BABYLON;
  39156. (function (BABYLON) {
  39157. var SSAORenderingPipeline = (function (_super) {
  39158. __extends(SSAORenderingPipeline, _super);
  39159. /**
  39160. * @constructor
  39161. * @param {string} name - The rendering pipeline name
  39162. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39163. * @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 }
  39164. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39165. */
  39166. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39167. var _this = this;
  39168. _super.call(this, scene.getEngine(), name);
  39169. // Members
  39170. /**
  39171. * The PassPostProcess id in the pipeline that contains the original scene color
  39172. * @type {string}
  39173. */
  39174. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39175. /**
  39176. * The SSAO PostProcess id in the pipeline
  39177. * @type {string}
  39178. */
  39179. this.SSAORenderEffect = "SSAORenderEffect";
  39180. /**
  39181. * The horizontal blur PostProcess id in the pipeline
  39182. * @type {string}
  39183. */
  39184. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39185. /**
  39186. * The vertical blur PostProcess id in the pipeline
  39187. * @type {string}
  39188. */
  39189. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39190. /**
  39191. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39192. * @type {string}
  39193. */
  39194. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39195. /**
  39196. * The output strength of the SSAO post-process. Default value is 1.0.
  39197. * @type {number}
  39198. */
  39199. this.totalStrength = 1.0;
  39200. /**
  39201. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39202. * @type {number}
  39203. */
  39204. this.radius = 0.0001;
  39205. /**
  39206. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39207. * Must not be equal to fallOff and superior to fallOff.
  39208. * Default value is 0.975
  39209. * @type {number}
  39210. */
  39211. this.area = 0.0075;
  39212. /**
  39213. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39214. * Must not be equal to area and inferior to area.
  39215. * Default value is 0.0
  39216. * @type {number}
  39217. */
  39218. this.fallOff = 0.000001;
  39219. /**
  39220. * The base color of the SSAO post-process
  39221. * The final result is "base + ssao" between [0, 1]
  39222. * @type {number}
  39223. */
  39224. this.base = 0.5;
  39225. this._firstUpdate = true;
  39226. this._scene = scene;
  39227. // Set up assets
  39228. this._createRandomTexture();
  39229. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39230. var ssaoRatio = ratio.ssaoRatio || ratio;
  39231. var combineRatio = ratio.combineRatio || ratio;
  39232. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39233. this._createSSAOPostProcess(ssaoRatio);
  39234. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39235. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39236. this._createSSAOCombinePostProcess(combineRatio);
  39237. // Set up pipeline
  39238. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39242. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39243. // Finish
  39244. scene.postProcessRenderPipelineManager.addPipeline(this);
  39245. if (cameras)
  39246. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39247. }
  39248. // Public Methods
  39249. /**
  39250. * Returns the horizontal blur PostProcess
  39251. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39252. */
  39253. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39254. return this._blurHPostProcess;
  39255. };
  39256. /**
  39257. * Returns the vertical blur PostProcess
  39258. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39259. */
  39260. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39261. return this._blurVPostProcess;
  39262. };
  39263. /**
  39264. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39265. */
  39266. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39267. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39268. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39269. this._originalColorPostProcess = undefined;
  39270. this._ssaoPostProcess = undefined;
  39271. this._blurHPostProcess = undefined;
  39272. this._blurVPostProcess = undefined;
  39273. this._ssaoCombinePostProcess = undefined;
  39274. this._randomTexture.dispose();
  39275. if (disableDepthRender)
  39276. this._scene.disableDepthRenderer();
  39277. };
  39278. // Private Methods
  39279. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39280. var _this = this;
  39281. var numSamples = 16;
  39282. var sampleSphere = [
  39283. 0.5381, 0.1856, -0.4319,
  39284. 0.1379, 0.2486, 0.4430,
  39285. 0.3371, 0.5679, -0.0057,
  39286. -0.6999, -0.0451, -0.0019,
  39287. 0.0689, -0.1598, -0.8547,
  39288. 0.0560, 0.0069, -0.1843,
  39289. -0.0146, 0.1402, 0.0762,
  39290. 0.0100, -0.1924, -0.0344,
  39291. -0.3577, -0.5301, -0.4358,
  39292. -0.3169, 0.1063, 0.0158,
  39293. 0.0103, -0.5869, 0.0046,
  39294. -0.0897, -0.4940, 0.3287,
  39295. 0.7119, -0.0154, -0.0918,
  39296. -0.0533, 0.0596, -0.5411,
  39297. 0.0352, -0.0631, 0.5460,
  39298. -0.4776, 0.2847, -0.0271
  39299. ];
  39300. var samplesFactor = 1.0 / numSamples;
  39301. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39302. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39303. "area", "fallOff", "base"
  39304. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39305. this._ssaoPostProcess.onApply = function (effect) {
  39306. if (_this._firstUpdate) {
  39307. effect.setArray3("sampleSphere", sampleSphere);
  39308. effect.setFloat("samplesFactor", samplesFactor);
  39309. effect.setFloat("randTextureTiles", 4.0);
  39310. _this._firstUpdate = false;
  39311. }
  39312. effect.setFloat("totalStrength", _this.totalStrength);
  39313. effect.setFloat("radius", _this.radius);
  39314. effect.setFloat("area", _this.area);
  39315. effect.setFloat("fallOff", _this.fallOff);
  39316. effect.setFloat("base", _this.base);
  39317. effect.setTexture("textureSampler", _this._depthTexture);
  39318. effect.setTexture("randomSampler", _this._randomTexture);
  39319. };
  39320. };
  39321. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39322. var _this = this;
  39323. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39324. this._ssaoCombinePostProcess.onApply = function (effect) {
  39325. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39326. };
  39327. };
  39328. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39329. var size = 512;
  39330. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39331. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39332. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39333. var context = this._randomTexture.getContext();
  39334. var rand = function (min, max) {
  39335. return Math.random() * (max - min) + min;
  39336. };
  39337. var randVector = BABYLON.Vector3.Zero();
  39338. for (var x = 0; x < size; x++) {
  39339. for (var y = 0; y < size; y++) {
  39340. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39341. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39342. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39343. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39344. context.fillRect(x, y, 1, 1);
  39345. }
  39346. }
  39347. this._randomTexture.update(false);
  39348. };
  39349. return SSAORenderingPipeline;
  39350. })(BABYLON.PostProcessRenderPipeline);
  39351. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39352. })(BABYLON || (BABYLON = {}));
  39353. var BABYLON;
  39354. (function (BABYLON) {
  39355. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39356. var VolumetricLightScatteringPostProcess = (function (_super) {
  39357. __extends(VolumetricLightScatteringPostProcess, _super);
  39358. /**
  39359. * @constructor
  39360. * @param {string} name - The post-process name
  39361. * @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)
  39362. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39363. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39364. * @param {number} samples - The post-process quality, default 100
  39365. * @param {number} samplingMode - The post-process filtering mode
  39366. * @param {BABYLON.Engine} engine - The babylon engine
  39367. * @param {boolean} reusable - If the post-process is reusable
  39368. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39369. */
  39370. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39371. var _this = this;
  39372. if (samples === void 0) { samples = 100; }
  39373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39374. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39375. this._screenCoordinates = BABYLON.Vector2.Zero();
  39376. /**
  39377. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39378. * @type {Vector3}
  39379. */
  39380. this.customMeshPosition = BABYLON.Vector3.Zero();
  39381. /**
  39382. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39383. * @type {boolean}
  39384. */
  39385. this.useCustomMeshPosition = false;
  39386. /**
  39387. * If the post-process should inverse the light scattering direction
  39388. * @type {boolean}
  39389. */
  39390. this.invert = true;
  39391. /**
  39392. * Array containing the excluded meshes not rendered in the internal pass
  39393. */
  39394. this.excludedMeshes = new Array();
  39395. /**
  39396. * Controls the overall intensity of the post-process
  39397. * @type {number}
  39398. */
  39399. this.exposure = 0.3;
  39400. /**
  39401. * Dissipates each sample's contribution in range [0, 1]
  39402. * @type {number}
  39403. */
  39404. this.decay = 0.96815;
  39405. /**
  39406. * Controls the overall intensity of each sample
  39407. * @type {number}
  39408. */
  39409. this.weight = 0.58767;
  39410. /**
  39411. * Controls the density of each sample
  39412. * @type {number}
  39413. */
  39414. this.density = 0.926;
  39415. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  39416. var engine = scene.getEngine();
  39417. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  39418. // Configure mesh
  39419. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  39420. // Configure
  39421. this._createPass(scene, ratio.passRatio || ratio);
  39422. this.onActivate = function (camera) {
  39423. if (!_this.isSupported) {
  39424. _this.dispose(camera);
  39425. }
  39426. _this.onActivate = null;
  39427. };
  39428. this.onApply = function (effect) {
  39429. _this._updateMeshScreenCoordinates(scene);
  39430. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  39431. effect.setFloat("exposure", _this.exposure);
  39432. effect.setFloat("decay", _this.decay);
  39433. effect.setFloat("weight", _this.weight);
  39434. effect.setFloat("density", _this.density);
  39435. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  39436. };
  39437. }
  39438. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  39439. get: function () {
  39440. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39441. return false;
  39442. },
  39443. set: function (useDiffuseColor) {
  39444. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39445. },
  39446. enumerable: true,
  39447. configurable: true
  39448. });
  39449. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  39450. var mesh = subMesh.getMesh();
  39451. // Render this.mesh as default
  39452. if (mesh === this.mesh) {
  39453. return mesh.material.isReady(mesh);
  39454. }
  39455. var defines = [];
  39456. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39457. var material = subMesh.getMaterial();
  39458. var needUV = false;
  39459. // Alpha test
  39460. if (material) {
  39461. if (material.needAlphaTesting()) {
  39462. defines.push("#define ALPHATEST");
  39463. }
  39464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39465. attribs.push(BABYLON.VertexBuffer.UVKind);
  39466. defines.push("#define UV1");
  39467. }
  39468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39469. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39470. defines.push("#define UV2");
  39471. }
  39472. }
  39473. // Bones
  39474. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39478. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39479. }
  39480. else {
  39481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39482. }
  39483. // Instances
  39484. if (useInstances) {
  39485. defines.push("#define INSTANCES");
  39486. attribs.push("world0");
  39487. attribs.push("world1");
  39488. attribs.push("world2");
  39489. attribs.push("world3");
  39490. }
  39491. // Get correct effect
  39492. var join = defines.join("\n");
  39493. if (this._cachedDefines !== join) {
  39494. this._cachedDefines = join;
  39495. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  39496. }
  39497. return this._volumetricLightScatteringPass.isReady();
  39498. };
  39499. /**
  39500. * Sets the new light position for light scattering effect
  39501. * @param {BABYLON.Vector3} The new custom light position
  39502. */
  39503. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  39504. this.customMeshPosition = position;
  39505. };
  39506. /**
  39507. * Returns the light position for light scattering effect
  39508. * @return {BABYLON.Vector3} The custom light position
  39509. */
  39510. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  39511. return this.customMeshPosition;
  39512. };
  39513. /**
  39514. * Disposes the internal assets and detaches the post-process from the camera
  39515. */
  39516. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  39517. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  39518. if (rttIndex !== -1) {
  39519. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  39520. }
  39521. this._volumetricLightScatteringRTT.dispose();
  39522. _super.prototype.dispose.call(this, camera);
  39523. };
  39524. /**
  39525. * Returns the render target texture used by the post-process
  39526. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  39527. */
  39528. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  39529. return this._volumetricLightScatteringRTT;
  39530. };
  39531. // Private methods
  39532. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  39533. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  39534. return true;
  39535. }
  39536. return false;
  39537. };
  39538. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  39539. var _this = this;
  39540. var engine = scene.getEngine();
  39541. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39542. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39543. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39544. this._volumetricLightScatteringRTT.renderList = null;
  39545. this._volumetricLightScatteringRTT.renderParticles = false;
  39546. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  39547. // Custom render function for submeshes
  39548. var renderSubMesh = function (subMesh) {
  39549. var mesh = subMesh.getRenderingMesh();
  39550. if (_this._meshExcluded(mesh)) {
  39551. return;
  39552. }
  39553. var scene = mesh.getScene();
  39554. var engine = scene.getEngine();
  39555. // Culling
  39556. engine.setState(subMesh.getMaterial().backFaceCulling);
  39557. // Managing instances
  39558. var batch = mesh._getInstancesRenderList(subMesh._id);
  39559. if (batch.mustReturn) {
  39560. return;
  39561. }
  39562. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39563. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39564. var effect = _this._volumetricLightScatteringPass;
  39565. if (mesh === _this.mesh) {
  39566. effect = subMesh.getMaterial().getEffect();
  39567. }
  39568. engine.enableEffect(effect);
  39569. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  39570. if (mesh === _this.mesh) {
  39571. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  39572. }
  39573. else {
  39574. var material = subMesh.getMaterial();
  39575. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  39576. // Alpha test
  39577. if (material && material.needAlphaTesting()) {
  39578. var alphaTexture = material.getAlphaTestTexture();
  39579. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  39580. if (alphaTexture) {
  39581. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39582. }
  39583. }
  39584. // Bones
  39585. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39586. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39587. }
  39588. }
  39589. // Draw
  39590. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  39591. }
  39592. };
  39593. // Render target texture callbacks
  39594. var savedSceneClearColor;
  39595. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  39596. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  39597. savedSceneClearColor = scene.clearColor;
  39598. scene.clearColor = sceneClearColor;
  39599. };
  39600. this._volumetricLightScatteringRTT.onAfterRender = function () {
  39601. scene.clearColor = savedSceneClearColor;
  39602. };
  39603. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  39604. var engine = scene.getEngine();
  39605. var index;
  39606. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39607. renderSubMesh(opaqueSubMeshes.data[index]);
  39608. }
  39609. engine.setAlphaTesting(true);
  39610. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39611. renderSubMesh(alphaTestSubMeshes.data[index]);
  39612. }
  39613. engine.setAlphaTesting(false);
  39614. if (transparentSubMeshes.length) {
  39615. // Sort sub meshes
  39616. for (index = 0; index < transparentSubMeshes.length; index++) {
  39617. var submesh = transparentSubMeshes.data[index];
  39618. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  39619. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  39620. }
  39621. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  39622. sortedArray.sort(function (a, b) {
  39623. // Alpha index first
  39624. if (a._alphaIndex > b._alphaIndex) {
  39625. return 1;
  39626. }
  39627. if (a._alphaIndex < b._alphaIndex) {
  39628. return -1;
  39629. }
  39630. // Then distance to camera
  39631. if (a._distanceToCamera < b._distanceToCamera) {
  39632. return 1;
  39633. }
  39634. if (a._distanceToCamera > b._distanceToCamera) {
  39635. return -1;
  39636. }
  39637. return 0;
  39638. });
  39639. // Render sub meshes
  39640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39641. for (index = 0; index < sortedArray.length; index++) {
  39642. renderSubMesh(sortedArray[index]);
  39643. }
  39644. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39645. }
  39646. };
  39647. };
  39648. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  39649. var transform = scene.getTransformMatrix();
  39650. var meshPosition;
  39651. if (this.useCustomMeshPosition) {
  39652. meshPosition = this.customMeshPosition;
  39653. }
  39654. else if (this.attachedNode) {
  39655. meshPosition = this.attachedNode.position;
  39656. }
  39657. else {
  39658. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  39659. }
  39660. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  39661. this._screenCoordinates.x = pos.x / this._viewPort.width;
  39662. this._screenCoordinates.y = pos.y / this._viewPort.height;
  39663. if (this.invert)
  39664. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  39665. };
  39666. // Static methods
  39667. /**
  39668. * Creates a default mesh for the Volumeric Light Scattering post-process
  39669. * @param {string} The mesh name
  39670. * @param {BABYLON.Scene} The scene where to create the mesh
  39671. * @return {BABYLON.Mesh} the default mesh
  39672. */
  39673. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  39674. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  39675. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  39676. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  39677. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  39678. mesh.material = material;
  39679. return mesh;
  39680. };
  39681. __decorate([
  39682. BABYLON.serializeAsVector3()
  39683. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  39684. __decorate([
  39685. BABYLON.serialize()
  39686. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  39687. __decorate([
  39688. BABYLON.serialize()
  39689. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  39690. __decorate([
  39691. BABYLON.serializeAsMeshReference()
  39692. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  39693. __decorate([
  39694. BABYLON.serialize()
  39695. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  39696. __decorate([
  39697. BABYLON.serialize()
  39698. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  39699. __decorate([
  39700. BABYLON.serialize()
  39701. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  39702. __decorate([
  39703. BABYLON.serialize()
  39704. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  39705. __decorate([
  39706. BABYLON.serialize()
  39707. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  39708. return VolumetricLightScatteringPostProcess;
  39709. })(BABYLON.PostProcess);
  39710. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  39711. })(BABYLON || (BABYLON = {}));
  39712. // BABYLON.JS Chromatic Aberration GLSL Shader
  39713. // Author: Olivier Guyot
  39714. // Separates very slightly R, G and B colors on the edges of the screen
  39715. // Inspired by Francois Tarlier & Martins Upitis
  39716. var BABYLON;
  39717. (function (BABYLON) {
  39718. var LensRenderingPipeline = (function (_super) {
  39719. __extends(LensRenderingPipeline, _super);
  39720. /**
  39721. * @constructor
  39722. *
  39723. * Effect parameters are as follow:
  39724. * {
  39725. * chromatic_aberration: number; // from 0 to x (1 for realism)
  39726. * edge_blur: number; // from 0 to x (1 for realism)
  39727. * distortion: number; // from 0 to x (1 for realism)
  39728. * grain_amount: number; // from 0 to 1
  39729. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  39730. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  39731. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  39732. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  39733. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  39734. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  39735. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  39736. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  39737. * }
  39738. * Note: if an effect parameter is unset, effect is disabled
  39739. *
  39740. * @param {string} name - The rendering pipeline name
  39741. * @param {object} parameters - An object containing all parameters (see above)
  39742. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39743. * @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)
  39744. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39745. */
  39746. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  39747. var _this = this;
  39748. if (ratio === void 0) { ratio = 1.0; }
  39749. _super.call(this, scene.getEngine(), name);
  39750. // Lens effects can be of the following:
  39751. // - chromatic aberration (slight shift of RGB colors)
  39752. // - blur on the edge of the lens
  39753. // - lens distortion
  39754. // - depth-of-field blur & highlights enhancing
  39755. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  39756. // - grain effect (noise or custom texture)
  39757. // Two additional texture samplers are needed:
  39758. // - depth map (for depth-of-field)
  39759. // - grain texture
  39760. /**
  39761. * The chromatic aberration PostProcess id in the pipeline
  39762. * @type {string}
  39763. */
  39764. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  39765. /**
  39766. * The highlights enhancing PostProcess id in the pipeline
  39767. * @type {string}
  39768. */
  39769. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  39770. /**
  39771. * The depth-of-field PostProcess id in the pipeline
  39772. * @type {string}
  39773. */
  39774. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  39775. this._scene = scene;
  39776. // Fetch texture samplers
  39777. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39778. if (parameters.grain_texture) {
  39779. this._grainTexture = parameters.grain_texture;
  39780. }
  39781. else {
  39782. this._createGrainTexture();
  39783. }
  39784. // save parameters
  39785. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  39786. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  39787. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  39788. this._distortion = parameters.distortion ? parameters.distortion : 0;
  39789. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  39790. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  39791. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  39792. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  39793. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  39794. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  39795. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  39796. // Create effects
  39797. this._createChromaticAberrationPostProcess(ratio);
  39798. this._createHighlightsPostProcess(ratio);
  39799. this._createDepthOfFieldPostProcess(ratio / 4);
  39800. // Set up pipeline
  39801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  39802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  39803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  39804. if (this._highlightsGain === -1) {
  39805. this._disableEffect(this.HighlightsEnhancingEffect, null);
  39806. }
  39807. // Finish
  39808. scene.postProcessRenderPipelineManager.addPipeline(this);
  39809. if (cameras) {
  39810. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39811. }
  39812. }
  39813. // public methods (self explanatory)
  39814. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  39815. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  39816. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  39817. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  39818. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  39819. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  39820. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  39821. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  39822. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  39823. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  39824. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  39825. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  39826. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  39827. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  39828. };
  39829. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  39830. this._highlightsPostProcess.updateEffect();
  39831. };
  39832. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  39833. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  39834. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  39835. this._highlightsGain = amount;
  39836. };
  39837. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  39838. if (this._highlightsGain === -1) {
  39839. this._highlightsGain = 1.0;
  39840. }
  39841. this._highlightsThreshold = amount;
  39842. };
  39843. LensRenderingPipeline.prototype.disableHighlights = function () {
  39844. this._highlightsGain = -1;
  39845. };
  39846. /**
  39847. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  39848. */
  39849. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39850. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39851. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39852. this._chromaticAberrationPostProcess = undefined;
  39853. this._highlightsPostProcess = undefined;
  39854. this._depthOfFieldPostProcess = undefined;
  39855. this._grainTexture.dispose();
  39856. if (disableDepthRender)
  39857. this._scene.disableDepthRenderer();
  39858. };
  39859. // colors shifting and distortion
  39860. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  39861. var _this = this;
  39862. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  39863. [], // samplers
  39864. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39865. this._chromaticAberrationPostProcess.onApply = function (effect) {
  39866. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  39867. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  39868. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  39869. };
  39870. };
  39871. // highlights enhancing
  39872. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  39873. var _this = this;
  39874. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  39875. [], // samplers
  39876. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  39877. this._highlightsPostProcess.onApply = function (effect) {
  39878. effect.setFloat('gain', _this._highlightsGain);
  39879. effect.setFloat('threshold', _this._highlightsThreshold);
  39880. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  39881. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  39882. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  39883. };
  39884. };
  39885. // colors shifting and distortion
  39886. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  39887. var _this = this;
  39888. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  39889. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  39890. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  39891. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39892. this._depthOfFieldPostProcess.onApply = function (effect) {
  39893. effect.setTexture("depthSampler", _this._depthTexture);
  39894. effect.setTexture("grainSampler", _this._grainTexture);
  39895. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  39896. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  39897. effect.setFloat('grain_amount', _this._grainAmount);
  39898. effect.setBool('blur_noise', _this._blurNoise);
  39899. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  39900. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  39901. effect.setFloat('distortion', _this._distortion);
  39902. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  39903. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  39904. effect.setFloat('aperture', _this._dofAperture);
  39905. effect.setFloat('darken', _this._dofDarken);
  39906. effect.setFloat('edge_blur', _this._edgeBlur);
  39907. effect.setBool('highlights', (_this._highlightsGain !== -1));
  39908. effect.setFloat('near', _this._scene.activeCamera.minZ);
  39909. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  39910. };
  39911. };
  39912. // creates a black and white random noise texture, 512x512
  39913. LensRenderingPipeline.prototype._createGrainTexture = function () {
  39914. var size = 512;
  39915. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39916. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39917. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39918. var context = this._grainTexture.getContext();
  39919. var rand = function (min, max) {
  39920. return Math.random() * (max - min) + min;
  39921. };
  39922. var value;
  39923. for (var x = 0; x < size; x++) {
  39924. for (var y = 0; y < size; y++) {
  39925. value = Math.floor(rand(0.42, 0.58) * 255);
  39926. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  39927. context.fillRect(x, y, 1, 1);
  39928. }
  39929. }
  39930. this._grainTexture.update(false);
  39931. };
  39932. return LensRenderingPipeline;
  39933. })(BABYLON.PostProcessRenderPipeline);
  39934. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  39935. })(BABYLON || (BABYLON = {}));
  39936. //
  39937. // This post-process allows the modification of rendered colors by using
  39938. // a 'look-up table' (LUT). This effect is also called Color Grading.
  39939. //
  39940. // The object needs to be provided an url to a texture containing the color
  39941. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  39942. // Use an image editing software to tweak the LUT to match your needs.
  39943. //
  39944. // For an example of a color LUT, see here:
  39945. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  39946. // For explanations on color grading, see here:
  39947. // http://udn.epicgames.com/Three/ColorGrading.html
  39948. //
  39949. var BABYLON;
  39950. (function (BABYLON) {
  39951. var ColorCorrectionPostProcess = (function (_super) {
  39952. __extends(ColorCorrectionPostProcess, _super);
  39953. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  39954. var _this = this;
  39955. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  39956. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39957. this._colorTableTexture.anisotropicFilteringLevel = 1;
  39958. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39959. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39960. this.onApply = function (effect) {
  39961. effect.setTexture("colorTable", _this._colorTableTexture);
  39962. };
  39963. }
  39964. return ColorCorrectionPostProcess;
  39965. })(BABYLON.PostProcess);
  39966. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  39967. })(BABYLON || (BABYLON = {}));
  39968. var BABYLON;
  39969. (function (BABYLON) {
  39970. var AnaglyphFreeCamera = (function (_super) {
  39971. __extends(AnaglyphFreeCamera, _super);
  39972. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39973. _super.call(this, name, position, scene);
  39974. this.interaxialDistance = interaxialDistance;
  39975. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39976. }
  39977. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39978. return "AnaglyphFreeCamera";
  39979. };
  39980. return AnaglyphFreeCamera;
  39981. })(BABYLON.FreeCamera);
  39982. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39983. var AnaglyphArcRotateCamera = (function (_super) {
  39984. __extends(AnaglyphArcRotateCamera, _super);
  39985. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39986. _super.call(this, name, alpha, beta, radius, target, scene);
  39987. this.interaxialDistance = interaxialDistance;
  39988. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39989. }
  39990. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39991. return "AnaglyphArcRotateCamera";
  39992. };
  39993. return AnaglyphArcRotateCamera;
  39994. })(BABYLON.ArcRotateCamera);
  39995. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39996. var AnaglyphGamepadCamera = (function (_super) {
  39997. __extends(AnaglyphGamepadCamera, _super);
  39998. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39999. _super.call(this, name, position, scene);
  40000. this.interaxialDistance = interaxialDistance;
  40001. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40002. }
  40003. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40004. return "AnaglyphGamepadCamera";
  40005. };
  40006. return AnaglyphGamepadCamera;
  40007. })(BABYLON.GamepadCamera);
  40008. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40009. var AnaglyphUniversalCamera = (function (_super) {
  40010. __extends(AnaglyphUniversalCamera, _super);
  40011. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40012. _super.call(this, name, position, scene);
  40013. this.interaxialDistance = interaxialDistance;
  40014. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40015. }
  40016. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40017. return "AnaglyphUniversalCamera";
  40018. };
  40019. return AnaglyphUniversalCamera;
  40020. })(BABYLON.UniversalCamera);
  40021. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40022. var StereoscopicFreeCamera = (function (_super) {
  40023. __extends(StereoscopicFreeCamera, _super);
  40024. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40025. _super.call(this, name, position, scene);
  40026. this.interaxialDistance = interaxialDistance;
  40027. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40028. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40029. }
  40030. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40031. return "StereoscopicFreeCamera";
  40032. };
  40033. return StereoscopicFreeCamera;
  40034. })(BABYLON.FreeCamera);
  40035. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40036. var StereoscopicArcRotateCamera = (function (_super) {
  40037. __extends(StereoscopicArcRotateCamera, _super);
  40038. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40039. _super.call(this, name, alpha, beta, radius, target, scene);
  40040. this.interaxialDistance = interaxialDistance;
  40041. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40042. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40043. }
  40044. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40045. return "StereoscopicArcRotateCamera";
  40046. };
  40047. return StereoscopicArcRotateCamera;
  40048. })(BABYLON.ArcRotateCamera);
  40049. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40050. var StereoscopicGamepadCamera = (function (_super) {
  40051. __extends(StereoscopicGamepadCamera, _super);
  40052. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40053. _super.call(this, name, position, scene);
  40054. this.interaxialDistance = interaxialDistance;
  40055. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40056. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40057. }
  40058. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40059. return "StereoscopicGamepadCamera";
  40060. };
  40061. return StereoscopicGamepadCamera;
  40062. })(BABYLON.GamepadCamera);
  40063. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40064. var StereoscopicUniversalCamera = (function (_super) {
  40065. __extends(StereoscopicUniversalCamera, _super);
  40066. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40067. _super.call(this, name, position, scene);
  40068. this.interaxialDistance = interaxialDistance;
  40069. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40070. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40071. }
  40072. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40073. return "StereoscopicUniversalCamera";
  40074. };
  40075. return StereoscopicUniversalCamera;
  40076. })(BABYLON.UniversalCamera);
  40077. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40078. })(BABYLON || (BABYLON = {}));
  40079. var BABYLON;
  40080. (function (BABYLON) {
  40081. var HDRRenderingPipeline = (function (_super) {
  40082. __extends(HDRRenderingPipeline, _super);
  40083. /**
  40084. * @constructor
  40085. * @param {string} name - The rendering pipeline name
  40086. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40087. * @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)
  40088. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40089. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40090. */
  40091. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40092. var _this = this;
  40093. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40094. _super.call(this, scene.getEngine(), name);
  40095. /**
  40096. * Public members
  40097. */
  40098. // Gaussian Blur
  40099. /**
  40100. * Gaussian blur coefficient
  40101. * @type {number}
  40102. */
  40103. this.gaussCoeff = 0.3;
  40104. /**
  40105. * Gaussian blur mean
  40106. * @type {number}
  40107. */
  40108. this.gaussMean = 1.0;
  40109. /**
  40110. * Gaussian blur standard deviation
  40111. * @type {number}
  40112. */
  40113. this.gaussStandDev = 0.8;
  40114. /**
  40115. * Gaussian blur multiplier. Multiplies the blur effect
  40116. * @type {number}
  40117. */
  40118. this.gaussMultiplier = 4.0;
  40119. // HDR
  40120. /**
  40121. * Exposure, controls the overall intensity of the pipeline
  40122. * @type {number}
  40123. */
  40124. this.exposure = 1.0;
  40125. /**
  40126. * Minimum luminance that the post-process can output. Luminance is >= 0
  40127. * @type {number}
  40128. */
  40129. this.minimumLuminance = 1.0;
  40130. /**
  40131. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40132. * @type {number}
  40133. */
  40134. this.maximumLuminance = 1e20;
  40135. /**
  40136. * Increase rate for luminance: eye adaptation speed to dark
  40137. * @type {number}
  40138. */
  40139. this.luminanceIncreaserate = 0.5;
  40140. /**
  40141. * Decrease rate for luminance: eye adaptation speed to bright
  40142. * @type {number}
  40143. */
  40144. this.luminanceDecreaseRate = 0.5;
  40145. // Bright pass
  40146. /**
  40147. * Minimum luminance needed to compute HDR
  40148. * @type {number}
  40149. */
  40150. this.brightThreshold = 0.8;
  40151. this._needUpdate = true;
  40152. this._scene = scene;
  40153. // Bright pass
  40154. this._createBrightPassPostProcess(scene, ratio);
  40155. // Down sample X4
  40156. this._createDownSampleX4PostProcess(scene, ratio);
  40157. // Create gaussian blur post-processes
  40158. this._createGaussianBlurPostProcess(scene, ratio);
  40159. // Texture adder
  40160. this._createTextureAdderPostProcess(scene, ratio);
  40161. // Luminance generator
  40162. this._createLuminanceGeneratorPostProcess(scene);
  40163. // HDR
  40164. this._createHDRPostProcess(scene, ratio);
  40165. // Pass postprocess
  40166. if (originalPostProcess === null) {
  40167. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40168. }
  40169. else {
  40170. this._originalPostProcess = originalPostProcess;
  40171. }
  40172. // Configure pipeline
  40173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40179. var addDownSamplerPostProcess = function (id) {
  40180. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40181. };
  40182. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40183. addDownSamplerPostProcess(i);
  40184. }
  40185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40186. // Finish
  40187. scene.postProcessRenderPipelineManager.addPipeline(this);
  40188. if (cameras !== null) {
  40189. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40190. }
  40191. this.update();
  40192. }
  40193. /**
  40194. * Tells the pipeline to update its post-processes
  40195. */
  40196. HDRRenderingPipeline.prototype.update = function () {
  40197. this._needUpdate = true;
  40198. };
  40199. /**
  40200. * Returns the current calculated luminance
  40201. */
  40202. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40203. return this._hdrCurrentLuminance;
  40204. };
  40205. /**
  40206. * Returns the currently drawn luminance
  40207. */
  40208. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40209. return this._hdrOutputLuminance;
  40210. };
  40211. /**
  40212. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40213. */
  40214. HDRRenderingPipeline.prototype.dispose = function () {
  40215. this._originalPostProcess = undefined;
  40216. this._brightPassPostProcess = undefined;
  40217. this._downSampleX4PostProcess = undefined;
  40218. this._guassianBlurHPostProcess = undefined;
  40219. this._guassianBlurVPostProcess = undefined;
  40220. this._textureAdderPostProcess = undefined;
  40221. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40222. this._downSamplePostProcesses[i] = undefined;
  40223. }
  40224. this._hdrPostProcess = undefined;
  40225. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40226. };
  40227. /**
  40228. * Creates the HDR post-process and computes the luminance adaptation
  40229. */
  40230. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40231. var _this = this;
  40232. var hdrLastLuminance = 0.0;
  40233. this._hdrOutputLuminance = -1.0;
  40234. this._hdrCurrentLuminance = 1.0;
  40235. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40236. this._hdrPostProcess.onApply = function (effect) {
  40237. if (_this._hdrOutputLuminance < 0.0) {
  40238. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40239. }
  40240. else {
  40241. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40242. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40243. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40244. }
  40245. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40246. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40247. }
  40248. else {
  40249. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40250. }
  40251. }
  40252. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40253. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40254. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40255. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40256. effect.setFloat("exposure", _this.exposure);
  40257. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40258. _this._needUpdate = false;
  40259. };
  40260. };
  40261. /**
  40262. * Texture Adder post-process
  40263. */
  40264. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40265. var _this = this;
  40266. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40267. this._textureAdderPostProcess.onApply = function (effect) {
  40268. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40269. };
  40270. };
  40271. /**
  40272. * Down sample X4 post-process
  40273. */
  40274. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40275. var _this = this;
  40276. var downSampleX4Offsets = new Array(32);
  40277. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40278. this._downSampleX4PostProcess.onApply = function (effect) {
  40279. if (_this._needUpdate) {
  40280. var id = 0;
  40281. for (var i = -2; i < 2; i++) {
  40282. for (var j = -2; j < 2; j++) {
  40283. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40284. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40285. id += 2;
  40286. }
  40287. }
  40288. }
  40289. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40290. };
  40291. };
  40292. /**
  40293. * Bright pass post-process
  40294. */
  40295. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40296. var _this = this;
  40297. var brightOffsets = new Array(8);
  40298. var brightPassCallback = function (effect) {
  40299. if (_this._needUpdate) {
  40300. var sU = (1.0 / _this._brightPassPostProcess.width);
  40301. var sV = (1.0 / _this._brightPassPostProcess.height);
  40302. brightOffsets[0] = -0.5 * sU;
  40303. brightOffsets[1] = 0.5 * sV;
  40304. brightOffsets[2] = 0.5 * sU;
  40305. brightOffsets[3] = 0.5 * sV;
  40306. brightOffsets[4] = -0.5 * sU;
  40307. brightOffsets[5] = -0.5 * sV;
  40308. brightOffsets[6] = 0.5 * sU;
  40309. brightOffsets[7] = -0.5 * sV;
  40310. }
  40311. effect.setArray2("dsOffsets", brightOffsets);
  40312. effect.setFloat("brightThreshold", _this.brightThreshold);
  40313. };
  40314. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40315. this._brightPassPostProcess.onApply = brightPassCallback;
  40316. };
  40317. /**
  40318. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40319. */
  40320. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40321. var _this = this;
  40322. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40323. var luminanceOffsets = new Array(8);
  40324. var downSampleOffsets = new Array(18);
  40325. var halfDestPixelSize;
  40326. this._downSamplePostProcesses = new Array(lumSteps);
  40327. // Utils for luminance
  40328. var luminanceUpdateSourceOffsets = function (width, height) {
  40329. var sU = (1.0 / width);
  40330. var sV = (1.0 / height);
  40331. luminanceOffsets[0] = -0.5 * sU;
  40332. luminanceOffsets[1] = 0.5 * sV;
  40333. luminanceOffsets[2] = 0.5 * sU;
  40334. luminanceOffsets[3] = 0.5 * sV;
  40335. luminanceOffsets[4] = -0.5 * sU;
  40336. luminanceOffsets[5] = -0.5 * sV;
  40337. luminanceOffsets[6] = 0.5 * sU;
  40338. luminanceOffsets[7] = -0.5 * sV;
  40339. };
  40340. var luminanceUpdateDestOffsets = function (width, height) {
  40341. var id = 0;
  40342. for (var x = -1; x < 2; x++) {
  40343. for (var y = -1; y < 2; y++) {
  40344. downSampleOffsets[id] = (x) / width;
  40345. downSampleOffsets[id + 1] = (y) / height;
  40346. id += 2;
  40347. }
  40348. }
  40349. };
  40350. // Luminance callback
  40351. var luminanceCallback = function (effect) {
  40352. if (_this._needUpdate) {
  40353. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40354. }
  40355. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40356. effect.setArray2("lumOffsets", luminanceOffsets);
  40357. };
  40358. // Down sample callbacks
  40359. var downSampleCallback = function (indice) {
  40360. var i = indice;
  40361. return function (effect) {
  40362. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40363. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40364. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40365. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40366. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40367. effect.setArray2("dsOffsets", downSampleOffsets);
  40368. };
  40369. };
  40370. var downSampleAfterRenderCallback = function (effect) {
  40371. // Unpack result
  40372. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40373. 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);
  40374. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40375. };
  40376. // Create luminance post-process
  40377. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40378. 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);
  40379. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40380. // Create down sample post-processes
  40381. for (var i = lumSteps - 2; i >= 0; i--) {
  40382. var length = Math.pow(3, i);
  40383. ratio = { width: length, height: length };
  40384. var defines = "#define DOWN_SAMPLE\n";
  40385. if (i === 0) {
  40386. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40387. }
  40388. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40389. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40390. if (i === 0) {
  40391. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40392. }
  40393. }
  40394. };
  40395. /**
  40396. * Gaussian blur post-processes. Horizontal and Vertical
  40397. */
  40398. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40399. var _this = this;
  40400. var blurOffsetsW = new Array(9);
  40401. var blurOffsetsH = new Array(9);
  40402. var blurWeights = new Array(9);
  40403. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40404. // Utils for gaussian blur
  40405. var calculateBlurOffsets = function (height) {
  40406. var lastOutputDimensions = {
  40407. width: scene.getEngine().getRenderWidth(),
  40408. height: scene.getEngine().getRenderHeight()
  40409. };
  40410. for (var i = 0; i < 9; i++) {
  40411. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  40412. if (height) {
  40413. blurOffsetsH[i] = value;
  40414. }
  40415. else {
  40416. blurOffsetsW[i] = value;
  40417. }
  40418. }
  40419. };
  40420. var calculateWeights = function () {
  40421. var x = 0.0;
  40422. for (var i = 0; i < 9; i++) {
  40423. x = (i - 4.0) / 4.0;
  40424. 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));
  40425. }
  40426. };
  40427. // Callback
  40428. var gaussianBlurCallback = function (height) {
  40429. return function (effect) {
  40430. if (_this._needUpdate) {
  40431. calculateWeights();
  40432. calculateBlurOffsets(height);
  40433. }
  40434. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  40435. effect.setArray("blurWeights", blurWeights);
  40436. effect.setFloat("multiplier", _this.gaussMultiplier);
  40437. };
  40438. };
  40439. // Create horizontal gaussian blur post-processes
  40440. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  40441. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  40442. // Create vertical gaussian blur post-process
  40443. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  40444. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  40445. };
  40446. // Luminance generator
  40447. HDRRenderingPipeline.LUM_STEPS = 6;
  40448. return HDRRenderingPipeline;
  40449. })(BABYLON.PostProcessRenderPipeline);
  40450. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  40451. })(BABYLON || (BABYLON = {}));
  40452. var BABYLON;
  40453. (function (BABYLON) {
  40454. var FaceAdjacencies = (function () {
  40455. function FaceAdjacencies() {
  40456. this.edges = new Array();
  40457. this.edgesConnectedCount = 0;
  40458. }
  40459. return FaceAdjacencies;
  40460. })();
  40461. var EdgesRenderer = (function () {
  40462. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  40463. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  40464. if (epsilon === void 0) { epsilon = 0.95; }
  40465. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  40466. this.edgesWidthScalerForOrthographic = 1000.0;
  40467. this.edgesWidthScalerForPerspective = 50.0;
  40468. this._linesPositions = new Array();
  40469. this._linesNormals = new Array();
  40470. this._linesIndices = new Array();
  40471. this._buffers = new Array();
  40472. this._checkVerticesInsteadOfIndices = false;
  40473. this._source = source;
  40474. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  40475. this._epsilon = epsilon;
  40476. this._prepareRessources();
  40477. this._generateEdgesLines();
  40478. }
  40479. EdgesRenderer.prototype._prepareRessources = function () {
  40480. if (this._lineShader) {
  40481. return;
  40482. }
  40483. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  40484. attributes: ["position", "normal"],
  40485. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  40486. });
  40487. this._lineShader.disableDepthWrite = true;
  40488. this._lineShader.backFaceCulling = false;
  40489. };
  40490. EdgesRenderer.prototype.dispose = function () {
  40491. this._vb0.dispose();
  40492. this._vb1.dispose();
  40493. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  40494. this._lineShader.dispose();
  40495. };
  40496. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  40497. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  40498. return 0;
  40499. }
  40500. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  40501. return 1;
  40502. }
  40503. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  40504. return 2;
  40505. }
  40506. return -1;
  40507. };
  40508. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  40509. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  40510. return 0;
  40511. }
  40512. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  40513. return 1;
  40514. }
  40515. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  40516. return 2;
  40517. }
  40518. return -1;
  40519. };
  40520. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  40521. var needToCreateLine;
  40522. if (edge === undefined) {
  40523. needToCreateLine = true;
  40524. }
  40525. else {
  40526. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  40527. needToCreateLine = dotProduct < this._epsilon;
  40528. }
  40529. if (needToCreateLine) {
  40530. var offset = this._linesPositions.length / 3;
  40531. var normal = p0.subtract(p1);
  40532. normal.normalize();
  40533. // Positions
  40534. this._linesPositions.push(p0.x);
  40535. this._linesPositions.push(p0.y);
  40536. this._linesPositions.push(p0.z);
  40537. this._linesPositions.push(p0.x);
  40538. this._linesPositions.push(p0.y);
  40539. this._linesPositions.push(p0.z);
  40540. this._linesPositions.push(p1.x);
  40541. this._linesPositions.push(p1.y);
  40542. this._linesPositions.push(p1.z);
  40543. this._linesPositions.push(p1.x);
  40544. this._linesPositions.push(p1.y);
  40545. this._linesPositions.push(p1.z);
  40546. // Normals
  40547. this._linesNormals.push(p1.x);
  40548. this._linesNormals.push(p1.y);
  40549. this._linesNormals.push(p1.z);
  40550. this._linesNormals.push(-1);
  40551. this._linesNormals.push(p1.x);
  40552. this._linesNormals.push(p1.y);
  40553. this._linesNormals.push(p1.z);
  40554. this._linesNormals.push(1);
  40555. this._linesNormals.push(p0.x);
  40556. this._linesNormals.push(p0.y);
  40557. this._linesNormals.push(p0.z);
  40558. this._linesNormals.push(-1);
  40559. this._linesNormals.push(p0.x);
  40560. this._linesNormals.push(p0.y);
  40561. this._linesNormals.push(p0.z);
  40562. this._linesNormals.push(1);
  40563. // Indices
  40564. this._linesIndices.push(offset);
  40565. this._linesIndices.push(offset + 1);
  40566. this._linesIndices.push(offset + 2);
  40567. this._linesIndices.push(offset);
  40568. this._linesIndices.push(offset + 2);
  40569. this._linesIndices.push(offset + 3);
  40570. }
  40571. };
  40572. EdgesRenderer.prototype._generateEdgesLines = function () {
  40573. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40574. var indices = this._source.getIndices();
  40575. // First let's find adjacencies
  40576. var adjacencies = new Array();
  40577. var faceNormals = new Array();
  40578. var index;
  40579. var faceAdjacencies;
  40580. // Prepare faces
  40581. for (index = 0; index < indices.length; index += 3) {
  40582. faceAdjacencies = new FaceAdjacencies();
  40583. var p0Index = indices[index];
  40584. var p1Index = indices[index + 1];
  40585. var p2Index = indices[index + 2];
  40586. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  40587. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  40588. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  40589. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  40590. faceNormal.normalize();
  40591. faceNormals.push(faceNormal);
  40592. adjacencies.push(faceAdjacencies);
  40593. }
  40594. // Scan
  40595. for (index = 0; index < adjacencies.length; index++) {
  40596. faceAdjacencies = adjacencies[index];
  40597. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  40598. var otherFaceAdjacencies = adjacencies[otherIndex];
  40599. if (faceAdjacencies.edgesConnectedCount === 3) {
  40600. break;
  40601. }
  40602. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  40603. continue;
  40604. }
  40605. var otherP0 = indices[otherIndex * 3];
  40606. var otherP1 = indices[otherIndex * 3 + 1];
  40607. var otherP2 = indices[otherIndex * 3 + 2];
  40608. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  40609. var otherEdgeIndex;
  40610. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  40611. continue;
  40612. }
  40613. switch (edgeIndex) {
  40614. case 0:
  40615. if (this._checkVerticesInsteadOfIndices) {
  40616. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  40617. }
  40618. else {
  40619. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  40620. }
  40621. break;
  40622. case 1:
  40623. if (this._checkVerticesInsteadOfIndices) {
  40624. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  40625. }
  40626. else {
  40627. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  40628. }
  40629. break;
  40630. case 2:
  40631. if (this._checkVerticesInsteadOfIndices) {
  40632. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  40633. }
  40634. else {
  40635. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  40636. }
  40637. break;
  40638. }
  40639. if (otherEdgeIndex === -1) {
  40640. continue;
  40641. }
  40642. faceAdjacencies.edges[edgeIndex] = otherIndex;
  40643. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  40644. faceAdjacencies.edgesConnectedCount++;
  40645. otherFaceAdjacencies.edgesConnectedCount++;
  40646. if (faceAdjacencies.edgesConnectedCount === 3) {
  40647. break;
  40648. }
  40649. }
  40650. }
  40651. }
  40652. // Create lines
  40653. for (index = 0; index < adjacencies.length; index++) {
  40654. // 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
  40655. var current = adjacencies[index];
  40656. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  40657. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  40658. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  40659. }
  40660. // Merge into a single mesh
  40661. var engine = this._source.getScene().getEngine();
  40662. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  40663. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  40664. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  40665. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  40666. this._ib = engine.createIndexBuffer(this._linesIndices);
  40667. this._indicesCount = this._linesIndices.length;
  40668. };
  40669. EdgesRenderer.prototype.render = function () {
  40670. if (!this._lineShader.isReady()) {
  40671. return;
  40672. }
  40673. var scene = this._source.getScene();
  40674. var engine = scene.getEngine();
  40675. this._lineShader._preBind();
  40676. // VBOs
  40677. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  40678. scene.resetCachedMaterial();
  40679. this._lineShader.setColor4("color", this._source.edgesColor);
  40680. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  40681. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  40682. }
  40683. else {
  40684. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  40685. }
  40686. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  40687. this._lineShader.bind(this._source.getWorldMatrix());
  40688. // Draw order
  40689. engine.draw(true, 0, this._indicesCount);
  40690. this._lineShader.unbind();
  40691. engine.setDepthWrite(true);
  40692. };
  40693. return EdgesRenderer;
  40694. })();
  40695. BABYLON.EdgesRenderer = EdgesRenderer;
  40696. })(BABYLON || (BABYLON = {}));
  40697. var BABYLON;
  40698. (function (BABYLON) {
  40699. (function (TonemappingOperator) {
  40700. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  40701. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  40702. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  40703. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  40704. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  40705. var TonemappingOperator = BABYLON.TonemappingOperator;
  40706. ;
  40707. var TonemapPostProcess = (function (_super) {
  40708. __extends(TonemapPostProcess, _super);
  40709. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  40710. var _this = this;
  40711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40712. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40713. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  40714. this._operator = _operator;
  40715. this.exposureAdjustment = exposureAdjustment;
  40716. var defines = "#define ";
  40717. if (this._operator === TonemappingOperator.Hable)
  40718. defines += "HABLE_TONEMAPPING";
  40719. else if (this._operator === TonemappingOperator.Reinhard)
  40720. defines += "REINHARD_TONEMAPPING";
  40721. else if (this._operator === TonemappingOperator.HejiDawson)
  40722. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  40723. else if (this._operator === TonemappingOperator.Photographic)
  40724. defines += "PHOTOGRAPHIC_TONEMAPPING";
  40725. //sadly a second call to create the effect.
  40726. this.updateEffect(defines);
  40727. this.onApply = function (effect) {
  40728. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  40729. };
  40730. }
  40731. return TonemapPostProcess;
  40732. })(BABYLON.PostProcess);
  40733. BABYLON.TonemapPostProcess = TonemapPostProcess;
  40734. })(BABYLON || (BABYLON = {}));
  40735. var BABYLON;
  40736. (function (BABYLON) {
  40737. var ReflectionProbe = (function () {
  40738. function ReflectionProbe(name, size, scene, generateMipMaps) {
  40739. var _this = this;
  40740. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40741. this.name = name;
  40742. this._viewMatrix = BABYLON.Matrix.Identity();
  40743. this._target = BABYLON.Vector3.Zero();
  40744. this._add = BABYLON.Vector3.Zero();
  40745. this.position = BABYLON.Vector3.Zero();
  40746. this._scene = scene;
  40747. this._scene.reflectionProbes.push(this);
  40748. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  40749. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  40750. switch (faceIndex) {
  40751. case 0:
  40752. _this._add.copyFromFloats(1, 0, 0);
  40753. break;
  40754. case 1:
  40755. _this._add.copyFromFloats(-1, 0, 0);
  40756. break;
  40757. case 2:
  40758. _this._add.copyFromFloats(0, -1, 0);
  40759. break;
  40760. case 3:
  40761. _this._add.copyFromFloats(0, 1, 0);
  40762. break;
  40763. case 4:
  40764. _this._add.copyFromFloats(0, 0, 1);
  40765. break;
  40766. case 5:
  40767. _this._add.copyFromFloats(0, 0, -1);
  40768. break;
  40769. }
  40770. if (_this._attachedMesh) {
  40771. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  40772. }
  40773. _this.position.addToRef(_this._add, _this._target);
  40774. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  40775. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  40776. };
  40777. this._renderTargetTexture.onAfterUnbind = function () {
  40778. scene.updateTransformMatrix(true);
  40779. };
  40780. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  40781. }
  40782. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  40783. get: function () {
  40784. return this._renderTargetTexture.refreshRate;
  40785. },
  40786. set: function (value) {
  40787. this._renderTargetTexture.refreshRate = value;
  40788. },
  40789. enumerable: true,
  40790. configurable: true
  40791. });
  40792. ReflectionProbe.prototype.getScene = function () {
  40793. return this._scene;
  40794. };
  40795. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  40796. get: function () {
  40797. return this._renderTargetTexture;
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  40803. get: function () {
  40804. return this._renderTargetTexture.renderList;
  40805. },
  40806. enumerable: true,
  40807. configurable: true
  40808. });
  40809. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  40810. this._attachedMesh = mesh;
  40811. };
  40812. ReflectionProbe.prototype.dispose = function () {
  40813. var index = this._scene.reflectionProbes.indexOf(this);
  40814. if (index !== -1) {
  40815. // Remove from the scene if found
  40816. this._scene.reflectionProbes.splice(index, 1);
  40817. }
  40818. if (this._renderTargetTexture) {
  40819. this._renderTargetTexture.dispose();
  40820. this._renderTargetTexture = null;
  40821. }
  40822. };
  40823. return ReflectionProbe;
  40824. })();
  40825. BABYLON.ReflectionProbe = ReflectionProbe;
  40826. })(BABYLON || (BABYLON = {}));
  40827. var BABYLON;
  40828. (function (BABYLON) {
  40829. var SolidParticle = (function () {
  40830. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  40831. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  40832. this.position = BABYLON.Vector3.Zero(); // position
  40833. this.rotation = BABYLON.Vector3.Zero(); // rotation
  40834. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  40835. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  40836. this.velocity = BABYLON.Vector3.Zero(); // velocity
  40837. this.alive = true; // alive
  40838. this.idx = particleIndex;
  40839. this._pos = positionIndex;
  40840. this._model = model;
  40841. this.shapeId = shapeId;
  40842. this.idxInShape = idxInShape;
  40843. }
  40844. Object.defineProperty(SolidParticle.prototype, "scale", {
  40845. //legacy support, changed scale to scaling
  40846. get: function () {
  40847. return this.scaling;
  40848. },
  40849. set: function (scale) {
  40850. this.scaling = scale;
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40856. //legacy support, changed quaternion to rotationQuaternion
  40857. get: function () {
  40858. return this.rotationQuaternion;
  40859. },
  40860. set: function (q) {
  40861. this.rotationQuaternion = q;
  40862. },
  40863. enumerable: true,
  40864. configurable: true
  40865. });
  40866. return SolidParticle;
  40867. })();
  40868. BABYLON.SolidParticle = SolidParticle;
  40869. var ModelShape = (function () {
  40870. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40871. this.shapeID = id;
  40872. this._shape = shape;
  40873. this._shapeUV = shapeUV;
  40874. this._positionFunction = posFunction;
  40875. this._vertexFunction = vtxFunction;
  40876. }
  40877. return ModelShape;
  40878. })();
  40879. BABYLON.ModelShape = ModelShape;
  40880. })(BABYLON || (BABYLON = {}));
  40881. var BABYLON;
  40882. (function (BABYLON) {
  40883. /**
  40884. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  40885. */
  40886. var SolidParticleSystem = (function () {
  40887. /**
  40888. * Creates a SPS (Solid Particle System) object.
  40889. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40890. * `scene` (Scene) is the scene in which the SPS is added.
  40891. * `updatableè (default true) : if the SPS must be updatable or immutable.
  40892. * `isPickable` (default false) : if the solid particles must be pickable.
  40893. */
  40894. function SolidParticleSystem(name, scene, options) {
  40895. // public members
  40896. /**
  40897. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40898. * Example : var p = SPS.particles[i];
  40899. */
  40900. this.particles = new Array();
  40901. /**
  40902. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40903. */
  40904. this.nbParticles = 0;
  40905. /**
  40906. * If the particles must ever face the camera (default false). Useful for planar particles.
  40907. */
  40908. this.billboard = false;
  40909. /**
  40910. * This a counter ofr your own usage. It's not set by any SPS functions.
  40911. */
  40912. this.counter = 0;
  40913. /**
  40914. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40915. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  40916. */
  40917. this.vars = {};
  40918. this._positions = new Array();
  40919. this._indices = new Array();
  40920. this._normals = new Array();
  40921. this._colors = new Array();
  40922. this._uvs = new Array();
  40923. this._index = 0; // indices index
  40924. this._updatable = true;
  40925. this._pickable = false;
  40926. this._isVisibilityBoxLocked = false;
  40927. this._alwaysVisible = false;
  40928. this._shapeCounter = 0;
  40929. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  40930. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40931. this._computeParticleColor = true;
  40932. this._computeParticleTexture = true;
  40933. this._computeParticleRotation = true;
  40934. this._computeParticleVertex = false;
  40935. this._computeBoundingBox = false;
  40936. this._cam_axisZ = BABYLON.Vector3.Zero();
  40937. this._cam_axisY = BABYLON.Vector3.Zero();
  40938. this._cam_axisX = BABYLON.Vector3.Zero();
  40939. this._axisX = BABYLON.Axis.X;
  40940. this._axisY = BABYLON.Axis.Y;
  40941. this._axisZ = BABYLON.Axis.Z;
  40942. this._fakeCamPos = BABYLON.Vector3.Zero();
  40943. this._rotMatrix = new BABYLON.Matrix();
  40944. this._invertMatrix = new BABYLON.Matrix();
  40945. this._rotated = BABYLON.Vector3.Zero();
  40946. this._quaternion = new BABYLON.Quaternion();
  40947. this._vertex = BABYLON.Vector3.Zero();
  40948. this._normal = BABYLON.Vector3.Zero();
  40949. this._yaw = 0.0;
  40950. this._pitch = 0.0;
  40951. this._roll = 0.0;
  40952. this._halfroll = 0.0;
  40953. this._halfpitch = 0.0;
  40954. this._halfyaw = 0.0;
  40955. this._sinRoll = 0.0;
  40956. this._cosRoll = 0.0;
  40957. this._sinPitch = 0.0;
  40958. this._cosPitch = 0.0;
  40959. this._sinYaw = 0.0;
  40960. this._cosYaw = 0.0;
  40961. this._w = 0.0;
  40962. this._minimum = BABYLON.Tmp.Vector3[0];
  40963. this._maximum = BABYLON.Tmp.Vector3[1];
  40964. this.name = name;
  40965. this._scene = scene;
  40966. this._camera = scene.activeCamera;
  40967. this._pickable = options ? options.isPickable : false;
  40968. if (options && options.updatable) {
  40969. this._updatable = options.updatable;
  40970. }
  40971. else {
  40972. this._updatable = true;
  40973. }
  40974. if (this._pickable) {
  40975. this.pickedParticles = [];
  40976. }
  40977. }
  40978. /**
  40979. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40980. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40981. */
  40982. SolidParticleSystem.prototype.buildMesh = function () {
  40983. if (this.nbParticles === 0) {
  40984. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40985. this.addShape(triangle, 1);
  40986. triangle.dispose();
  40987. }
  40988. this._positions32 = new Float32Array(this._positions);
  40989. this._uvs32 = new Float32Array(this._uvs);
  40990. this._colors32 = new Float32Array(this._colors);
  40991. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40992. this._normals32 = new Float32Array(this._normals);
  40993. this._fixedNormal32 = new Float32Array(this._normals);
  40994. var vertexData = new BABYLON.VertexData();
  40995. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40996. vertexData.indices = this._indices;
  40997. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40998. if (this._uvs32) {
  40999. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41000. ;
  41001. }
  41002. if (this._colors32) {
  41003. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41004. }
  41005. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41006. vertexData.applyToMesh(mesh, this._updatable);
  41007. this.mesh = mesh;
  41008. this.mesh.isPickable = this._pickable;
  41009. // free memory
  41010. this._positions = null;
  41011. this._normals = null;
  41012. this._uvs = null;
  41013. this._colors = null;
  41014. if (!this._updatable) {
  41015. this.particles.length = 0;
  41016. }
  41017. return mesh;
  41018. };
  41019. /**
  41020. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41021. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41022. * Thus the particles generated from `digest()` have their property `position` set yet.
  41023. * `mesh` (`Mesh`) is the mesh to be digested
  41024. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41025. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41026. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41027. */
  41028. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41029. var size = (options && options.facetNb) || 1;
  41030. var number = (options && options.number);
  41031. var delta = (options && options.delta) || 0;
  41032. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41033. var meshInd = mesh.getIndices();
  41034. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41035. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41036. var f = 0; // facet counter
  41037. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41038. // compute size from number
  41039. if (number) {
  41040. number = (number > totalFacets) ? totalFacets : number;
  41041. size = Math.round(totalFacets / number);
  41042. delta = 0;
  41043. }
  41044. else {
  41045. size = (size > totalFacets) ? totalFacets : size;
  41046. }
  41047. var facetPos = []; // submesh positions
  41048. var facetInd = []; // submesh indices
  41049. var facetUV = []; // submesh UV
  41050. var facetCol = []; // submesh colors
  41051. var barycenter = BABYLON.Tmp.Vector3[0];
  41052. var rand;
  41053. var sizeO = size;
  41054. while (f < totalFacets) {
  41055. size = sizeO + Math.floor((1 + delta) * Math.random());
  41056. if (f > totalFacets - size) {
  41057. size = totalFacets - f;
  41058. }
  41059. // reset temp arrays
  41060. facetPos.length = 0;
  41061. facetInd.length = 0;
  41062. facetUV.length = 0;
  41063. facetCol.length = 0;
  41064. // iterate over "size" facets
  41065. var fi = 0;
  41066. for (var j = f * 3; j < (f + size) * 3; j++) {
  41067. facetInd.push(fi);
  41068. var i = meshInd[j];
  41069. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41070. if (meshUV) {
  41071. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41072. }
  41073. if (meshCol) {
  41074. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41075. }
  41076. fi++;
  41077. }
  41078. // create a model shape for each single particle
  41079. var idx = this.nbParticles;
  41080. var shape = this._posToShape(facetPos);
  41081. var shapeUV = this._uvsToShapeUV(facetUV);
  41082. // compute the barycenter of the shape
  41083. var v;
  41084. for (v = 0; v < shape.length; v++) {
  41085. barycenter.addInPlace(shape[v]);
  41086. }
  41087. barycenter.scaleInPlace(1 / shape.length);
  41088. // shift the shape from its barycenter to the origin
  41089. for (v = 0; v < shape.length; v++) {
  41090. shape[v].subtractInPlace(barycenter);
  41091. }
  41092. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41093. // add the particle in the SPS
  41094. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41095. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41096. // initialize the particle position
  41097. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41098. this._index += shape.length;
  41099. idx++;
  41100. this.nbParticles++;
  41101. this._shapeCounter++;
  41102. f += size;
  41103. }
  41104. return this;
  41105. };
  41106. //reset copy
  41107. SolidParticleSystem.prototype._resetCopy = function () {
  41108. this._copy.position.x = 0;
  41109. this._copy.position.y = 0;
  41110. this._copy.position.z = 0;
  41111. this._copy.rotation.x = 0;
  41112. this._copy.rotation.y = 0;
  41113. this._copy.rotation.z = 0;
  41114. this._copy.rotationQuaternion = null;
  41115. this._copy.scaling.x = 1;
  41116. this._copy.scaling.y = 1;
  41117. this._copy.scaling.z = 1;
  41118. this._copy.uvs.x = 0;
  41119. this._copy.uvs.y = 0;
  41120. this._copy.uvs.z = 1;
  41121. this._copy.uvs.w = 1;
  41122. this._copy.color = null;
  41123. };
  41124. // _meshBuilder : inserts the shape model in the global SPS mesh
  41125. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41126. var i;
  41127. var u = 0;
  41128. var c = 0;
  41129. this._resetCopy();
  41130. if (options && options.positionFunction) {
  41131. options.positionFunction(this._copy, idx, idxInShape);
  41132. }
  41133. if (this._copy.rotationQuaternion) {
  41134. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41135. }
  41136. else {
  41137. this._yaw = this._copy.rotation.y;
  41138. this._pitch = this._copy.rotation.x;
  41139. this._roll = this._copy.rotation.z;
  41140. this._quaternionRotationYPR();
  41141. }
  41142. this._quaternionToRotationMatrix();
  41143. for (i = 0; i < shape.length; i++) {
  41144. this._vertex.x = shape[i].x;
  41145. this._vertex.y = shape[i].y;
  41146. this._vertex.z = shape[i].z;
  41147. if (options && options.vertexFunction) {
  41148. options.vertexFunction(this._copy, this._vertex, i);
  41149. }
  41150. this._vertex.x *= this._copy.scaling.x;
  41151. this._vertex.y *= this._copy.scaling.y;
  41152. this._vertex.z *= this._copy.scaling.z;
  41153. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41154. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41155. if (meshUV) {
  41156. 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);
  41157. u += 2;
  41158. }
  41159. if (this._copy.color) {
  41160. this._color = this._copy.color;
  41161. }
  41162. else if (meshCol && meshCol[c]) {
  41163. this._color.r = meshCol[c];
  41164. this._color.g = meshCol[c + 1];
  41165. this._color.b = meshCol[c + 2];
  41166. this._color.a = meshCol[c + 3];
  41167. }
  41168. else {
  41169. this._color.r = 1;
  41170. this._color.g = 1;
  41171. this._color.b = 1;
  41172. this._color.a = 1;
  41173. }
  41174. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41175. c += 4;
  41176. }
  41177. for (i = 0; i < meshInd.length; i++) {
  41178. indices.push(p + meshInd[i]);
  41179. }
  41180. if (this._pickable) {
  41181. var nbfaces = meshInd.length / 3;
  41182. for (i = 0; i < nbfaces; i++) {
  41183. this.pickedParticles.push({ idx: idx, faceId: i });
  41184. }
  41185. }
  41186. };
  41187. // returns a shape array from positions array
  41188. SolidParticleSystem.prototype._posToShape = function (positions) {
  41189. var shape = [];
  41190. for (var i = 0; i < positions.length; i += 3) {
  41191. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41192. }
  41193. return shape;
  41194. };
  41195. // returns a shapeUV array from a Vector4 uvs
  41196. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41197. var shapeUV = [];
  41198. if (uvs) {
  41199. for (var i = 0; i < uvs.length; i++)
  41200. shapeUV.push(uvs[i]);
  41201. }
  41202. return shapeUV;
  41203. };
  41204. // adds a new particle object in the particles array
  41205. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41206. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41207. };
  41208. /**
  41209. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41210. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41211. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41212. * `nb` (positive integer) the number of particles to be created from this model
  41213. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41214. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41215. */
  41216. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41217. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41218. var meshInd = mesh.getIndices();
  41219. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41220. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41221. var shape = this._posToShape(meshPos);
  41222. var shapeUV = this._uvsToShapeUV(meshUV);
  41223. var posfunc = options ? options.positionFunction : null;
  41224. var vtxfunc = options ? options.vertexFunction : null;
  41225. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41226. // particles
  41227. var idx = this.nbParticles;
  41228. for (var i = 0; i < nb; i++) {
  41229. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41230. if (this._updatable) {
  41231. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41232. }
  41233. this._index += shape.length;
  41234. idx++;
  41235. }
  41236. this.nbParticles += nb;
  41237. this._shapeCounter++;
  41238. return this._shapeCounter - 1;
  41239. };
  41240. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41241. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41242. this._resetCopy();
  41243. if (particle._model._positionFunction) {
  41244. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41245. }
  41246. if (this._copy.rotationQuaternion) {
  41247. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41248. }
  41249. else {
  41250. this._yaw = this._copy.rotation.y;
  41251. this._pitch = this._copy.rotation.x;
  41252. this._roll = this._copy.rotation.z;
  41253. this._quaternionRotationYPR();
  41254. }
  41255. this._quaternionToRotationMatrix();
  41256. this._shape = particle._model._shape;
  41257. for (var pt = 0; pt < this._shape.length; pt++) {
  41258. this._vertex.x = this._shape[pt].x;
  41259. this._vertex.y = this._shape[pt].y;
  41260. this._vertex.z = this._shape[pt].z;
  41261. if (particle._model._vertexFunction) {
  41262. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41263. }
  41264. this._vertex.x *= this._copy.scaling.x;
  41265. this._vertex.y *= this._copy.scaling.y;
  41266. this._vertex.z *= this._copy.scaling.z;
  41267. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41268. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41269. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41270. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41271. }
  41272. particle.position.x = 0;
  41273. particle.position.y = 0;
  41274. particle.position.z = 0;
  41275. particle.rotation.x = 0;
  41276. particle.rotation.y = 0;
  41277. particle.rotation.z = 0;
  41278. particle.rotationQuaternion = null;
  41279. particle.scaling.x = 1;
  41280. particle.scaling.y = 1;
  41281. particle.scaling.z = 1;
  41282. };
  41283. /**
  41284. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41285. */
  41286. SolidParticleSystem.prototype.rebuildMesh = function () {
  41287. for (var p = 0; p < this.particles.length; p++) {
  41288. this._rebuildParticle(this.particles[p]);
  41289. }
  41290. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41291. };
  41292. /**
  41293. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41294. * This method calls `updateParticle()` for each particle of the SPS.
  41295. * For an animated SPS, it is usually called within the render loop.
  41296. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41297. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41298. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41299. */
  41300. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41301. if (start === void 0) { start = 0; }
  41302. if (end === void 0) { end = this.nbParticles - 1; }
  41303. if (update === void 0) { update = true; }
  41304. if (!this._updatable) {
  41305. return;
  41306. }
  41307. // custom beforeUpdate
  41308. this.beforeUpdateParticles(start, end, update);
  41309. this._cam_axisX.x = 1;
  41310. this._cam_axisX.y = 0;
  41311. this._cam_axisX.z = 0;
  41312. this._cam_axisY.x = 0;
  41313. this._cam_axisY.y = 1;
  41314. this._cam_axisY.z = 0;
  41315. this._cam_axisZ.x = 0;
  41316. this._cam_axisZ.y = 0;
  41317. this._cam_axisZ.z = 1;
  41318. // if the particles will always face the camera
  41319. if (this.billboard) {
  41320. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41321. this._yaw = this.mesh.rotation.y;
  41322. this._pitch = this.mesh.rotation.x;
  41323. this._roll = this.mesh.rotation.z;
  41324. this._quaternionRotationYPR();
  41325. this._quaternionToRotationMatrix();
  41326. this._rotMatrix.invertToRef(this._invertMatrix);
  41327. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41328. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41329. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41330. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41331. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41332. this._cam_axisY.normalize();
  41333. this._cam_axisX.normalize();
  41334. this._cam_axisZ.normalize();
  41335. }
  41336. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41337. var idx = 0;
  41338. var index = 0;
  41339. var colidx = 0;
  41340. var colorIndex = 0;
  41341. var uvidx = 0;
  41342. var uvIndex = 0;
  41343. if (this._computeBoundingBox) {
  41344. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41345. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41346. }
  41347. // particle loop
  41348. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41349. for (var p = start; p <= end; p++) {
  41350. this._particle = this.particles[p];
  41351. this._shape = this._particle._model._shape;
  41352. this._shapeUV = this._particle._model._shapeUV;
  41353. // call to custom user function to update the particle properties
  41354. this.updateParticle(this._particle);
  41355. // particle rotation matrix
  41356. if (this.billboard) {
  41357. this._particle.rotation.x = 0.0;
  41358. this._particle.rotation.y = 0.0;
  41359. }
  41360. if (this._computeParticleRotation) {
  41361. if (this._particle.rotationQuaternion) {
  41362. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41363. }
  41364. else {
  41365. this._yaw = this._particle.rotation.y;
  41366. this._pitch = this._particle.rotation.x;
  41367. this._roll = this._particle.rotation.z;
  41368. this._quaternionRotationYPR();
  41369. }
  41370. this._quaternionToRotationMatrix();
  41371. }
  41372. for (var pt = 0; pt < this._shape.length; pt++) {
  41373. idx = index + pt * 3;
  41374. colidx = colorIndex + pt * 4;
  41375. uvidx = uvIndex + pt * 2;
  41376. this._vertex.x = this._shape[pt].x;
  41377. this._vertex.y = this._shape[pt].y;
  41378. this._vertex.z = this._shape[pt].z;
  41379. if (this._computeParticleVertex) {
  41380. this.updateParticleVertex(this._particle, this._vertex, pt);
  41381. }
  41382. // positions
  41383. this._vertex.x *= this._particle.scaling.x;
  41384. this._vertex.y *= this._particle.scaling.y;
  41385. this._vertex.z *= this._particle.scaling.z;
  41386. 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];
  41387. 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;
  41388. 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;
  41389. 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;
  41390. 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;
  41391. 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;
  41392. 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;
  41393. if (this._computeBoundingBox) {
  41394. if (this._positions32[idx] < this._minimum.x) {
  41395. this._minimum.x = this._positions32[idx];
  41396. }
  41397. if (this._positions32[idx] > this._maximum.x) {
  41398. this._maximum.x = this._positions32[idx];
  41399. }
  41400. if (this._positions32[idx + 1] < this._minimum.y) {
  41401. this._minimum.y = this._positions32[idx + 1];
  41402. }
  41403. if (this._positions32[idx + 1] > this._maximum.y) {
  41404. this._maximum.y = this._positions32[idx + 1];
  41405. }
  41406. if (this._positions32[idx + 2] < this._minimum.z) {
  41407. this._minimum.z = this._positions32[idx + 2];
  41408. }
  41409. if (this._positions32[idx + 2] > this._maximum.z) {
  41410. this._maximum.z = this._positions32[idx + 2];
  41411. }
  41412. }
  41413. // normals : if the particles can't be morphed then just rotate the normals
  41414. if (!this._computeParticleVertex && !this.billboard) {
  41415. this._normal.x = this._fixedNormal32[idx];
  41416. this._normal.y = this._fixedNormal32[idx + 1];
  41417. this._normal.z = this._fixedNormal32[idx + 2];
  41418. 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];
  41419. 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;
  41420. 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;
  41421. 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;
  41422. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41423. 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;
  41424. 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;
  41425. }
  41426. if (this._computeParticleColor) {
  41427. this._colors32[colidx] = this._particle.color.r;
  41428. this._colors32[colidx + 1] = this._particle.color.g;
  41429. this._colors32[colidx + 2] = this._particle.color.b;
  41430. this._colors32[colidx + 3] = this._particle.color.a;
  41431. }
  41432. if (this._computeParticleTexture) {
  41433. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41434. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41435. }
  41436. }
  41437. index = idx + 3;
  41438. colorIndex = colidx + 4;
  41439. uvIndex = uvidx + 2;
  41440. }
  41441. if (update) {
  41442. if (this._computeParticleColor) {
  41443. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41444. }
  41445. if (this._computeParticleTexture) {
  41446. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41447. }
  41448. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41449. if (!this.mesh.areNormalsFrozen) {
  41450. if (this._computeParticleVertex || this.billboard) {
  41451. // recompute the normals only if the particles can be morphed, update then the normal reference array
  41452. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  41453. for (var i = 0; i < this._normals32.length; i++) {
  41454. this._fixedNormal32[i] = this._normals32[i];
  41455. }
  41456. }
  41457. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41458. }
  41459. }
  41460. if (this._computeBoundingBox) {
  41461. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41462. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41463. }
  41464. this.afterUpdateParticles(start, end, update);
  41465. };
  41466. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41467. this._halfroll = this._roll * 0.5;
  41468. this._halfpitch = this._pitch * 0.5;
  41469. this._halfyaw = this._yaw * 0.5;
  41470. this._sinRoll = Math.sin(this._halfroll);
  41471. this._cosRoll = Math.cos(this._halfroll);
  41472. this._sinPitch = Math.sin(this._halfpitch);
  41473. this._cosPitch = Math.cos(this._halfpitch);
  41474. this._sinYaw = Math.sin(this._halfyaw);
  41475. this._cosYaw = Math.cos(this._halfyaw);
  41476. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41477. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41478. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41479. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41480. };
  41481. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41482. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41483. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41484. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41485. this._rotMatrix.m[3] = 0;
  41486. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41487. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41488. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41489. this._rotMatrix.m[7] = 0;
  41490. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41491. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41492. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41493. this._rotMatrix.m[11] = 0;
  41494. this._rotMatrix.m[12] = 0;
  41495. this._rotMatrix.m[13] = 0;
  41496. this._rotMatrix.m[14] = 0;
  41497. this._rotMatrix.m[15] = 1.0;
  41498. };
  41499. /**
  41500. * Disposes the SPS
  41501. */
  41502. SolidParticleSystem.prototype.dispose = function () {
  41503. this.mesh.dispose();
  41504. this.vars = null;
  41505. // drop references to internal big arrays for the GC
  41506. this._positions = null;
  41507. this._indices = null;
  41508. this._normals = null;
  41509. this._uvs = null;
  41510. this._colors = null;
  41511. this._positions32 = null;
  41512. this._normals32 = null;
  41513. this._fixedNormal32 = null;
  41514. this._uvs32 = null;
  41515. this._colors32 = null;
  41516. this.pickedParticles = null;
  41517. };
  41518. /**
  41519. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41520. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41521. */
  41522. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41523. if (!this._isVisibilityBoxLocked) {
  41524. this.mesh.refreshBoundingInfo();
  41525. }
  41526. };
  41527. /**
  41528. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41529. * @param size the size (float) of the visibility box
  41530. * note : this doesn't lock the SPS mesh bounding box.
  41531. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41532. */
  41533. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41534. var vis = size / 2;
  41535. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41536. };
  41537. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41538. // getter and setter
  41539. get: function () {
  41540. return this._alwaysVisible;
  41541. },
  41542. /**
  41543. * Sets the SPS as always visible or not
  41544. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41545. */
  41546. set: function (val) {
  41547. this._alwaysVisible = val;
  41548. this.mesh.alwaysSelectAsActiveMesh = val;
  41549. },
  41550. enumerable: true,
  41551. configurable: true
  41552. });
  41553. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41554. get: function () {
  41555. return this._isVisibilityBoxLocked;
  41556. },
  41557. /**
  41558. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41559. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41560. */
  41561. set: function (val) {
  41562. this._isVisibilityBoxLocked = val;
  41563. this.mesh.getBoundingInfo().isLocked = val;
  41564. },
  41565. enumerable: true,
  41566. configurable: true
  41567. });
  41568. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41569. // getters
  41570. get: function () {
  41571. return this._computeParticleRotation;
  41572. },
  41573. // Optimizer setters
  41574. /**
  41575. * Tells to `setParticles()` to compute the particle rotations or not.
  41576. * Default value : true. The SPS is faster when it's set to false.
  41577. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  41578. */
  41579. set: function (val) {
  41580. this._computeParticleRotation = val;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  41586. get: function () {
  41587. return this._computeParticleColor;
  41588. },
  41589. /**
  41590. * Tells to `setParticles()` to compute the particle colors or not.
  41591. * Default value : true. The SPS is faster when it's set to false.
  41592. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  41593. */
  41594. set: function (val) {
  41595. this._computeParticleColor = val;
  41596. },
  41597. enumerable: true,
  41598. configurable: true
  41599. });
  41600. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  41601. get: function () {
  41602. return this._computeParticleTexture;
  41603. },
  41604. /**
  41605. * Tells to `setParticles()` to compute the particle textures or not.
  41606. * Default value : true. The SPS is faster when it's set to false.
  41607. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  41608. */
  41609. set: function (val) {
  41610. this._computeParticleTexture = val;
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  41616. get: function () {
  41617. return this._computeParticleVertex;
  41618. },
  41619. /**
  41620. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  41621. * Default value : false. The SPS is faster when it's set to false.
  41622. * Note : the particle custom vertex positions aren't stored values.
  41623. */
  41624. set: function (val) {
  41625. this._computeParticleVertex = val;
  41626. },
  41627. enumerable: true,
  41628. configurable: true
  41629. });
  41630. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  41631. get: function () {
  41632. return this._computeBoundingBox;
  41633. },
  41634. /**
  41635. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  41636. */
  41637. set: function (val) {
  41638. this._computeBoundingBox = val;
  41639. },
  41640. enumerable: true,
  41641. configurable: true
  41642. });
  41643. // =======================================================================
  41644. // Particle behavior logic
  41645. // these following methods may be overwritten by the user to fit his needs
  41646. /**
  41647. * This function does nothing. It may be overwritten to set all the particle first values.
  41648. * The SPS doesn't call this function, you may have to call it by your own.
  41649. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  41650. */
  41651. SolidParticleSystem.prototype.initParticles = function () {
  41652. };
  41653. /**
  41654. * This function does nothing. It may be overwritten to recycle a particle.
  41655. * The SPS doesn't call this function, you may have to call it by your own.
  41656. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  41657. */
  41658. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41659. return particle;
  41660. };
  41661. /**
  41662. * Updates a particle : this function should be overwritten by the user.
  41663. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41664. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  41665. * ex : just set a particle position or velocity and recycle conditions
  41666. */
  41667. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41668. return particle;
  41669. };
  41670. /**
  41671. * Updates a vertex of a particle : it can be overwritten by the user.
  41672. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41673. * @param particle the current particle
  41674. * @param vertex the current index of the current particle
  41675. * @param pt the index of the current vertex in the particle shape
  41676. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  41677. * ex : just set a vertex particle position
  41678. */
  41679. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41680. return vertex;
  41681. };
  41682. /**
  41683. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41684. * This does nothing and may be overwritten by the user.
  41685. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41686. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41687. * @param update the boolean update value actually passed to setParticles()
  41688. */
  41689. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41690. };
  41691. /**
  41692. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41693. * This will be passed three parameters.
  41694. * This does nothing and may be overwritten by the user.
  41695. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41696. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41697. * @param update the boolean update value actually passed to setParticles()
  41698. */
  41699. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41700. };
  41701. return SolidParticleSystem;
  41702. })();
  41703. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41704. })(BABYLON || (BABYLON = {}));
  41705. var BABYLON;
  41706. (function (BABYLON) {
  41707. var Internals;
  41708. (function (Internals) {
  41709. var FileFaceOrientation = (function () {
  41710. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  41711. this.name = name;
  41712. this.worldAxisForNormal = worldAxisForNormal;
  41713. this.worldAxisForFileX = worldAxisForFileX;
  41714. this.worldAxisForFileY = worldAxisForFileY;
  41715. }
  41716. return FileFaceOrientation;
  41717. })();
  41718. ;
  41719. /**
  41720. * Helper class dealing with the extraction of spherical polynomial dataArray
  41721. * from a cube map.
  41722. */
  41723. var CubeMapToSphericalPolynomialTools = (function () {
  41724. function CubeMapToSphericalPolynomialTools() {
  41725. }
  41726. /**
  41727. * Converts a cubemap to the according Spherical Polynomial data.
  41728. * This extracts the first 3 orders only as they are the only one used in the lighting.
  41729. *
  41730. * @param cubeInfo The Cube map to extract the information from.
  41731. * @return The Spherical Polynomial data.
  41732. */
  41733. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  41734. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  41735. var totalSolidAngle = 0.0;
  41736. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  41737. var du = 2.0 / cubeInfo.size;
  41738. var dv = du;
  41739. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  41740. var minUV = du * 0.5 - 1.0;
  41741. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  41742. var fileFace = this.FileFaces[faceIndex];
  41743. var dataArray = cubeInfo[fileFace.name];
  41744. var v = minUV;
  41745. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  41746. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  41747. // Because SP is still linear, so summation is fine in that basis.
  41748. for (var y = 0; y < cubeInfo.size; y++) {
  41749. var u = minUV;
  41750. for (var x = 0; x < cubeInfo.size; x++) {
  41751. // World direction (not normalised)
  41752. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  41753. worldDirection.normalize();
  41754. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  41755. if (1) {
  41756. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  41757. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  41758. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  41759. var color = new BABYLON.Color3(r, g, b);
  41760. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  41761. }
  41762. else {
  41763. if (faceIndex == 0) {
  41764. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  41765. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  41766. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  41767. }
  41768. else if (faceIndex == 1) {
  41769. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  41770. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  41771. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  41772. }
  41773. else if (faceIndex == 2) {
  41774. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  41775. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  41776. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  41777. }
  41778. else if (faceIndex == 3) {
  41779. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  41780. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  41781. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  41782. }
  41783. else if (faceIndex == 4) {
  41784. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  41785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  41786. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  41787. }
  41788. else if (faceIndex == 5) {
  41789. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  41790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  41791. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  41792. }
  41793. 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]);
  41794. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  41795. }
  41796. totalSolidAngle += deltaSolidAngle;
  41797. u += du;
  41798. }
  41799. v += dv;
  41800. }
  41801. }
  41802. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  41803. var correction = correctSolidAngle / totalSolidAngle;
  41804. sphericalHarmonics.scale(correction);
  41805. // Additionally scale by pi -- audit needed
  41806. sphericalHarmonics.scale(1.0 / Math.PI);
  41807. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  41808. };
  41809. CubeMapToSphericalPolynomialTools.FileFaces = [
  41810. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  41811. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  41812. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  41813. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  41814. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  41815. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  41816. ];
  41817. return CubeMapToSphericalPolynomialTools;
  41818. })();
  41819. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  41820. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41821. })(BABYLON || (BABYLON = {}));
  41822. var BABYLON;
  41823. (function (BABYLON) {
  41824. var Internals;
  41825. (function (Internals) {
  41826. /**
  41827. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  41828. */
  41829. var PanoramaToCubeMapTools = (function () {
  41830. function PanoramaToCubeMapTools() {
  41831. }
  41832. /**
  41833. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  41834. *
  41835. * @param float32Array The source data.
  41836. * @param inputWidth The width of the input panorama.
  41837. * @param inputhHeight The height of the input panorama.
  41838. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  41839. * @return The cubemap data
  41840. */
  41841. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  41842. if (!float32Array) {
  41843. throw "ConvertPanoramaToCubemap: input cannot be null";
  41844. }
  41845. if (float32Array.length != inputWidth * inputHeight * 3) {
  41846. throw "ConvertPanoramaToCubemap: input size is wrong";
  41847. }
  41848. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  41849. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  41850. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  41851. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  41852. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  41853. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  41854. return {
  41855. front: textureFront,
  41856. back: textureBack,
  41857. left: textureLeft,
  41858. right: textureRight,
  41859. up: textureUp,
  41860. down: textureDown,
  41861. size: size
  41862. };
  41863. };
  41864. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  41865. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  41866. var textureArray = new Float32Array(buffer);
  41867. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  41868. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  41869. var dy = 1 / texSize;
  41870. var fy = 0;
  41871. for (var y = 0; y < texSize; y++) {
  41872. var xv1 = faceData[0];
  41873. var xv2 = faceData[2];
  41874. for (var x = 0; x < texSize; x++) {
  41875. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  41876. v.normalize();
  41877. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  41878. // 3 channels per pixels
  41879. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  41880. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  41881. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  41882. xv1 = xv1.add(rotDX1);
  41883. xv2 = xv2.add(rotDX2);
  41884. }
  41885. fy += dy;
  41886. }
  41887. return textureArray;
  41888. };
  41889. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  41890. var theta = Math.atan2(vDir.z, vDir.x);
  41891. var phi = Math.acos(vDir.y);
  41892. while (theta < -Math.PI)
  41893. theta += 2 * Math.PI;
  41894. while (theta > Math.PI)
  41895. theta -= 2 * Math.PI;
  41896. var dx = theta / Math.PI;
  41897. var dy = phi / Math.PI;
  41898. // recenter.
  41899. dx = dx * 0.5 + 0.5;
  41900. var px = Math.round(dx * inputWidth);
  41901. if (px < 0)
  41902. px = 0;
  41903. else if (px >= inputWidth)
  41904. px = inputWidth - 1;
  41905. var py = Math.round(dy * inputHeight);
  41906. if (py < 0)
  41907. py = 0;
  41908. else if (py >= inputHeight)
  41909. py = inputHeight - 1;
  41910. var inputY = (inputHeight - py - 1);
  41911. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  41912. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  41913. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  41914. return {
  41915. r: r,
  41916. g: g,
  41917. b: b
  41918. };
  41919. };
  41920. PanoramaToCubeMapTools.FACE_FRONT = [
  41921. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41922. new BABYLON.Vector3(1.0, -1.0, -1.0),
  41923. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  41924. new BABYLON.Vector3(1.0, 1.0, -1.0)
  41925. ];
  41926. PanoramaToCubeMapTools.FACE_BACK = [
  41927. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41928. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41929. new BABYLON.Vector3(1.0, 1.0, 1.0),
  41930. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  41931. ];
  41932. PanoramaToCubeMapTools.FACE_RIGHT = [
  41933. new BABYLON.Vector3(1.0, -1.0, -1.0),
  41934. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41935. new BABYLON.Vector3(1.0, 1.0, -1.0),
  41936. new BABYLON.Vector3(1.0, 1.0, 1.0)
  41937. ];
  41938. PanoramaToCubeMapTools.FACE_LEFT = [
  41939. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41940. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41941. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  41942. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  41943. ];
  41944. PanoramaToCubeMapTools.FACE_DOWN = [
  41945. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  41946. new BABYLON.Vector3(1.0, 1.0, -1.0),
  41947. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  41948. new BABYLON.Vector3(1.0, 1.0, 1.0)
  41949. ];
  41950. PanoramaToCubeMapTools.FACE_UP = [
  41951. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  41952. new BABYLON.Vector3(1.0, -1.0, 1.0),
  41953. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  41954. new BABYLON.Vector3(1.0, -1.0, -1.0)
  41955. ];
  41956. return PanoramaToCubeMapTools;
  41957. })();
  41958. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  41959. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41960. })(BABYLON || (BABYLON = {}));
  41961. var BABYLON;
  41962. (function (BABYLON) {
  41963. var Internals;
  41964. (function (Internals) {
  41965. ;
  41966. /**
  41967. * This groups tools to convert HDR texture to native colors array.
  41968. */
  41969. var HDRTools = (function () {
  41970. function HDRTools() {
  41971. }
  41972. HDRTools.Ldexp = function (mantissa, exponent) {
  41973. if (exponent > 1023) {
  41974. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  41975. }
  41976. if (exponent < -1074) {
  41977. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  41978. }
  41979. return mantissa * Math.pow(2, exponent);
  41980. };
  41981. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  41982. if (exponent > 0) {
  41983. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  41984. float32array[index + 0] = red * exponent;
  41985. float32array[index + 1] = green * exponent;
  41986. float32array[index + 2] = blue * exponent;
  41987. }
  41988. else {
  41989. float32array[index + 0] = 0;
  41990. float32array[index + 1] = 0;
  41991. float32array[index + 2] = 0;
  41992. }
  41993. };
  41994. HDRTools.readStringLine = function (uint8array, startIndex) {
  41995. var line = "";
  41996. var character = "";
  41997. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  41998. character = String.fromCharCode(uint8array[i]);
  41999. if (character == "\n") {
  42000. break;
  42001. }
  42002. line += character;
  42003. }
  42004. return line;
  42005. };
  42006. /**
  42007. * Reads header information from an RGBE texture stored in a native array.
  42008. * More information on this format are available here:
  42009. * https://en.wikipedia.org/wiki/RGBE_image_format
  42010. *
  42011. * @param uint8array The binary file stored in native array.
  42012. * @return The header information.
  42013. */
  42014. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42015. var height = 0;
  42016. var width = 0;
  42017. var line = this.readStringLine(uint8array, 0);
  42018. if (line[0] != '#' || line[1] != '?') {
  42019. throw "Bad HDR Format.";
  42020. }
  42021. var endOfHeader = false;
  42022. var findFormat = false;
  42023. var lineIndex = 0;
  42024. do {
  42025. lineIndex += (line.length + 1);
  42026. line = this.readStringLine(uint8array, lineIndex);
  42027. if (line == "FORMAT=32-bit_rle_rgbe") {
  42028. findFormat = true;
  42029. }
  42030. else if (line.length == 0) {
  42031. endOfHeader = true;
  42032. }
  42033. } while (!endOfHeader);
  42034. if (!findFormat) {
  42035. throw "HDR Bad header format, unsupported FORMAT";
  42036. }
  42037. lineIndex += (line.length + 1);
  42038. line = this.readStringLine(uint8array, lineIndex);
  42039. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42040. var match = sizeRegexp.exec(line);
  42041. // TODO. Support +Y and -X if needed.
  42042. if (match.length < 3) {
  42043. throw "HDR Bad header format, no size";
  42044. }
  42045. width = parseInt(match[2]);
  42046. height = parseInt(match[1]);
  42047. if (width < 8 || width > 0x7fff) {
  42048. throw "HDR Bad header format, unsupported size";
  42049. }
  42050. lineIndex += (line.length + 1);
  42051. return {
  42052. height: height,
  42053. width: width,
  42054. dataPosition: lineIndex
  42055. };
  42056. };
  42057. /**
  42058. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42059. * This RGBE texture needs to store the information as a panorama.
  42060. *
  42061. * More information on this format are available here:
  42062. * https://en.wikipedia.org/wiki/RGBE_image_format
  42063. *
  42064. * @param buffer The binary file stored in an array buffer.
  42065. * @param size The expected size of the extracted cubemap.
  42066. * @return The Cube Map information.
  42067. */
  42068. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42069. var uint8array = new Uint8Array(buffer);
  42070. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42071. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42072. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42073. return cubeMapData;
  42074. };
  42075. /**
  42076. * Returns the pixels data extracted from an RGBE texture.
  42077. * This pixels will be stored left to right up to down in the R G B order in one array.
  42078. *
  42079. * More information on this format are available here:
  42080. * https://en.wikipedia.org/wiki/RGBE_image_format
  42081. *
  42082. * @param uint8array The binary file stored in an array buffer.
  42083. * @param hdrInfo The header information of the file.
  42084. * @return The pixels data in RGB right to left up to down order.
  42085. */
  42086. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42087. // Keep for multi format supports.
  42088. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42089. };
  42090. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42091. var num_scanlines = hdrInfo.height;
  42092. var scanline_width = hdrInfo.width;
  42093. var a, b, c, d, count;
  42094. var dataIndex = hdrInfo.dataPosition;
  42095. var index = 0, endIndex = 0, i = 0;
  42096. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42097. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42098. // 3 channels of 4 bytes per pixel in float.
  42099. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42100. var resultArray = new Float32Array(resultBuffer);
  42101. // read in each successive scanline
  42102. while (num_scanlines > 0) {
  42103. a = uint8array[dataIndex++];
  42104. b = uint8array[dataIndex++];
  42105. c = uint8array[dataIndex++];
  42106. d = uint8array[dataIndex++];
  42107. if (a != 2 || b != 2 || (c & 0x80)) {
  42108. // this file is not run length encoded
  42109. throw "HDR Bad header format, not RLE";
  42110. }
  42111. if (((c << 8) | d) != scanline_width) {
  42112. throw "HDR Bad header format, wrong scan line width";
  42113. }
  42114. index = 0;
  42115. // read each of the four channels for the scanline into the buffer
  42116. for (i = 0; i < 4; i++) {
  42117. endIndex = (i + 1) * scanline_width;
  42118. while (index < endIndex) {
  42119. a = uint8array[dataIndex++];
  42120. b = uint8array[dataIndex++];
  42121. if (a > 128) {
  42122. // a run of the same value
  42123. count = a - 128;
  42124. if ((count == 0) || (count > endIndex - index)) {
  42125. throw "HDR Bad Format, bad scanline data (run)";
  42126. }
  42127. while (count-- > 0) {
  42128. scanLineArray[index++] = b;
  42129. }
  42130. }
  42131. else {
  42132. // a non-run
  42133. count = a;
  42134. if ((count == 0) || (count > endIndex - index)) {
  42135. throw "HDR Bad Format, bad scanline data (non-run)";
  42136. }
  42137. scanLineArray[index++] = b;
  42138. if (--count > 0) {
  42139. for (var j = 0; j < count; j++) {
  42140. scanLineArray[index++] = uint8array[dataIndex++];
  42141. }
  42142. }
  42143. }
  42144. }
  42145. }
  42146. // now convert data from buffer into floats
  42147. for (i = 0; i < scanline_width; i++) {
  42148. a = scanLineArray[i];
  42149. b = scanLineArray[i + scanline_width];
  42150. c = scanLineArray[i + 2 * scanline_width];
  42151. d = scanLineArray[i + 3 * scanline_width];
  42152. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42153. }
  42154. num_scanlines--;
  42155. }
  42156. return resultArray;
  42157. };
  42158. return HDRTools;
  42159. })();
  42160. Internals.HDRTools = HDRTools;
  42161. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42162. })(BABYLON || (BABYLON = {}));
  42163. //_______________________________________________________________
  42164. // Extracted from CubeMapGen:
  42165. // https://code.google.com/archive/p/cubemapgen/
  42166. //
  42167. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42168. //_______________________________________________________________
  42169. var BABYLON;
  42170. (function (BABYLON) {
  42171. var Internals;
  42172. (function (Internals) {
  42173. /**
  42174. * The bounding box information used during the conversion process.
  42175. */
  42176. var CMGBoundinBox = (function () {
  42177. function CMGBoundinBox() {
  42178. this.min = new BABYLON.Vector3(0, 0, 0);
  42179. this.max = new BABYLON.Vector3(0, 0, 0);
  42180. this.clear();
  42181. }
  42182. CMGBoundinBox.prototype.clear = function () {
  42183. this.min.x = CMGBoundinBox.MAX;
  42184. this.min.y = CMGBoundinBox.MAX;
  42185. this.min.z = CMGBoundinBox.MAX;
  42186. this.max.x = CMGBoundinBox.MIN;
  42187. this.max.y = CMGBoundinBox.MIN;
  42188. this.max.z = CMGBoundinBox.MIN;
  42189. };
  42190. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42191. this.min.x = Math.min(this.min.x, x);
  42192. this.min.y = Math.min(this.min.y, y);
  42193. this.min.z = Math.min(this.min.z, z);
  42194. this.max.x = Math.max(this.max.x, x);
  42195. this.max.y = Math.max(this.max.y, y);
  42196. this.max.z = Math.max(this.max.z, z);
  42197. };
  42198. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42199. this.min.x = Math.max(this.min.x, x);
  42200. this.min.y = Math.max(this.min.y, y);
  42201. this.min.z = Math.max(this.min.z, z);
  42202. };
  42203. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42204. this.max.x = Math.min(this.max.x, x);
  42205. this.max.y = Math.min(this.max.y, y);
  42206. this.max.z = Math.min(this.max.z, z);
  42207. };
  42208. CMGBoundinBox.prototype.empty = function () {
  42209. if ((this.min.x > this.max.y) ||
  42210. (this.min.y > this.max.y) ||
  42211. (this.min.z > this.max.y)) {
  42212. return true;
  42213. }
  42214. else {
  42215. return false;
  42216. }
  42217. };
  42218. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42219. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42220. return CMGBoundinBox;
  42221. })();
  42222. /**
  42223. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42224. * required by the glossinees of a material.
  42225. *
  42226. * This only supports the cosine drop power as well as Warp fixup generation method.
  42227. *
  42228. * This is using the process from CubeMapGen described here:
  42229. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42230. */
  42231. var PMREMGenerator = (function () {
  42232. /**
  42233. * Constructor of the generator.
  42234. *
  42235. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42236. * @param inputSize The size of the cubemap faces
  42237. * @param outputSize The size of the output cubemap faces
  42238. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42239. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42240. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42241. * @param specularPower The max specular level of the desired cubemap
  42242. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42243. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42244. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42245. */
  42246. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42247. this.input = input;
  42248. this.inputSize = inputSize;
  42249. this.outputSize = outputSize;
  42250. this.maxNumMipLevels = maxNumMipLevels;
  42251. this.numChannels = numChannels;
  42252. this.isFloat = isFloat;
  42253. this.specularPower = specularPower;
  42254. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42255. this.excludeBase = excludeBase;
  42256. this.fixup = fixup;
  42257. this._outputSurface = [];
  42258. this._numMipLevels = 0;
  42259. }
  42260. /**
  42261. * Launches the filter process and return the result.
  42262. *
  42263. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42264. */
  42265. PMREMGenerator.prototype.filterCubeMap = function () {
  42266. // Init cubemap processor
  42267. this.init();
  42268. // Filters the cubemap
  42269. this.filterCubeMapMipChain();
  42270. // Returns the filtered mips.
  42271. return this._outputSurface;
  42272. };
  42273. PMREMGenerator.prototype.init = function () {
  42274. var i;
  42275. var j;
  42276. var mipLevelSize;
  42277. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42278. if (this.maxNumMipLevels == 0) {
  42279. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42280. }
  42281. //first miplevel size
  42282. mipLevelSize = this.outputSize;
  42283. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42284. for (j = 0; j < this.maxNumMipLevels; j++) {
  42285. this._outputSurface.length++;
  42286. this._outputSurface[j] = [];
  42287. //Iterate over faces for output images
  42288. for (i = 0; i < 6; i++) {
  42289. this._outputSurface[j].length++;
  42290. // Initializes a new array for the output.
  42291. if (this.isFloat) {
  42292. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42293. }
  42294. else {
  42295. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42296. }
  42297. }
  42298. //next mip level is half size
  42299. mipLevelSize >>= 1;
  42300. this._numMipLevels++;
  42301. //terminate if mip chain becomes too small
  42302. if (mipLevelSize == 0) {
  42303. this.maxNumMipLevels = j;
  42304. return;
  42305. }
  42306. }
  42307. };
  42308. //--------------------------------------------------------------------------------------
  42309. //Cube map filtering and mip chain generation.
  42310. // the cube map filtereing is specified using a number of parameters:
  42311. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42312. // indicates the region of the hemisphere to filter over for each tap.
  42313. //
  42314. // Note that the top mip level is also a filtered version of the original input images
  42315. // as well in order to create mip chains for diffuse environment illumination.
  42316. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42317. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42318. //
  42319. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42320. // is a_InitialMipAngle
  42321. //
  42322. // The angle for the subsequent levels of the mip chain are specified by their parents
  42323. // filtering angle and a per-level scale and bias
  42324. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42325. //
  42326. //--------------------------------------------------------------------------------------
  42327. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42328. // First, take count of the lighting model to modify SpecularPower
  42329. // 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;
  42330. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42331. //Cone angle start (for generating subsequent mip levels)
  42332. var currentSpecularPower = this.specularPower;
  42333. //Build filter lookup tables based on the source miplevel size
  42334. this.precomputeFilterLookupTables(this.inputSize);
  42335. // Note that we need to filter the first level before generating mipmap
  42336. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42337. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42338. // TODO : Write a function to copy and scale the base mipmap in output
  42339. // I am just lazy here and just put a high specular power value, and do some if.
  42340. if (this.excludeBase && (levelIndex == 0)) {
  42341. // 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).
  42342. currentSpecularPower = 100000.0;
  42343. }
  42344. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42345. var srcCubeImage = this.input;
  42346. var dstCubeImage = this._outputSurface[levelIndex];
  42347. var dstSize = this.outputSize >> levelIndex;
  42348. // Compute required angle.
  42349. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42350. // filter cube surfaces
  42351. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42352. // fix seams
  42353. if (this.fixup) {
  42354. this.fixupCubeEdges(dstCubeImage, dstSize);
  42355. }
  42356. // Decrease the specular power to generate the mipmap chain
  42357. // TODO : Use another method for Exclude (see first comment at start of the function
  42358. if (this.excludeBase && (levelIndex == 0)) {
  42359. currentSpecularPower = this.specularPower;
  42360. }
  42361. currentSpecularPower *= this.cosinePowerDropPerMip;
  42362. }
  42363. };
  42364. //--------------------------------------------------------------------------------------
  42365. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42366. // It allow to optimize the texel to access base on the specular power.
  42367. //--------------------------------------------------------------------------------------
  42368. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42369. // We want to find the alpha such that:
  42370. // cos(alpha)^cosinePower = epsilon
  42371. // That's: acos(epsilon^(1/cosinePower))
  42372. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42373. var angle = 180.0;
  42374. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42375. angle *= 180.0 / Math.PI; // Convert to degree
  42376. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42377. return angle;
  42378. };
  42379. //--------------------------------------------------------------------------------------
  42380. //Builds the following lookup tables prior to filtering:
  42381. // -normalizer cube map
  42382. // -tap weight lookup table
  42383. //
  42384. //--------------------------------------------------------------------------------------
  42385. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42386. var srcTexelAngle;
  42387. var iCubeFace;
  42388. //clear pre-existing normalizer cube map
  42389. this._normCubeMap = [];
  42390. //Normalized vectors per cubeface and per-texel solid angle
  42391. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42392. };
  42393. //--------------------------------------------------------------------------------------
  42394. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42395. //
  42396. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42397. //
  42398. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42399. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42400. // below
  42401. //--------------------------------------------------------------------------------------
  42402. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42403. var iCubeFace;
  42404. var u;
  42405. var v;
  42406. //iterate over cube faces
  42407. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42408. //First three channels for norm cube, and last channel for solid angle
  42409. this._normCubeMap.push(new Float32Array(size * size * 4));
  42410. //fast texture walk, build normalizer cube map
  42411. var facesData = this.input[iCubeFace];
  42412. for (v = 0; v < size; v++) {
  42413. for (u = 0; u < size; u++) {
  42414. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  42415. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  42416. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  42417. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  42418. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  42419. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  42420. }
  42421. }
  42422. }
  42423. };
  42424. //--------------------------------------------------------------------------------------
  42425. // Convert cubemap face texel coordinates and face idx to 3D vector
  42426. // note the U and V coords are integer coords and range from 0 to size-1
  42427. // this routine can be used to generate a normalizer cube map
  42428. //--------------------------------------------------------------------------------------
  42429. // SL BEGIN
  42430. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  42431. var nvcU;
  42432. var nvcV;
  42433. var tempVec;
  42434. // Change from original AMD code
  42435. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42436. // + 0.5f is for texel center addressing
  42437. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  42438. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  42439. // warp fixup
  42440. if (fixup && size > 1) {
  42441. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  42442. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  42443. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  42444. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  42445. }
  42446. // Get current vector
  42447. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  42448. // U contribution
  42449. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42450. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  42451. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  42452. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  42453. // V contribution and Sum
  42454. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42455. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  42456. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  42457. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  42458. //add face axis
  42459. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  42460. PMREMGenerator._vectorTemp.x += faceAxis[0];
  42461. PMREMGenerator._vectorTemp.y += faceAxis[1];
  42462. PMREMGenerator._vectorTemp.z += faceAxis[2];
  42463. //normalize vector
  42464. PMREMGenerator._vectorTemp.normalize();
  42465. return PMREMGenerator._vectorTemp;
  42466. };
  42467. //--------------------------------------------------------------------------------------
  42468. // Convert 3D vector to cubemap face texel coordinates and face idx
  42469. // note the U and V coords are integer coords and range from 0 to size-1
  42470. // this routine can be used to generate a normalizer cube map
  42471. //
  42472. // returns face IDX and texel coords
  42473. //--------------------------------------------------------------------------------------
  42474. // SL BEGIN
  42475. /*
  42476. Mapping Texture Coordinates to Cube Map Faces
  42477. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  42478. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  42479. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  42480. map arrangement in Pixar's RenderMan package.
  42481. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  42482. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  42483. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  42484. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  42485. the major axis direction). The target column in the table below explains how the major axis direction
  42486. maps to the 2D image of a particular cube map target.
  42487. major axis
  42488. direction target sc tc ma
  42489. ---------- --------------------------------- --- --- ---
  42490. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  42491. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  42492. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  42493. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  42494. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  42495. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  42496. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  42497. an updated (s,t) is calculated as follows
  42498. s = ( sc/|ma| + 1 ) / 2
  42499. t = ( tc/|ma| + 1 ) / 2
  42500. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  42501. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  42502. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  42503. */
  42504. // Note this method return U and V in range from 0 to size-1
  42505. // SL END
  42506. // Store the information in vector3 for convenience (faceindex, u, v)
  42507. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  42508. var maxCoord;
  42509. var faceIdx;
  42510. //absolute value 3
  42511. var absX = Math.abs(x);
  42512. var absY = Math.abs(y);
  42513. var absZ = Math.abs(z);
  42514. if (absX >= absY && absX >= absZ) {
  42515. maxCoord = absX;
  42516. if (x >= 0) {
  42517. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  42518. }
  42519. else {
  42520. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  42521. }
  42522. }
  42523. else if (absY >= absX && absY >= absZ) {
  42524. maxCoord = absY;
  42525. if (y >= 0) {
  42526. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  42527. }
  42528. else {
  42529. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  42530. }
  42531. }
  42532. else {
  42533. maxCoord = absZ;
  42534. if (z >= 0) {
  42535. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  42536. }
  42537. else {
  42538. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  42539. }
  42540. }
  42541. //divide through by max coord so face vector lies on cube face
  42542. var scale = 1 / maxCoord;
  42543. x *= scale;
  42544. y *= scale;
  42545. z *= scale;
  42546. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42547. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  42548. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42549. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  42550. // Modify original AMD code to return value from 0 to Size - 1
  42551. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  42552. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  42553. PMREMGenerator._vectorTemp.x = faceIdx;
  42554. PMREMGenerator._vectorTemp.y = u;
  42555. PMREMGenerator._vectorTemp.z = v;
  42556. return PMREMGenerator._vectorTemp;
  42557. };
  42558. //--------------------------------------------------------------------------------------
  42559. //Original code from Ignacio CastaÒo
  42560. // This formula is from Manne ÷hrstrˆm's thesis.
  42561. // Take two coordiantes in the range [-1, 1] that define a portion of a
  42562. // cube face and return the area of the projection of that portion on the
  42563. // surface of the sphere.
  42564. //--------------------------------------------------------------------------------------
  42565. PMREMGenerator.prototype.areaElement = function (x, y) {
  42566. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  42567. };
  42568. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  42569. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42570. // (+ 0.5f is for texel center addressing)
  42571. u = (2.0 * (u + 0.5) / size) - 1.0;
  42572. v = (2.0 * (v + 0.5) / size) - 1.0;
  42573. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  42574. var invResolution = 1.0 / size;
  42575. // U and V are the -1..1 texture coordinate on the current face.
  42576. // Get projected area for this texel
  42577. var x0 = u - invResolution;
  42578. var y0 = v - invResolution;
  42579. var x1 = u + invResolution;
  42580. var y1 = v + invResolution;
  42581. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  42582. return solidAngle;
  42583. };
  42584. //--------------------------------------------------------------------------------------
  42585. //The key to the speed of these filtering routines is to quickly define a per-face
  42586. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  42587. // Later these pixels are selectively processed based on their dot products to see if
  42588. // they reside within the filtering cone.
  42589. //
  42590. //This is done by computing the smallest per-texel angle to get a conservative estimate
  42591. // of the number of texels needed to be covered in width and height order to filter the
  42592. // region. the bounding box for the center taps face is defined first, and if the
  42593. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  42594. // defined next
  42595. //--------------------------------------------------------------------------------------
  42596. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  42597. // note that pixels within these regions may be rejected
  42598. // based on the anlge
  42599. var iCubeFace;
  42600. var u;
  42601. var v;
  42602. // bounding box per face to specify region to process
  42603. var filterExtents = [];
  42604. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42605. filterExtents.push(new CMGBoundinBox());
  42606. }
  42607. // min angle a src texel can cover (in degrees)
  42608. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  42609. // angle about center tap to define filter cone
  42610. // filter angle is 1/2 the cone angle
  42611. var filterAngle = filterConeAngle / 2.0;
  42612. //ensure filter angle is larger than a texel
  42613. if (filterAngle < srcTexelAngle) {
  42614. filterAngle = srcTexelAngle;
  42615. }
  42616. //ensure filter cone is always smaller than the hemisphere
  42617. if (filterAngle > 90.0) {
  42618. filterAngle = 90.0;
  42619. }
  42620. // the maximum number of texels in 1D the filter cone angle will cover
  42621. // used to determine bounding box size for filter extents
  42622. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  42623. // ensure conservative region always covers at least one texel
  42624. if (filterSize < 1) {
  42625. filterSize = 1;
  42626. }
  42627. // dotProdThresh threshold based on cone angle to determine whether or not taps
  42628. // reside within the cone angle
  42629. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  42630. // process required faces
  42631. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42632. //iterate over dst cube map face texel
  42633. for (v = 0; v < dstSize; v++) {
  42634. for (u = 0; u < dstSize; u++) {
  42635. //get center tap direction
  42636. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  42637. //clear old per-face filter extents
  42638. this.clearFilterExtents(filterExtents);
  42639. //define per-face filter extents
  42640. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  42641. //perform filtering of src faces using filter extents
  42642. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  42643. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  42644. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  42645. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  42646. }
  42647. }
  42648. }
  42649. };
  42650. //--------------------------------------------------------------------------------------
  42651. //Clear filter extents for the 6 cube map faces
  42652. //--------------------------------------------------------------------------------------
  42653. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  42654. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  42655. filterExtents[iCubeFaces].clear();
  42656. }
  42657. };
  42658. //--------------------------------------------------------------------------------------
  42659. //Define per-face bounding box filter extents
  42660. //
  42661. // These define conservative texel regions in each of the faces the filter can possibly
  42662. // process. When the pixels in the regions are actually processed, the dot product
  42663. // between the tap vector and the center tap vector is used to determine the weight of
  42664. // the tap and whether or not the tap is within the cone.
  42665. //
  42666. //--------------------------------------------------------------------------------------
  42667. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  42668. //neighboring face and bleed over amount, and width of BBOX for
  42669. // left, right, top, and bottom edges of this face
  42670. var bleedOverAmount = [0, 0, 0, 0];
  42671. var bleedOverBBoxMin = [0, 0, 0, 0];
  42672. var bleedOverBBoxMax = [0, 0, 0, 0];
  42673. var neighborFace;
  42674. var neighborEdge;
  42675. var oppositeFaceIdx;
  42676. //get face idx, and u, v info from center tap dir
  42677. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  42678. var faceIdx = result.x;
  42679. var u = result.y;
  42680. var v = result.z;
  42681. //define bbox size within face
  42682. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  42683. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  42684. filterExtents[faceIdx].clampMin(0, 0, 0);
  42685. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  42686. //u and v extent in face corresponding to center tap
  42687. var minU = filterExtents[faceIdx].min.x;
  42688. var minV = filterExtents[faceIdx].min.y;
  42689. var maxU = filterExtents[faceIdx].max.x;
  42690. var maxV = filterExtents[faceIdx].max.y;
  42691. //bleed over amounts for face across u=0 edge (left)
  42692. bleedOverAmount[0] = (bboxSize - u);
  42693. bleedOverBBoxMin[0] = minV;
  42694. bleedOverBBoxMax[0] = maxV;
  42695. //bleed over amounts for face across u=1 edge (right)
  42696. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  42697. bleedOverBBoxMin[1] = minV;
  42698. bleedOverBBoxMax[1] = maxV;
  42699. //bleed over to face across v=0 edge (up)
  42700. bleedOverAmount[2] = (bboxSize - v);
  42701. bleedOverBBoxMin[2] = minU;
  42702. bleedOverBBoxMax[2] = maxU;
  42703. //bleed over to face across v=1 edge (down)
  42704. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  42705. bleedOverBBoxMin[3] = minU;
  42706. bleedOverBBoxMax[3] = maxU;
  42707. //compute bleed over regions in neighboring faces
  42708. for (var i = 0; i < 4; i++) {
  42709. if (bleedOverAmount[i] > 0) {
  42710. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  42711. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  42712. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  42713. // be flipped: the cases are
  42714. // if a left edge mates with a left or bottom edge on the neighbor
  42715. // if a top edge mates with a top or right edge on the neighbor
  42716. // if a right edge mates with a right or top edge on the neighbor
  42717. // if a bottom edge mates with a bottom or left edge on the neighbor
  42718. //Seeing as the edges are enumerated as follows
  42719. // left =0
  42720. // right =1
  42721. // top =2
  42722. // bottom =3
  42723. //
  42724. // so if the edge enums are the same, or the sum of the enums == 3,
  42725. // the bbox needs to be flipped
  42726. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  42727. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  42728. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  42729. }
  42730. //The way the bounding box is extended onto the neighboring face
  42731. // depends on which edge of neighboring face abuts with this one
  42732. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  42733. case PMREMGenerator.CP_EDGE_LEFT:
  42734. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  42735. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  42736. break;
  42737. case PMREMGenerator.CP_EDGE_RIGHT:
  42738. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  42739. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  42740. break;
  42741. case PMREMGenerator.CP_EDGE_TOP:
  42742. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  42743. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  42744. break;
  42745. case PMREMGenerator.CP_EDGE_BOTTOM:
  42746. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  42747. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  42748. break;
  42749. }
  42750. //clamp filter extents in non-center tap faces to remain within surface
  42751. filterExtents[neighborFace].clampMin(0, 0, 0);
  42752. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  42753. }
  42754. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  42755. // from the center tap face, then process the opposite face entirely for now.
  42756. //Note that the cases in which this happens, what usually happens is that
  42757. // more than one edge bleeds onto the opposite face, and the bounding box
  42758. // encompasses the entire cube map face.
  42759. if (bleedOverAmount[i] > srcSize) {
  42760. //determine opposite face
  42761. switch (faceIdx) {
  42762. case PMREMGenerator.CP_FACE_X_POS:
  42763. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  42764. break;
  42765. case PMREMGenerator.CP_FACE_X_NEG:
  42766. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  42767. break;
  42768. case PMREMGenerator.CP_FACE_Y_POS:
  42769. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  42770. break;
  42771. case PMREMGenerator.CP_FACE_Y_NEG:
  42772. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  42773. break;
  42774. case PMREMGenerator.CP_FACE_Z_POS:
  42775. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  42776. break;
  42777. case PMREMGenerator.CP_FACE_Z_NEG:
  42778. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  42779. break;
  42780. default:
  42781. break;
  42782. }
  42783. //just encompass entire face for now
  42784. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  42785. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  42786. }
  42787. }
  42788. };
  42789. //--------------------------------------------------------------------------------------
  42790. //ProcessFilterExtents
  42791. // Process bounding box in each cube face
  42792. //
  42793. //--------------------------------------------------------------------------------------
  42794. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  42795. //accumulators are 64-bit floats in order to have the precision needed
  42796. // over a summation of a large number of pixels
  42797. var dstAccum = [0, 0, 0, 0];
  42798. var weightAccum = 0;
  42799. var k = 0;
  42800. var nSrcChannels = this.numChannels;
  42801. // norm cube map and srcCubeMap have same face width
  42802. var faceWidth = srcSize;
  42803. //amount to add to pointer to move to next scanline in images
  42804. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  42805. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  42806. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  42807. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  42808. // iterate over cubefaces
  42809. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  42810. //if bbox is non empty
  42811. if (!filterExtents[iFaceIdx].empty()) {
  42812. var uStart = filterExtents[iFaceIdx].min.x;
  42813. var vStart = filterExtents[iFaceIdx].min.y;
  42814. var uEnd = filterExtents[iFaceIdx].max.x;
  42815. var vEnd = filterExtents[iFaceIdx].max.y;
  42816. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  42817. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  42818. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  42819. for (var v = vStart; v <= vEnd; v++) {
  42820. var normCubeRowWalk = 0;
  42821. var srcCubeRowWalk = 0;
  42822. for (var u = uStart; u <= uEnd; u++) {
  42823. //pointer to direction in cube map associated with texel
  42824. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  42825. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  42826. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  42827. //check dot product to see if texel is within cone
  42828. var tapDotProd = texelVectX * centerTapDir.x +
  42829. texelVectY * centerTapDir.y +
  42830. texelVectZ * centerTapDir.z;
  42831. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  42832. //solid angle stored in 4th channel of normalizer/solid angle cube map
  42833. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  42834. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  42835. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  42836. // so just adding one to specularpower do the trick.
  42837. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  42838. //iterate over channels
  42839. for (k = 0; k < nSrcChannels; k++) {
  42840. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  42841. srcCubeRowWalk++;
  42842. }
  42843. weightAccum += weight; //accumulate weight
  42844. }
  42845. else {
  42846. //step across source pixel
  42847. srcCubeRowWalk += nSrcChannels;
  42848. }
  42849. normCubeRowWalk += 4; // 4 channels per norm cube map.
  42850. }
  42851. startIndexNormCubeMap += normCubePitch;
  42852. startIndexSrcCubeMap += srcCubePitch;
  42853. }
  42854. }
  42855. }
  42856. //divide through by weights if weight is non zero
  42857. if (weightAccum != 0.0) {
  42858. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  42859. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  42860. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  42861. if (this.numChannels > 3) {
  42862. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  42863. }
  42864. }
  42865. else {
  42866. // otherwise sample nearest
  42867. // get face idx and u, v texel coordinate in face
  42868. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  42869. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  42870. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  42871. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  42872. if (this.numChannels > 3) {
  42873. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  42874. }
  42875. }
  42876. return PMREMGenerator._vectorTemp;
  42877. };
  42878. //--------------------------------------------------------------------------------------
  42879. // Fixup cube edges
  42880. //
  42881. // average texels on cube map faces across the edges
  42882. // WARP/BENT Method Only.
  42883. //--------------------------------------------------------------------------------------
  42884. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  42885. var k;
  42886. var j;
  42887. var i;
  42888. var iFace;
  42889. var iCorner = 0;
  42890. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  42891. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  42892. // note that if functionality to filter across the three texels for each corner, then
  42893. //indexed by corner and face idx. the array contains the face the start points belongs to.
  42894. var cornerPtr = [
  42895. [[], [], []],
  42896. [[], [], []],
  42897. [[], [], []],
  42898. [[], [], []],
  42899. [[], [], []],
  42900. [[], [], []],
  42901. [[], [], []],
  42902. [[], [], []]
  42903. ];
  42904. //if there is no fixup, or fixup width = 0, do nothing
  42905. if (cubeMapSize < 1) {
  42906. return;
  42907. }
  42908. //special case 1x1 cubemap, average face colors
  42909. if (cubeMapSize == 1) {
  42910. //iterate over channels
  42911. for (k = 0; k < this.numChannels; k++) {
  42912. var accum = 0.0;
  42913. //iterate over faces to accumulate face colors
  42914. for (iFace = 0; iFace < 6; iFace++) {
  42915. accum += cubeMap[iFace][k];
  42916. }
  42917. //compute average over 6 face colors
  42918. accum /= 6.0;
  42919. //iterate over faces to distribute face colors
  42920. for (iFace = 0; iFace < 6; iFace++) {
  42921. cubeMap[iFace][k] = accum;
  42922. }
  42923. }
  42924. return;
  42925. }
  42926. //iterate over faces to collect list of corner texel pointers
  42927. for (iFace = 0; iFace < 6; iFace++) {
  42928. //the 4 corner pointers for this face
  42929. faceCornerStartIndicies[0] = [iFace, 0];
  42930. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  42931. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  42932. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  42933. //iterate over face corners to collect cube corner pointers
  42934. for (iCorner = 0; iCorner < 4; iCorner++) {
  42935. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  42936. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  42937. cornerNumPtrs[corner]++;
  42938. }
  42939. }
  42940. //iterate over corners to average across corner tap values
  42941. for (iCorner = 0; iCorner < 8; iCorner++) {
  42942. for (k = 0; k < this.numChannels; k++) {
  42943. var cornerTapAccum = 0.0;
  42944. //iterate over corner texels and average results
  42945. for (i = 0; i < 3; i++) {
  42946. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  42947. }
  42948. //divide by 3 to compute average of corner tap values
  42949. cornerTapAccum *= (1.0 / 3.0);
  42950. //iterate over corner texels and average results
  42951. for (i = 0; i < 3; i++) {
  42952. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  42953. }
  42954. }
  42955. }
  42956. //iterate over the twelve edges of the cube to average across edges
  42957. for (i = 0; i < 12; i++) {
  42958. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  42959. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  42960. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  42961. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  42962. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  42963. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  42964. var edgeWalk = 0;
  42965. var neighborEdgeWalk = 0;
  42966. //Determine walking pointers based on edge type
  42967. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  42968. switch (edge) {
  42969. case PMREMGenerator.CP_EDGE_LEFT:
  42970. // no change to faceEdgeStartPtr
  42971. edgeWalk = this.numChannels * cubeMapSize;
  42972. break;
  42973. case PMREMGenerator.CP_EDGE_RIGHT:
  42974. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  42975. edgeWalk = this.numChannels * cubeMapSize;
  42976. break;
  42977. case PMREMGenerator.CP_EDGE_TOP:
  42978. // no change to faceEdgeStartPtr
  42979. edgeWalk = this.numChannels;
  42980. break;
  42981. case PMREMGenerator.CP_EDGE_BOTTOM:
  42982. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  42983. edgeWalk = this.numChannels;
  42984. break;
  42985. }
  42986. //For certain types of edge abutments, the neighbor edge walk needs to
  42987. // be flipped: the cases are
  42988. // if a left edge mates with a left or bottom edge on the neighbor
  42989. // if a top edge mates with a top or right edge on the neighbor
  42990. // if a right edge mates with a right or top edge on the neighbor
  42991. // if a bottom edge mates with a bottom or left edge on the neighbor
  42992. //Seeing as the edges are enumerated as follows
  42993. // left =0
  42994. // right =1
  42995. // top =2
  42996. // bottom =3
  42997. //
  42998. //If the edge enums are the same, or the sum of the enums == 3,
  42999. // the neighbor edge walk needs to be flipped
  43000. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43001. switch (neighborEdge) {
  43002. case PMREMGenerator.CP_EDGE_LEFT:
  43003. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43004. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43005. break;
  43006. case PMREMGenerator.CP_EDGE_RIGHT:
  43007. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43008. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43009. break;
  43010. case PMREMGenerator.CP_EDGE_TOP:
  43011. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43012. neighborEdgeWalk = -this.numChannels;
  43013. break;
  43014. case PMREMGenerator.CP_EDGE_BOTTOM:
  43015. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43016. neighborEdgeWalk = -this.numChannels;
  43017. break;
  43018. }
  43019. }
  43020. else {
  43021. //swapped direction neighbor edge walk
  43022. switch (neighborEdge) {
  43023. case PMREMGenerator.CP_EDGE_LEFT:
  43024. //no change to neighborEdgeStartPtr for this case since it points
  43025. // to the upper left corner already
  43026. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43027. break;
  43028. case PMREMGenerator.CP_EDGE_RIGHT:
  43029. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43030. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43031. break;
  43032. case PMREMGenerator.CP_EDGE_TOP:
  43033. //no change to neighborEdgeStartPtr for this case since it points
  43034. // to the upper left corner already
  43035. neighborEdgeWalk = this.numChannels;
  43036. break;
  43037. case PMREMGenerator.CP_EDGE_BOTTOM:
  43038. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43039. neighborEdgeWalk = this.numChannels;
  43040. break;
  43041. }
  43042. }
  43043. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43044. //nearby neighborhood
  43045. //step ahead one texel on edge
  43046. edgeStartIndex += edgeWalk;
  43047. neighborEdgeStartIndex += neighborEdgeWalk;
  43048. // note that this loop does not process the corner texels, since they have already been
  43049. // averaged across faces across earlier
  43050. for (j = 1; j < (cubeMapSize - 1); j++) {
  43051. //for each set of taps along edge, average them
  43052. // and rewrite the results into the edges
  43053. for (k = 0; k < this.numChannels; k++) {
  43054. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43055. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43056. //compute average of tap intensity values
  43057. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43058. //propagate average of taps to edge taps
  43059. cubeMap[face][edgeStartIndex + k] = avgTap;
  43060. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43061. }
  43062. edgeStartIndex += edgeWalk;
  43063. neighborEdgeStartIndex += neighborEdgeWalk;
  43064. }
  43065. }
  43066. };
  43067. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43068. PMREMGenerator.CP_UDIR = 0;
  43069. PMREMGenerator.CP_VDIR = 1;
  43070. PMREMGenerator.CP_FACEAXIS = 2;
  43071. //used to index cube faces
  43072. PMREMGenerator.CP_FACE_X_POS = 0;
  43073. PMREMGenerator.CP_FACE_X_NEG = 1;
  43074. PMREMGenerator.CP_FACE_Y_POS = 2;
  43075. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43076. PMREMGenerator.CP_FACE_Z_POS = 4;
  43077. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43078. //used to index image edges
  43079. // NOTE.. the actual number corresponding to the edge is important
  43080. // do not change these, or the code will break
  43081. //
  43082. // CP_EDGE_LEFT is u = 0
  43083. // CP_EDGE_RIGHT is u = width-1
  43084. // CP_EDGE_TOP is v = 0
  43085. // CP_EDGE_BOTTOM is v = height-1
  43086. PMREMGenerator.CP_EDGE_LEFT = 0;
  43087. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43088. PMREMGenerator.CP_EDGE_TOP = 2;
  43089. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43090. //corners of CUBE map (P or N specifys if it corresponds to the
  43091. // positive or negative direction each of X, Y, and Z
  43092. PMREMGenerator.CP_CORNER_NNN = 0;
  43093. PMREMGenerator.CP_CORNER_NNP = 1;
  43094. PMREMGenerator.CP_CORNER_NPN = 2;
  43095. PMREMGenerator.CP_CORNER_NPP = 3;
  43096. PMREMGenerator.CP_CORNER_PNN = 4;
  43097. PMREMGenerator.CP_CORNER_PNP = 5;
  43098. PMREMGenerator.CP_CORNER_PPN = 6;
  43099. PMREMGenerator.CP_CORNER_PPP = 7;
  43100. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43101. //3x2 matrices that map cube map indexing vectors in 3d
  43102. // (after face selection and divide through by the
  43103. // _ABSOLUTE VALUE_ of the max coord)
  43104. // into NVC space
  43105. //Note this currently assumes the D3D cube face ordering and orientation
  43106. PMREMGenerator._sgFace2DMapping = [
  43107. //XPOS face
  43108. [[0, 0, -1],
  43109. [0, -1, 0],
  43110. [1, 0, 0]],
  43111. //XNEG face
  43112. [[0, 0, 1],
  43113. [0, -1, 0],
  43114. [-1, 0, 0]],
  43115. //YPOS face
  43116. [[1, 0, 0],
  43117. [0, 0, 1],
  43118. [0, 1, 0]],
  43119. //YNEG face
  43120. [[1, 0, 0],
  43121. [0, 0, -1],
  43122. [0, -1, 0]],
  43123. //ZPOS face
  43124. [[1, 0, 0],
  43125. [0, -1, 0],
  43126. [0, 0, 1]],
  43127. //ZNEG face
  43128. [[-1, 0, 0],
  43129. [0, -1, 0],
  43130. [0, 0, -1]],
  43131. ];
  43132. //------------------------------------------------------------------------------
  43133. // D3D cube map face specification
  43134. // mapping from 3D x,y,z cube map lookup coordinates
  43135. // to 2D within face u,v coordinates
  43136. //
  43137. // --------------------> U direction
  43138. // | (within-face texture space)
  43139. // | _____
  43140. // | | |
  43141. // | | +Y |
  43142. // | _____|_____|_____ _____
  43143. // | | | | | |
  43144. // | | -X | +Z | +X | -Z |
  43145. // | |_____|_____|_____|_____|
  43146. // | | |
  43147. // | | -Y |
  43148. // | |_____|
  43149. // |
  43150. // v V direction
  43151. // (within-face texture space)
  43152. //------------------------------------------------------------------------------
  43153. //Information about neighbors and how texture coorrdinates change across faces
  43154. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43155. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43156. //Note this currently assumes the D3D cube face ordering and orientation
  43157. PMREMGenerator._sgCubeNgh = [
  43158. //XPOS face
  43159. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43160. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43161. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43162. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43163. //XNEG face
  43164. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43165. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43166. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43167. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43168. //YPOS face
  43169. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43170. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43171. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43172. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43173. //YNEG face
  43174. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43175. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43176. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43177. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43178. //ZPOS face
  43179. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43180. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43181. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43182. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43183. //ZNEG face
  43184. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43185. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43186. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43187. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43188. ];
  43189. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43190. // this table is used to average over the edges.
  43191. PMREMGenerator._sgCubeEdgeList = [
  43192. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43193. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43194. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43195. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43196. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43197. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43198. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43199. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43200. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43201. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43202. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43203. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43204. ];
  43205. //Information about which of the 8 cube corners are correspond to the
  43206. // the 4 corners in each cube face
  43207. // the order is upper left, upper right, lower left, lower right
  43208. PMREMGenerator._sgCubeCornerList = [
  43209. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43210. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43211. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43212. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43213. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43214. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43215. ];
  43216. return PMREMGenerator;
  43217. })();
  43218. Internals.PMREMGenerator = PMREMGenerator;
  43219. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43220. })(BABYLON || (BABYLON = {}));
  43221. var BABYLON;
  43222. (function (BABYLON) {
  43223. /**
  43224. * This represents a texture coming from an HDR input.
  43225. *
  43226. * The only supported format is currently panorama picture stored in RGBE format.
  43227. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43228. */
  43229. var HDRCubeTexture = (function (_super) {
  43230. __extends(HDRCubeTexture, _super);
  43231. /**
  43232. * Instantiates an HDRTexture from the following parameters.
  43233. *
  43234. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43235. * @param scene The scene the texture will be used in
  43236. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43237. * @param noMipmap Forces to not generate the mipmap if true
  43238. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43239. * @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)
  43240. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43241. */
  43242. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43243. if (noMipmap === void 0) { noMipmap = false; }
  43244. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43245. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43246. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43247. _super.call(this, scene);
  43248. this._useInGammaSpace = false;
  43249. this._generateHarmonics = true;
  43250. /**
  43251. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43252. */
  43253. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43254. /**
  43255. * The spherical polynomial data extracted from the texture.
  43256. */
  43257. this.sphericalPolynomial = null;
  43258. /**
  43259. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43260. * This is usefull at run time to apply the good shader.
  43261. */
  43262. this.isPMREM = false;
  43263. this.name = url;
  43264. this.url = url;
  43265. this._noMipmap = noMipmap;
  43266. this.hasAlpha = false;
  43267. this._size = size;
  43268. this._useInGammaSpace = useInGammaSpace;
  43269. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43270. this.isPMREM = this._usePMREMGenerator;
  43271. if (!url) {
  43272. return;
  43273. }
  43274. this._texture = this._getFromCache(url, noMipmap);
  43275. if (!this._texture) {
  43276. if (!scene.useDelayedTextureLoading) {
  43277. this.loadTexture();
  43278. }
  43279. else {
  43280. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43281. }
  43282. }
  43283. this.isCube = true;
  43284. this._textureMatrix = BABYLON.Matrix.Identity();
  43285. }
  43286. HDRCubeTexture.prototype.loadTexture = function () {
  43287. var _this = this;
  43288. var callback = function (buffer) {
  43289. // Extract the raw linear data.
  43290. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43291. // Generate harmonics if needed.
  43292. if (_this._generateHarmonics) {
  43293. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43294. }
  43295. var results = [];
  43296. var byteArray = null;
  43297. // Create uintarray fallback.
  43298. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43299. // 3 channels of 1 bytes per pixel in bytes.
  43300. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43301. byteArray = new Uint8Array(byteBuffer);
  43302. }
  43303. // Push each faces.
  43304. for (var j = 0; j < 6; j++) {
  43305. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43306. // If special cases.
  43307. if (_this._useInGammaSpace || byteArray) {
  43308. for (var i = 0; i < _this._size * _this._size; i++) {
  43309. // Put in gamma space if requested.
  43310. if (_this._useInGammaSpace) {
  43311. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43312. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43313. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43314. }
  43315. // Convert to int texture for fallback.
  43316. if (byteArray) {
  43317. // R
  43318. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43319. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43320. // G
  43321. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43322. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43323. // B
  43324. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43325. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43326. }
  43327. }
  43328. }
  43329. results.push(dataFace);
  43330. }
  43331. return results;
  43332. };
  43333. var mipmapGenerator = null;
  43334. if (!this._noMipmap && this._usePMREMGenerator) {
  43335. mipmapGenerator = function (data) {
  43336. // Custom setup of the generator matching with the PBR shader values.
  43337. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43338. return generator.filterCubeMap();
  43339. };
  43340. }
  43341. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43342. };
  43343. HDRCubeTexture.prototype.clone = function () {
  43344. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43345. // Base texture
  43346. newTexture.level = this.level;
  43347. newTexture.wrapU = this.wrapU;
  43348. newTexture.wrapV = this.wrapV;
  43349. newTexture.coordinatesIndex = this.coordinatesIndex;
  43350. newTexture.coordinatesMode = this.coordinatesMode;
  43351. return newTexture;
  43352. };
  43353. // Methods
  43354. HDRCubeTexture.prototype.delayLoad = function () {
  43355. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43356. return;
  43357. }
  43358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43359. this._texture = this._getFromCache(this.url, this._noMipmap);
  43360. if (!this._texture) {
  43361. this.loadTexture();
  43362. }
  43363. };
  43364. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43365. return this._textureMatrix;
  43366. };
  43367. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43368. var texture = null;
  43369. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43370. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43371. texture.name = parsedTexture.name;
  43372. texture.hasAlpha = parsedTexture.hasAlpha;
  43373. texture.level = parsedTexture.level;
  43374. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43375. }
  43376. return texture;
  43377. };
  43378. HDRCubeTexture.prototype.serialize = function () {
  43379. if (!this.name) {
  43380. return null;
  43381. }
  43382. var serializationObject = {};
  43383. serializationObject.name = this.name;
  43384. serializationObject.hasAlpha = this.hasAlpha;
  43385. serializationObject.isCube = true;
  43386. serializationObject.level = this.level;
  43387. serializationObject.size = this._size;
  43388. serializationObject.coordinatesMode = this.coordinatesMode;
  43389. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43390. serializationObject.generateHarmonics = this._generateHarmonics;
  43391. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43392. return serializationObject;
  43393. };
  43394. HDRCubeTexture._facesMapping = [
  43395. "right",
  43396. "up",
  43397. "front",
  43398. "left",
  43399. "down",
  43400. "back"
  43401. ];
  43402. return HDRCubeTexture;
  43403. })(BABYLON.BaseTexture);
  43404. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43405. })(BABYLON || (BABYLON = {}));
  43406. var BABYLON;
  43407. (function (BABYLON) {
  43408. var Debug;
  43409. (function (Debug) {
  43410. /**
  43411. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43412. */
  43413. var SkeletonViewer = (function () {
  43414. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43415. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43416. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43417. this.skeleton = skeleton;
  43418. this.mesh = mesh;
  43419. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43420. this.renderingGroupId = renderingGroupId;
  43421. this.color = BABYLON.Color3.White();
  43422. this._debugLines = [];
  43423. this._isEnabled = false;
  43424. this._scene = scene;
  43425. this.update();
  43426. this._renderFunction = this.update.bind(this);
  43427. }
  43428. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43429. get: function () {
  43430. return this._isEnabled;
  43431. },
  43432. set: function (value) {
  43433. if (this._isEnabled === value) {
  43434. return;
  43435. }
  43436. this._isEnabled = value;
  43437. if (value) {
  43438. this._scene.registerBeforeRender(this._renderFunction);
  43439. }
  43440. else {
  43441. this._scene.unregisterBeforeRender(this._renderFunction);
  43442. }
  43443. },
  43444. enumerable: true,
  43445. configurable: true
  43446. });
  43447. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43448. if (x === void 0) { x = 0; }
  43449. if (y === void 0) { y = 0; }
  43450. if (z === void 0) { z = 0; }
  43451. var tmat = BABYLON.Tmp.Matrix[0];
  43452. var parentBone = bone.getParent();
  43453. tmat.copyFrom(bone.getLocalMatrix());
  43454. if (x !== 0 || y !== 0 || z !== 0) {
  43455. var tmat2 = BABYLON.Tmp.Matrix[1];
  43456. BABYLON.Matrix.IdentityToRef(tmat2);
  43457. tmat2.m[12] = x;
  43458. tmat2.m[13] = y;
  43459. tmat2.m[14] = z;
  43460. tmat2.multiplyToRef(tmat, tmat);
  43461. }
  43462. if (parentBone) {
  43463. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  43464. }
  43465. tmat.multiplyToRef(meshMat, tmat);
  43466. position.x = tmat.m[12];
  43467. position.y = tmat.m[13];
  43468. position.z = tmat.m[14];
  43469. };
  43470. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  43471. var len = bones.length;
  43472. for (var i = 0; i < len; i++) {
  43473. var bone = bones[i];
  43474. var points = this._debugLines[i];
  43475. if (!points) {
  43476. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43477. this._debugLines[i] = points;
  43478. }
  43479. this._getBonePosition(points[0], bone, meshMat);
  43480. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  43481. }
  43482. };
  43483. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  43484. var len = bones.length;
  43485. var boneNum = 0;
  43486. for (var i = len - 1; i >= 0; i--) {
  43487. var childBone = bones[i];
  43488. var parentBone = childBone.getParent();
  43489. if (!parentBone) {
  43490. continue;
  43491. }
  43492. var points = this._debugLines[boneNum];
  43493. if (!points) {
  43494. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43495. this._debugLines[boneNum] = points;
  43496. }
  43497. this._getBonePosition(points[0], childBone, meshMat);
  43498. this._getBonePosition(points[1], parentBone, meshMat);
  43499. boneNum++;
  43500. }
  43501. };
  43502. SkeletonViewer.prototype.update = function () {
  43503. if (this.autoUpdateBonesMatrices) {
  43504. this._updateBoneMatrix(this.skeleton.bones[0]);
  43505. }
  43506. if (this.skeleton.bones[0].length === undefined) {
  43507. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43508. }
  43509. else {
  43510. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43511. }
  43512. if (!this._debugMesh) {
  43513. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  43514. this._debugMesh.renderingGroupId = this.renderingGroupId;
  43515. }
  43516. else {
  43517. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  43518. }
  43519. this._debugMesh.color = this.color;
  43520. };
  43521. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  43522. if (bone.getParent()) {
  43523. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  43524. }
  43525. var children = bone.children;
  43526. var len = children.length;
  43527. for (var i = 0; i < len; i++) {
  43528. this._updateBoneMatrix(children[i]);
  43529. }
  43530. };
  43531. SkeletonViewer.prototype.dispose = function () {
  43532. if (this._debugMesh) {
  43533. this.isEnabled = false;
  43534. this._debugMesh.dispose();
  43535. this._debugMesh = null;
  43536. }
  43537. };
  43538. return SkeletonViewer;
  43539. })();
  43540. Debug.SkeletonViewer = SkeletonViewer;
  43541. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43542. })(BABYLON || (BABYLON = {}));
  43543. 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)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\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}"};
  43544. 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#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"};
  43545. 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={}));";
  43546. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  43547. module.exports = BABYLON;
  43548. };