babylon.max.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.conjugateToRef = function (ref) {
  1295. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1296. return this;
  1297. };
  1298. Quaternion.prototype.conjugateInPlace = function () {
  1299. this.x *= -1;
  1300. this.y *= -1;
  1301. this.z *= -1;
  1302. return this;
  1303. };
  1304. Quaternion.prototype.conjugate = function () {
  1305. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1306. return result;
  1307. };
  1308. Quaternion.prototype.length = function () {
  1309. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1310. };
  1311. Quaternion.prototype.normalize = function () {
  1312. var length = 1.0 / this.length();
  1313. this.x *= length;
  1314. this.y *= length;
  1315. this.z *= length;
  1316. this.w *= length;
  1317. return this;
  1318. };
  1319. Quaternion.prototype.toEulerAngles = function (order) {
  1320. if (order === void 0) { order = "YZX"; }
  1321. var result = Vector3.Zero();
  1322. this.toEulerAnglesToRef(result, order);
  1323. return result;
  1324. };
  1325. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1326. if (order === void 0) { order = "YZX"; }
  1327. var heading, attitude, bank;
  1328. var x = this.x, y = this.y, z = this.z, w = this.w;
  1329. switch (order) {
  1330. case "YZX":
  1331. var test = x * y + z * w;
  1332. if (test > 0.499) {
  1333. heading = 2 * Math.atan2(x, w);
  1334. attitude = Math.PI / 2;
  1335. bank = 0;
  1336. }
  1337. if (test < -0.499) {
  1338. heading = -2 * Math.atan2(x, w);
  1339. attitude = -Math.PI / 2;
  1340. bank = 0;
  1341. }
  1342. if (isNaN(heading)) {
  1343. var sqx = x * x;
  1344. var sqy = y * y;
  1345. var sqz = z * z;
  1346. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1347. attitude = Math.asin(2 * test); // attitude
  1348. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1349. }
  1350. break;
  1351. default:
  1352. throw new Error("Euler order " + order + " not supported yet.");
  1353. }
  1354. result.y = heading;
  1355. result.z = attitude;
  1356. result.x = bank;
  1357. return this;
  1358. };
  1359. ;
  1360. Quaternion.prototype.toRotationMatrix = function (result) {
  1361. var xx = this.x * this.x;
  1362. var yy = this.y * this.y;
  1363. var zz = this.z * this.z;
  1364. var xy = this.x * this.y;
  1365. var zw = this.z * this.w;
  1366. var zx = this.z * this.x;
  1367. var yw = this.y * this.w;
  1368. var yz = this.y * this.z;
  1369. var xw = this.x * this.w;
  1370. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1371. result.m[1] = 2.0 * (xy + zw);
  1372. result.m[2] = 2.0 * (zx - yw);
  1373. result.m[3] = 0;
  1374. result.m[4] = 2.0 * (xy - zw);
  1375. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1376. result.m[6] = 2.0 * (yz + xw);
  1377. result.m[7] = 0;
  1378. result.m[8] = 2.0 * (zx + yw);
  1379. result.m[9] = 2.0 * (yz - xw);
  1380. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1381. result.m[11] = 0;
  1382. result.m[12] = 0;
  1383. result.m[13] = 0;
  1384. result.m[14] = 0;
  1385. result.m[15] = 1.0;
  1386. return this;
  1387. };
  1388. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1389. Quaternion.FromRotationMatrixToRef(matrix, this);
  1390. return this;
  1391. };
  1392. // Statics
  1393. Quaternion.FromRotationMatrix = function (matrix) {
  1394. var result = new Quaternion();
  1395. Quaternion.FromRotationMatrixToRef(matrix, result);
  1396. return result;
  1397. };
  1398. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1399. var data = matrix.m;
  1400. var m11 = data[0], m12 = data[4], m13 = data[8];
  1401. var m21 = data[1], m22 = data[5], m23 = data[9];
  1402. var m31 = data[2], m32 = data[6], m33 = data[10];
  1403. var trace = m11 + m22 + m33;
  1404. var s;
  1405. if (trace > 0) {
  1406. s = 0.5 / Math.sqrt(trace + 1.0);
  1407. result.w = 0.25 / s;
  1408. result.x = (m32 - m23) * s;
  1409. result.y = (m13 - m31) * s;
  1410. result.z = (m21 - m12) * s;
  1411. }
  1412. else if (m11 > m22 && m11 > m33) {
  1413. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1414. result.w = (m32 - m23) / s;
  1415. result.x = 0.25 * s;
  1416. result.y = (m12 + m21) / s;
  1417. result.z = (m13 + m31) / s;
  1418. }
  1419. else if (m22 > m33) {
  1420. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1421. result.w = (m13 - m31) / s;
  1422. result.x = (m12 + m21) / s;
  1423. result.y = 0.25 * s;
  1424. result.z = (m23 + m32) / s;
  1425. }
  1426. else {
  1427. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1428. result.w = (m21 - m12) / s;
  1429. result.x = (m13 + m31) / s;
  1430. result.y = (m23 + m32) / s;
  1431. result.z = 0.25 * s;
  1432. }
  1433. };
  1434. Quaternion.Inverse = function (q) {
  1435. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1436. };
  1437. Quaternion.Identity = function () {
  1438. return new Quaternion(0, 0, 0, 1);
  1439. };
  1440. Quaternion.RotationAxis = function (axis, angle) {
  1441. var result = new Quaternion();
  1442. var sin = Math.sin(angle / 2);
  1443. axis.normalize();
  1444. result.w = Math.cos(angle / 2);
  1445. result.x = axis.x * sin;
  1446. result.y = axis.y * sin;
  1447. result.z = axis.z * sin;
  1448. return result;
  1449. };
  1450. Quaternion.FromArray = function (array, offset) {
  1451. if (!offset) {
  1452. offset = 0;
  1453. }
  1454. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1455. };
  1456. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1457. var result = new Quaternion();
  1458. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1459. return result;
  1460. };
  1461. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1462. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1463. var halfRoll = roll * 0.5;
  1464. var halfPitch = pitch * 0.5;
  1465. var halfYaw = yaw * 0.5;
  1466. var sinRoll = Math.sin(halfRoll);
  1467. var cosRoll = Math.cos(halfRoll);
  1468. var sinPitch = Math.sin(halfPitch);
  1469. var cosPitch = Math.cos(halfPitch);
  1470. var sinYaw = Math.sin(halfYaw);
  1471. var cosYaw = Math.cos(halfYaw);
  1472. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1473. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1474. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1475. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1476. };
  1477. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1478. var result = new Quaternion();
  1479. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1480. return result;
  1481. };
  1482. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1483. // Produces a quaternion from Euler angles in the z-x-z orientation
  1484. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1485. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1486. var halfBeta = beta * 0.5;
  1487. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1488. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1489. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1490. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1491. };
  1492. Quaternion.Slerp = function (left, right, amount) {
  1493. var num2;
  1494. var num3;
  1495. var num = amount;
  1496. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1497. var flag = false;
  1498. if (num4 < 0) {
  1499. flag = true;
  1500. num4 = -num4;
  1501. }
  1502. if (num4 > 0.999999) {
  1503. num3 = 1 - num;
  1504. num2 = flag ? -num : num;
  1505. }
  1506. else {
  1507. var num5 = Math.acos(num4);
  1508. var num6 = (1.0 / Math.sin(num5));
  1509. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1510. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1511. }
  1512. 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));
  1513. };
  1514. return Quaternion;
  1515. })();
  1516. BABYLON.Quaternion = Quaternion;
  1517. var Matrix = (function () {
  1518. function Matrix() {
  1519. this.m = new Float32Array(16);
  1520. }
  1521. // Properties
  1522. Matrix.prototype.isIdentity = function () {
  1523. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1524. return false;
  1525. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1526. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1527. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1528. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1529. return false;
  1530. return true;
  1531. };
  1532. Matrix.prototype.determinant = function () {
  1533. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1534. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1535. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1536. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1537. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1538. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1539. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1540. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1541. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1542. };
  1543. // Methods
  1544. Matrix.prototype.toArray = function () {
  1545. return this.m;
  1546. };
  1547. Matrix.prototype.asArray = function () {
  1548. return this.toArray();
  1549. };
  1550. Matrix.prototype.invert = function () {
  1551. this.invertToRef(this);
  1552. return this;
  1553. };
  1554. Matrix.prototype.reset = function () {
  1555. for (var index = 0; index < 16; index++) {
  1556. this.m[index] = 0;
  1557. }
  1558. return this;
  1559. };
  1560. Matrix.prototype.add = function (other) {
  1561. var result = new Matrix();
  1562. this.addToRef(other, result);
  1563. return result;
  1564. };
  1565. Matrix.prototype.addToRef = function (other, result) {
  1566. for (var index = 0; index < 16; index++) {
  1567. result.m[index] = this.m[index] + other.m[index];
  1568. }
  1569. return this;
  1570. };
  1571. Matrix.prototype.addToSelf = function (other) {
  1572. for (var index = 0; index < 16; index++) {
  1573. this.m[index] += other.m[index];
  1574. }
  1575. return this;
  1576. };
  1577. Matrix.prototype.invertToRef = function (other) {
  1578. var l1 = this.m[0];
  1579. var l2 = this.m[1];
  1580. var l3 = this.m[2];
  1581. var l4 = this.m[3];
  1582. var l5 = this.m[4];
  1583. var l6 = this.m[5];
  1584. var l7 = this.m[6];
  1585. var l8 = this.m[7];
  1586. var l9 = this.m[8];
  1587. var l10 = this.m[9];
  1588. var l11 = this.m[10];
  1589. var l12 = this.m[11];
  1590. var l13 = this.m[12];
  1591. var l14 = this.m[13];
  1592. var l15 = this.m[14];
  1593. var l16 = this.m[15];
  1594. var l17 = (l11 * l16) - (l12 * l15);
  1595. var l18 = (l10 * l16) - (l12 * l14);
  1596. var l19 = (l10 * l15) - (l11 * l14);
  1597. var l20 = (l9 * l16) - (l12 * l13);
  1598. var l21 = (l9 * l15) - (l11 * l13);
  1599. var l22 = (l9 * l14) - (l10 * l13);
  1600. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1601. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1602. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1603. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1604. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1605. var l28 = (l7 * l16) - (l8 * l15);
  1606. var l29 = (l6 * l16) - (l8 * l14);
  1607. var l30 = (l6 * l15) - (l7 * l14);
  1608. var l31 = (l5 * l16) - (l8 * l13);
  1609. var l32 = (l5 * l15) - (l7 * l13);
  1610. var l33 = (l5 * l14) - (l6 * l13);
  1611. var l34 = (l7 * l12) - (l8 * l11);
  1612. var l35 = (l6 * l12) - (l8 * l10);
  1613. var l36 = (l6 * l11) - (l7 * l10);
  1614. var l37 = (l5 * l12) - (l8 * l9);
  1615. var l38 = (l5 * l11) - (l7 * l9);
  1616. var l39 = (l5 * l10) - (l6 * l9);
  1617. other.m[0] = l23 * l27;
  1618. other.m[4] = l24 * l27;
  1619. other.m[8] = l25 * l27;
  1620. other.m[12] = l26 * l27;
  1621. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1622. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1623. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1624. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1625. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1626. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1627. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1628. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1629. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1630. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1631. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1632. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1633. return this;
  1634. };
  1635. Matrix.prototype.setTranslation = function (vector3) {
  1636. this.m[12] = vector3.x;
  1637. this.m[13] = vector3.y;
  1638. this.m[14] = vector3.z;
  1639. return this;
  1640. };
  1641. Matrix.prototype.multiply = function (other) {
  1642. var result = new Matrix();
  1643. this.multiplyToRef(other, result);
  1644. return result;
  1645. };
  1646. Matrix.prototype.copyFrom = function (other) {
  1647. for (var index = 0; index < 16; index++) {
  1648. this.m[index] = other.m[index];
  1649. }
  1650. return this;
  1651. };
  1652. Matrix.prototype.copyToArray = function (array, offset) {
  1653. if (offset === void 0) { offset = 0; }
  1654. for (var index = 0; index < 16; index++) {
  1655. array[offset + index] = this.m[index];
  1656. }
  1657. return this;
  1658. };
  1659. Matrix.prototype.multiplyToRef = function (other, result) {
  1660. this.multiplyToArray(other, result.m, 0);
  1661. return this;
  1662. };
  1663. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1664. var tm0 = this.m[0];
  1665. var tm1 = this.m[1];
  1666. var tm2 = this.m[2];
  1667. var tm3 = this.m[3];
  1668. var tm4 = this.m[4];
  1669. var tm5 = this.m[5];
  1670. var tm6 = this.m[6];
  1671. var tm7 = this.m[7];
  1672. var tm8 = this.m[8];
  1673. var tm9 = this.m[9];
  1674. var tm10 = this.m[10];
  1675. var tm11 = this.m[11];
  1676. var tm12 = this.m[12];
  1677. var tm13 = this.m[13];
  1678. var tm14 = this.m[14];
  1679. var tm15 = this.m[15];
  1680. var om0 = other.m[0];
  1681. var om1 = other.m[1];
  1682. var om2 = other.m[2];
  1683. var om3 = other.m[3];
  1684. var om4 = other.m[4];
  1685. var om5 = other.m[5];
  1686. var om6 = other.m[6];
  1687. var om7 = other.m[7];
  1688. var om8 = other.m[8];
  1689. var om9 = other.m[9];
  1690. var om10 = other.m[10];
  1691. var om11 = other.m[11];
  1692. var om12 = other.m[12];
  1693. var om13 = other.m[13];
  1694. var om14 = other.m[14];
  1695. var om15 = other.m[15];
  1696. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1697. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1698. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1699. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1700. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1701. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1702. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1703. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1704. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1705. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1706. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1707. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1708. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1709. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1710. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1711. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1712. return this;
  1713. };
  1714. Matrix.prototype.equals = function (value) {
  1715. return value &&
  1716. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1717. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1718. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1719. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1720. };
  1721. Matrix.prototype.clone = function () {
  1722. 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]);
  1723. };
  1724. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1725. translation.x = this.m[12];
  1726. translation.y = this.m[13];
  1727. translation.z = this.m[14];
  1728. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1729. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1730. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1731. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1732. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1733. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1734. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1735. rotation.x = 0;
  1736. rotation.y = 0;
  1737. rotation.z = 0;
  1738. rotation.w = 1;
  1739. return false;
  1740. }
  1741. 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);
  1742. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1743. return true;
  1744. };
  1745. // Statics
  1746. Matrix.FromArray = function (array, offset) {
  1747. var result = new Matrix();
  1748. if (!offset) {
  1749. offset = 0;
  1750. }
  1751. Matrix.FromArrayToRef(array, offset, result);
  1752. return result;
  1753. };
  1754. Matrix.FromArrayToRef = function (array, offset, result) {
  1755. for (var index = 0; index < 16; index++) {
  1756. result.m[index] = array[index + offset];
  1757. }
  1758. };
  1759. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1760. for (var index = 0; index < 16; index++) {
  1761. result.m[index] = array[index + offset] * scale;
  1762. }
  1763. };
  1764. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1765. result.m[0] = initialM11;
  1766. result.m[1] = initialM12;
  1767. result.m[2] = initialM13;
  1768. result.m[3] = initialM14;
  1769. result.m[4] = initialM21;
  1770. result.m[5] = initialM22;
  1771. result.m[6] = initialM23;
  1772. result.m[7] = initialM24;
  1773. result.m[8] = initialM31;
  1774. result.m[9] = initialM32;
  1775. result.m[10] = initialM33;
  1776. result.m[11] = initialM34;
  1777. result.m[12] = initialM41;
  1778. result.m[13] = initialM42;
  1779. result.m[14] = initialM43;
  1780. result.m[15] = initialM44;
  1781. };
  1782. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1783. var result = new Matrix();
  1784. result.m[0] = initialM11;
  1785. result.m[1] = initialM12;
  1786. result.m[2] = initialM13;
  1787. result.m[3] = initialM14;
  1788. result.m[4] = initialM21;
  1789. result.m[5] = initialM22;
  1790. result.m[6] = initialM23;
  1791. result.m[7] = initialM24;
  1792. result.m[8] = initialM31;
  1793. result.m[9] = initialM32;
  1794. result.m[10] = initialM33;
  1795. result.m[11] = initialM34;
  1796. result.m[12] = initialM41;
  1797. result.m[13] = initialM42;
  1798. result.m[14] = initialM43;
  1799. result.m[15] = initialM44;
  1800. return result;
  1801. };
  1802. Matrix.Compose = function (scale, rotation, translation) {
  1803. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1804. var rotationMatrix = Matrix.Identity();
  1805. rotation.toRotationMatrix(rotationMatrix);
  1806. result = result.multiply(rotationMatrix);
  1807. result.setTranslation(translation);
  1808. return result;
  1809. };
  1810. Matrix.Identity = function () {
  1811. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1812. };
  1813. Matrix.IdentityToRef = function (result) {
  1814. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1815. };
  1816. Matrix.Zero = function () {
  1817. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1818. };
  1819. Matrix.RotationX = function (angle) {
  1820. var result = new Matrix();
  1821. Matrix.RotationXToRef(angle, result);
  1822. return result;
  1823. };
  1824. Matrix.Invert = function (source) {
  1825. var result = new Matrix();
  1826. source.invertToRef(result);
  1827. return result;
  1828. };
  1829. Matrix.RotationXToRef = function (angle, result) {
  1830. var s = Math.sin(angle);
  1831. var c = Math.cos(angle);
  1832. result.m[0] = 1.0;
  1833. result.m[15] = 1.0;
  1834. result.m[5] = c;
  1835. result.m[10] = c;
  1836. result.m[9] = -s;
  1837. result.m[6] = s;
  1838. result.m[1] = 0;
  1839. result.m[2] = 0;
  1840. result.m[3] = 0;
  1841. result.m[4] = 0;
  1842. result.m[7] = 0;
  1843. result.m[8] = 0;
  1844. result.m[11] = 0;
  1845. result.m[12] = 0;
  1846. result.m[13] = 0;
  1847. result.m[14] = 0;
  1848. };
  1849. Matrix.RotationY = function (angle) {
  1850. var result = new Matrix();
  1851. Matrix.RotationYToRef(angle, result);
  1852. return result;
  1853. };
  1854. Matrix.RotationYToRef = function (angle, result) {
  1855. var s = Math.sin(angle);
  1856. var c = Math.cos(angle);
  1857. result.m[5] = 1.0;
  1858. result.m[15] = 1.0;
  1859. result.m[0] = c;
  1860. result.m[2] = -s;
  1861. result.m[8] = s;
  1862. result.m[10] = c;
  1863. result.m[1] = 0;
  1864. result.m[3] = 0;
  1865. result.m[4] = 0;
  1866. result.m[6] = 0;
  1867. result.m[7] = 0;
  1868. result.m[9] = 0;
  1869. result.m[11] = 0;
  1870. result.m[12] = 0;
  1871. result.m[13] = 0;
  1872. result.m[14] = 0;
  1873. };
  1874. Matrix.RotationZ = function (angle) {
  1875. var result = new Matrix();
  1876. Matrix.RotationZToRef(angle, result);
  1877. return result;
  1878. };
  1879. Matrix.RotationZToRef = function (angle, result) {
  1880. var s = Math.sin(angle);
  1881. var c = Math.cos(angle);
  1882. result.m[10] = 1.0;
  1883. result.m[15] = 1.0;
  1884. result.m[0] = c;
  1885. result.m[1] = s;
  1886. result.m[4] = -s;
  1887. result.m[5] = c;
  1888. result.m[2] = 0;
  1889. result.m[3] = 0;
  1890. result.m[6] = 0;
  1891. result.m[7] = 0;
  1892. result.m[8] = 0;
  1893. result.m[9] = 0;
  1894. result.m[11] = 0;
  1895. result.m[12] = 0;
  1896. result.m[13] = 0;
  1897. result.m[14] = 0;
  1898. };
  1899. Matrix.RotationAxis = function (axis, angle) {
  1900. var result = Matrix.Zero();
  1901. Matrix.RotationAxisToRef(axis, angle, result);
  1902. return result;
  1903. };
  1904. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1905. var s = Math.sin(-angle);
  1906. var c = Math.cos(-angle);
  1907. var c1 = 1 - c;
  1908. axis.normalize();
  1909. result.m[0] = (axis.x * axis.x) * c1 + c;
  1910. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1911. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1912. result.m[3] = 0.0;
  1913. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1914. result.m[5] = (axis.y * axis.y) * c1 + c;
  1915. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1916. result.m[7] = 0.0;
  1917. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1918. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1919. result.m[10] = (axis.z * axis.z) * c1 + c;
  1920. result.m[11] = 0.0;
  1921. result.m[15] = 1.0;
  1922. };
  1923. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1924. var result = new Matrix();
  1925. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1926. return result;
  1927. };
  1928. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1929. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1930. this._tempQuaternion.toRotationMatrix(result);
  1931. };
  1932. Matrix.Scaling = function (x, y, z) {
  1933. var result = Matrix.Zero();
  1934. Matrix.ScalingToRef(x, y, z, result);
  1935. return result;
  1936. };
  1937. Matrix.ScalingToRef = function (x, y, z, result) {
  1938. result.m[0] = x;
  1939. result.m[1] = 0;
  1940. result.m[2] = 0;
  1941. result.m[3] = 0;
  1942. result.m[4] = 0;
  1943. result.m[5] = y;
  1944. result.m[6] = 0;
  1945. result.m[7] = 0;
  1946. result.m[8] = 0;
  1947. result.m[9] = 0;
  1948. result.m[10] = z;
  1949. result.m[11] = 0;
  1950. result.m[12] = 0;
  1951. result.m[13] = 0;
  1952. result.m[14] = 0;
  1953. result.m[15] = 1.0;
  1954. };
  1955. Matrix.Translation = function (x, y, z) {
  1956. var result = Matrix.Identity();
  1957. Matrix.TranslationToRef(x, y, z, result);
  1958. return result;
  1959. };
  1960. Matrix.TranslationToRef = function (x, y, z, result) {
  1961. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1962. };
  1963. Matrix.Lerp = function (startValue, endValue, gradient) {
  1964. var startScale = new Vector3(0, 0, 0);
  1965. var startRotation = new Quaternion();
  1966. var startTranslation = new Vector3(0, 0, 0);
  1967. startValue.decompose(startScale, startRotation, startTranslation);
  1968. var endScale = new Vector3(0, 0, 0);
  1969. var endRotation = new Quaternion();
  1970. var endTranslation = new Vector3(0, 0, 0);
  1971. endValue.decompose(endScale, endRotation, endTranslation);
  1972. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1973. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1974. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1975. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1976. };
  1977. Matrix.LookAtLH = function (eye, target, up) {
  1978. var result = Matrix.Zero();
  1979. Matrix.LookAtLHToRef(eye, target, up, result);
  1980. return result;
  1981. };
  1982. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1983. // Z axis
  1984. target.subtractToRef(eye, this._zAxis);
  1985. this._zAxis.normalize();
  1986. // X axis
  1987. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1988. if (this._xAxis.lengthSquared() === 0) {
  1989. this._xAxis.x = 1.0;
  1990. }
  1991. else {
  1992. this._xAxis.normalize();
  1993. }
  1994. // Y axis
  1995. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1996. this._yAxis.normalize();
  1997. // Eye angles
  1998. var ex = -Vector3.Dot(this._xAxis, eye);
  1999. var ey = -Vector3.Dot(this._yAxis, eye);
  2000. var ez = -Vector3.Dot(this._zAxis, eye);
  2001. 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);
  2002. };
  2003. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2004. var matrix = Matrix.Zero();
  2005. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2006. return matrix;
  2007. };
  2008. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2009. var hw = 2.0 / width;
  2010. var hh = 2.0 / height;
  2011. var id = 1.0 / (zfar - znear);
  2012. var nid = znear / (znear - zfar);
  2013. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2014. };
  2015. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2016. var matrix = Matrix.Zero();
  2017. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2018. return matrix;
  2019. };
  2020. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2021. result.m[0] = 2.0 / (right - left);
  2022. result.m[1] = result.m[2] = result.m[3] = 0;
  2023. result.m[5] = 2.0 / (top - bottom);
  2024. result.m[4] = result.m[6] = result.m[7] = 0;
  2025. result.m[10] = -1.0 / (znear - zfar);
  2026. result.m[8] = result.m[9] = result.m[11] = 0;
  2027. result.m[12] = (left + right) / (left - right);
  2028. result.m[13] = (top + bottom) / (bottom - top);
  2029. result.m[14] = znear / (znear - zfar);
  2030. result.m[15] = 1.0;
  2031. };
  2032. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2033. var matrix = Matrix.Zero();
  2034. matrix.m[0] = (2.0 * znear) / width;
  2035. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2036. matrix.m[5] = (2.0 * znear) / height;
  2037. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2038. matrix.m[10] = -zfar / (znear - zfar);
  2039. matrix.m[8] = matrix.m[9] = 0.0;
  2040. matrix.m[11] = 1.0;
  2041. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2042. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2043. return matrix;
  2044. };
  2045. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2046. var matrix = Matrix.Zero();
  2047. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2048. return matrix;
  2049. };
  2050. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2051. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2052. var tan = 1.0 / (Math.tan(fov * 0.5));
  2053. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2054. if (v_fixed) {
  2055. result.m[0] = tan / aspect;
  2056. }
  2057. else {
  2058. result.m[0] = tan;
  2059. }
  2060. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2061. if (v_fixed) {
  2062. result.m[5] = tan;
  2063. }
  2064. else {
  2065. result.m[5] = tan * aspect;
  2066. }
  2067. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2068. result.m[8] = result.m[9] = 0.0;
  2069. result.m[10] = -zfar / (znear - zfar);
  2070. result.m[11] = 1.0;
  2071. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2072. result.m[14] = (znear * zfar) / (znear - zfar);
  2073. };
  2074. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2075. var cw = viewport.width;
  2076. var ch = viewport.height;
  2077. var cx = viewport.x;
  2078. var cy = viewport.y;
  2079. 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);
  2080. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2081. };
  2082. Matrix.GetAsMatrix2x2 = function (matrix) {
  2083. return new Float32Array([
  2084. matrix.m[0], matrix.m[1],
  2085. matrix.m[4], matrix.m[5]
  2086. ]);
  2087. };
  2088. Matrix.GetAsMatrix3x3 = function (matrix) {
  2089. return new Float32Array([
  2090. matrix.m[0], matrix.m[1], matrix.m[2],
  2091. matrix.m[4], matrix.m[5], matrix.m[6],
  2092. matrix.m[8], matrix.m[9], matrix.m[10]
  2093. ]);
  2094. };
  2095. Matrix.Transpose = function (matrix) {
  2096. var result = new Matrix();
  2097. result.m[0] = matrix.m[0];
  2098. result.m[1] = matrix.m[4];
  2099. result.m[2] = matrix.m[8];
  2100. result.m[3] = matrix.m[12];
  2101. result.m[4] = matrix.m[1];
  2102. result.m[5] = matrix.m[5];
  2103. result.m[6] = matrix.m[9];
  2104. result.m[7] = matrix.m[13];
  2105. result.m[8] = matrix.m[2];
  2106. result.m[9] = matrix.m[6];
  2107. result.m[10] = matrix.m[10];
  2108. result.m[11] = matrix.m[14];
  2109. result.m[12] = matrix.m[3];
  2110. result.m[13] = matrix.m[7];
  2111. result.m[14] = matrix.m[11];
  2112. result.m[15] = matrix.m[15];
  2113. return result;
  2114. };
  2115. Matrix.Reflection = function (plane) {
  2116. var matrix = new Matrix();
  2117. Matrix.ReflectionToRef(plane, matrix);
  2118. return matrix;
  2119. };
  2120. Matrix.ReflectionToRef = function (plane, result) {
  2121. plane.normalize();
  2122. var x = plane.normal.x;
  2123. var y = plane.normal.y;
  2124. var z = plane.normal.z;
  2125. var temp = -2 * x;
  2126. var temp2 = -2 * y;
  2127. var temp3 = -2 * z;
  2128. result.m[0] = (temp * x) + 1;
  2129. result.m[1] = temp2 * x;
  2130. result.m[2] = temp3 * x;
  2131. result.m[3] = 0.0;
  2132. result.m[4] = temp * y;
  2133. result.m[5] = (temp2 * y) + 1;
  2134. result.m[6] = temp3 * y;
  2135. result.m[7] = 0.0;
  2136. result.m[8] = temp * z;
  2137. result.m[9] = temp2 * z;
  2138. result.m[10] = (temp3 * z) + 1;
  2139. result.m[11] = 0.0;
  2140. result.m[12] = temp * plane.d;
  2141. result.m[13] = temp2 * plane.d;
  2142. result.m[14] = temp3 * plane.d;
  2143. result.m[15] = 1.0;
  2144. };
  2145. Matrix._tempQuaternion = new Quaternion();
  2146. Matrix._xAxis = Vector3.Zero();
  2147. Matrix._yAxis = Vector3.Zero();
  2148. Matrix._zAxis = Vector3.Zero();
  2149. return Matrix;
  2150. })();
  2151. BABYLON.Matrix = Matrix;
  2152. var Plane = (function () {
  2153. function Plane(a, b, c, d) {
  2154. this.normal = new Vector3(a, b, c);
  2155. this.d = d;
  2156. }
  2157. Plane.prototype.asArray = function () {
  2158. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2159. };
  2160. // Methods
  2161. Plane.prototype.clone = function () {
  2162. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2163. };
  2164. Plane.prototype.normalize = function () {
  2165. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2166. var magnitude = 0;
  2167. if (norm !== 0) {
  2168. magnitude = 1.0 / norm;
  2169. }
  2170. this.normal.x *= magnitude;
  2171. this.normal.y *= magnitude;
  2172. this.normal.z *= magnitude;
  2173. this.d *= magnitude;
  2174. return this;
  2175. };
  2176. Plane.prototype.transform = function (transformation) {
  2177. var transposedMatrix = Matrix.Transpose(transformation);
  2178. var x = this.normal.x;
  2179. var y = this.normal.y;
  2180. var z = this.normal.z;
  2181. var d = this.d;
  2182. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2183. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2184. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2185. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2186. return new Plane(normalX, normalY, normalZ, finalD);
  2187. };
  2188. Plane.prototype.dotCoordinate = function (point) {
  2189. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2190. };
  2191. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2192. var x1 = point2.x - point1.x;
  2193. var y1 = point2.y - point1.y;
  2194. var z1 = point2.z - point1.z;
  2195. var x2 = point3.x - point1.x;
  2196. var y2 = point3.y - point1.y;
  2197. var z2 = point3.z - point1.z;
  2198. var yz = (y1 * z2) - (z1 * y2);
  2199. var xz = (z1 * x2) - (x1 * z2);
  2200. var xy = (x1 * y2) - (y1 * x2);
  2201. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2202. var invPyth;
  2203. if (pyth !== 0) {
  2204. invPyth = 1.0 / pyth;
  2205. }
  2206. else {
  2207. invPyth = 0;
  2208. }
  2209. this.normal.x = yz * invPyth;
  2210. this.normal.y = xz * invPyth;
  2211. this.normal.z = xy * invPyth;
  2212. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2213. return this;
  2214. };
  2215. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2216. var dot = Vector3.Dot(this.normal, direction);
  2217. return (dot <= epsilon);
  2218. };
  2219. Plane.prototype.signedDistanceTo = function (point) {
  2220. return Vector3.Dot(point, this.normal) + this.d;
  2221. };
  2222. // Statics
  2223. Plane.FromArray = function (array) {
  2224. return new Plane(array[0], array[1], array[2], array[3]);
  2225. };
  2226. Plane.FromPoints = function (point1, point2, point3) {
  2227. var result = new Plane(0, 0, 0, 0);
  2228. result.copyFromPoints(point1, point2, point3);
  2229. return result;
  2230. };
  2231. Plane.FromPositionAndNormal = function (origin, normal) {
  2232. var result = new Plane(0, 0, 0, 0);
  2233. normal.normalize();
  2234. result.normal = normal;
  2235. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2236. return result;
  2237. };
  2238. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2239. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2240. return Vector3.Dot(point, normal) + d;
  2241. };
  2242. return Plane;
  2243. })();
  2244. BABYLON.Plane = Plane;
  2245. var Viewport = (function () {
  2246. function Viewport(x, y, width, height) {
  2247. this.x = x;
  2248. this.y = y;
  2249. this.width = width;
  2250. this.height = height;
  2251. }
  2252. Viewport.prototype.toGlobal = function (engine) {
  2253. var width = engine.getRenderWidth();
  2254. var height = engine.getRenderHeight();
  2255. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2256. };
  2257. Viewport.prototype.toScreenGlobal = function (engine) {
  2258. var width = engine.getRenderWidth(true);
  2259. var height = engine.getRenderHeight(true);
  2260. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2261. };
  2262. return Viewport;
  2263. })();
  2264. BABYLON.Viewport = Viewport;
  2265. var Frustum = (function () {
  2266. function Frustum() {
  2267. }
  2268. Frustum.GetPlanes = function (transform) {
  2269. var frustumPlanes = [];
  2270. for (var index = 0; index < 6; index++) {
  2271. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2272. }
  2273. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2274. return frustumPlanes;
  2275. };
  2276. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2277. // Near
  2278. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2279. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2280. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2281. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2282. frustumPlanes[0].normalize();
  2283. // Far
  2284. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2285. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2286. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2287. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2288. frustumPlanes[1].normalize();
  2289. // Left
  2290. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2291. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2292. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2293. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2294. frustumPlanes[2].normalize();
  2295. // Right
  2296. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2297. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2298. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2299. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2300. frustumPlanes[3].normalize();
  2301. // Top
  2302. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2303. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2304. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2305. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2306. frustumPlanes[4].normalize();
  2307. // Bottom
  2308. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2309. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2310. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2311. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2312. frustumPlanes[5].normalize();
  2313. };
  2314. return Frustum;
  2315. })();
  2316. BABYLON.Frustum = Frustum;
  2317. var Ray = (function () {
  2318. function Ray(origin, direction, length) {
  2319. if (length === void 0) { length = Number.MAX_VALUE; }
  2320. this.origin = origin;
  2321. this.direction = direction;
  2322. this.length = length;
  2323. }
  2324. // Methods
  2325. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2326. var d = 0.0;
  2327. var maxValue = Number.MAX_VALUE;
  2328. var inv;
  2329. var min;
  2330. var max;
  2331. var temp;
  2332. if (Math.abs(this.direction.x) < 0.0000001) {
  2333. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2334. return false;
  2335. }
  2336. }
  2337. else {
  2338. inv = 1.0 / this.direction.x;
  2339. min = (minimum.x - this.origin.x) * inv;
  2340. max = (maximum.x - this.origin.x) * inv;
  2341. if (max === -Infinity) {
  2342. max = Infinity;
  2343. }
  2344. if (min > max) {
  2345. temp = min;
  2346. min = max;
  2347. max = temp;
  2348. }
  2349. d = Math.max(min, d);
  2350. maxValue = Math.min(max, maxValue);
  2351. if (d > maxValue) {
  2352. return false;
  2353. }
  2354. }
  2355. if (Math.abs(this.direction.y) < 0.0000001) {
  2356. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2357. return false;
  2358. }
  2359. }
  2360. else {
  2361. inv = 1.0 / this.direction.y;
  2362. min = (minimum.y - this.origin.y) * inv;
  2363. max = (maximum.y - this.origin.y) * inv;
  2364. if (max === -Infinity) {
  2365. max = Infinity;
  2366. }
  2367. if (min > max) {
  2368. temp = min;
  2369. min = max;
  2370. max = temp;
  2371. }
  2372. d = Math.max(min, d);
  2373. maxValue = Math.min(max, maxValue);
  2374. if (d > maxValue) {
  2375. return false;
  2376. }
  2377. }
  2378. if (Math.abs(this.direction.z) < 0.0000001) {
  2379. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2380. return false;
  2381. }
  2382. }
  2383. else {
  2384. inv = 1.0 / this.direction.z;
  2385. min = (minimum.z - this.origin.z) * inv;
  2386. max = (maximum.z - this.origin.z) * inv;
  2387. if (max === -Infinity) {
  2388. max = Infinity;
  2389. }
  2390. if (min > max) {
  2391. temp = min;
  2392. min = max;
  2393. max = temp;
  2394. }
  2395. d = Math.max(min, d);
  2396. maxValue = Math.min(max, maxValue);
  2397. if (d > maxValue) {
  2398. return false;
  2399. }
  2400. }
  2401. return true;
  2402. };
  2403. Ray.prototype.intersectsBox = function (box) {
  2404. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2405. };
  2406. Ray.prototype.intersectsSphere = function (sphere) {
  2407. var x = sphere.center.x - this.origin.x;
  2408. var y = sphere.center.y - this.origin.y;
  2409. var z = sphere.center.z - this.origin.z;
  2410. var pyth = (x * x) + (y * y) + (z * z);
  2411. var rr = sphere.radius * sphere.radius;
  2412. if (pyth <= rr) {
  2413. return true;
  2414. }
  2415. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2416. if (dot < 0.0) {
  2417. return false;
  2418. }
  2419. var temp = pyth - (dot * dot);
  2420. return temp <= rr;
  2421. };
  2422. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2423. if (!this._edge1) {
  2424. this._edge1 = Vector3.Zero();
  2425. this._edge2 = Vector3.Zero();
  2426. this._pvec = Vector3.Zero();
  2427. this._tvec = Vector3.Zero();
  2428. this._qvec = Vector3.Zero();
  2429. }
  2430. vertex1.subtractToRef(vertex0, this._edge1);
  2431. vertex2.subtractToRef(vertex0, this._edge2);
  2432. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2433. var det = Vector3.Dot(this._edge1, this._pvec);
  2434. if (det === 0) {
  2435. return null;
  2436. }
  2437. var invdet = 1 / det;
  2438. this.origin.subtractToRef(vertex0, this._tvec);
  2439. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2440. if (bu < 0 || bu > 1.0) {
  2441. return null;
  2442. }
  2443. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2444. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2445. if (bv < 0 || bu + bv > 1.0) {
  2446. return null;
  2447. }
  2448. //check if the distance is longer than the predefined length.
  2449. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2450. if (distance > this.length) {
  2451. return null;
  2452. }
  2453. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2454. };
  2455. // Statics
  2456. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2457. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2458. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2459. var direction = end.subtract(start);
  2460. direction.normalize();
  2461. return new Ray(start, direction);
  2462. };
  2463. /**
  2464. * 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
  2465. * transformed to the given world matrix.
  2466. * @param origin The origin point
  2467. * @param end The end point
  2468. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2469. */
  2470. Ray.CreateNewFromTo = function (origin, end, world) {
  2471. if (world === void 0) { world = Matrix.Identity(); }
  2472. var direction = end.subtract(origin);
  2473. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2474. direction.normalize();
  2475. return Ray.Transform(new Ray(origin, direction, length), world);
  2476. };
  2477. Ray.Transform = function (ray, matrix) {
  2478. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2479. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2480. return new Ray(newOrigin, newDirection, ray.length);
  2481. };
  2482. return Ray;
  2483. })();
  2484. BABYLON.Ray = Ray;
  2485. (function (Space) {
  2486. Space[Space["LOCAL"] = 0] = "LOCAL";
  2487. Space[Space["WORLD"] = 1] = "WORLD";
  2488. })(BABYLON.Space || (BABYLON.Space = {}));
  2489. var Space = BABYLON.Space;
  2490. var Axis = (function () {
  2491. function Axis() {
  2492. }
  2493. Axis.X = new Vector3(1, 0, 0);
  2494. Axis.Y = new Vector3(0, 1, 0);
  2495. Axis.Z = new Vector3(0, 0, 1);
  2496. return Axis;
  2497. })();
  2498. BABYLON.Axis = Axis;
  2499. ;
  2500. var BezierCurve = (function () {
  2501. function BezierCurve() {
  2502. }
  2503. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2504. // Extract X (which is equal to time here)
  2505. var f0 = 1 - 3 * x2 + 3 * x1;
  2506. var f1 = 3 * x2 - 6 * x1;
  2507. var f2 = 3 * x1;
  2508. var refinedT = t;
  2509. for (var i = 0; i < 5; i++) {
  2510. var refinedT2 = refinedT * refinedT;
  2511. var refinedT3 = refinedT2 * refinedT;
  2512. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2513. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2514. refinedT -= (x - t) * slope;
  2515. refinedT = Math.min(1, Math.max(0, refinedT));
  2516. }
  2517. // Resolve cubic bezier for the given x
  2518. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2519. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2520. Math.pow(refinedT, 3);
  2521. };
  2522. return BezierCurve;
  2523. })();
  2524. BABYLON.BezierCurve = BezierCurve;
  2525. (function (Orientation) {
  2526. Orientation[Orientation["CW"] = 0] = "CW";
  2527. Orientation[Orientation["CCW"] = 1] = "CCW";
  2528. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2529. var Orientation = BABYLON.Orientation;
  2530. var Angle = (function () {
  2531. function Angle(radians) {
  2532. var _this = this;
  2533. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2534. this.radians = function () { return _this._radians; };
  2535. this._radians = radians;
  2536. if (this._radians < 0)
  2537. this._radians += (2 * Math.PI);
  2538. }
  2539. Angle.BetweenTwoPoints = function (a, b) {
  2540. var delta = b.subtract(a);
  2541. var theta = Math.atan2(delta.y, delta.x);
  2542. return new Angle(theta);
  2543. };
  2544. Angle.FromRadians = function (radians) {
  2545. return new Angle(radians);
  2546. };
  2547. Angle.FromDegrees = function (degrees) {
  2548. return new Angle(degrees * Math.PI / 180);
  2549. };
  2550. return Angle;
  2551. })();
  2552. BABYLON.Angle = Angle;
  2553. var Arc2 = (function () {
  2554. function Arc2(startPoint, midPoint, endPoint) {
  2555. this.startPoint = startPoint;
  2556. this.midPoint = midPoint;
  2557. this.endPoint = endPoint;
  2558. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2559. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2560. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2561. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2562. 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);
  2563. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2564. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2565. var a1 = this.startAngle.degrees();
  2566. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2567. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2568. // angles correction
  2569. if (a2 - a1 > +180.0)
  2570. a2 -= 360.0;
  2571. if (a2 - a1 < -180.0)
  2572. a2 += 360.0;
  2573. if (a3 - a2 > +180.0)
  2574. a3 -= 360.0;
  2575. if (a3 - a2 < -180.0)
  2576. a3 += 360.0;
  2577. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2578. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2579. }
  2580. return Arc2;
  2581. })();
  2582. BABYLON.Arc2 = Arc2;
  2583. var PathCursor = (function () {
  2584. function PathCursor(path) {
  2585. this.path = path;
  2586. this._onchange = new Array();
  2587. this.value = 0;
  2588. this.animations = new Array();
  2589. }
  2590. PathCursor.prototype.getPoint = function () {
  2591. var point = this.path.getPointAtLengthPosition(this.value);
  2592. return new Vector3(point.x, 0, point.y);
  2593. };
  2594. PathCursor.prototype.moveAhead = function (step) {
  2595. if (step === void 0) { step = 0.002; }
  2596. this.move(step);
  2597. return this;
  2598. };
  2599. PathCursor.prototype.moveBack = function (step) {
  2600. if (step === void 0) { step = 0.002; }
  2601. this.move(-step);
  2602. return this;
  2603. };
  2604. PathCursor.prototype.move = function (step) {
  2605. if (Math.abs(step) > 1) {
  2606. throw "step size should be less than 1.";
  2607. }
  2608. this.value += step;
  2609. this.ensureLimits();
  2610. this.raiseOnChange();
  2611. return this;
  2612. };
  2613. PathCursor.prototype.ensureLimits = function () {
  2614. while (this.value > 1) {
  2615. this.value -= 1;
  2616. }
  2617. while (this.value < 0) {
  2618. this.value += 1;
  2619. }
  2620. return this;
  2621. };
  2622. // used by animation engine
  2623. PathCursor.prototype.markAsDirty = function (propertyName) {
  2624. this.ensureLimits();
  2625. this.raiseOnChange();
  2626. return this;
  2627. };
  2628. PathCursor.prototype.raiseOnChange = function () {
  2629. var _this = this;
  2630. this._onchange.forEach(function (f) { return f(_this); });
  2631. return this;
  2632. };
  2633. PathCursor.prototype.onchange = function (f) {
  2634. this._onchange.push(f);
  2635. return this;
  2636. };
  2637. return PathCursor;
  2638. })();
  2639. BABYLON.PathCursor = PathCursor;
  2640. var Path2 = (function () {
  2641. function Path2(x, y) {
  2642. this._points = new Array();
  2643. this._length = 0;
  2644. this.closed = false;
  2645. this._points.push(new Vector2(x, y));
  2646. }
  2647. Path2.prototype.addLineTo = function (x, y) {
  2648. if (closed) {
  2649. BABYLON.Tools.Error("cannot add lines to closed paths");
  2650. return this;
  2651. }
  2652. var newPoint = new Vector2(x, y);
  2653. var previousPoint = this._points[this._points.length - 1];
  2654. this._points.push(newPoint);
  2655. this._length += newPoint.subtract(previousPoint).length();
  2656. return this;
  2657. };
  2658. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2659. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2660. if (closed) {
  2661. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2662. return this;
  2663. }
  2664. var startPoint = this._points[this._points.length - 1];
  2665. var midPoint = new Vector2(midX, midY);
  2666. var endPoint = new Vector2(endX, endY);
  2667. var arc = new Arc2(startPoint, midPoint, endPoint);
  2668. var increment = arc.angle.radians() / numberOfSegments;
  2669. if (arc.orientation === Orientation.CW)
  2670. increment *= -1;
  2671. var currentAngle = arc.startAngle.radians() + increment;
  2672. for (var i = 0; i < numberOfSegments; i++) {
  2673. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2674. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2675. this.addLineTo(x, y);
  2676. currentAngle += increment;
  2677. }
  2678. return this;
  2679. };
  2680. Path2.prototype.close = function () {
  2681. this.closed = true;
  2682. return this;
  2683. };
  2684. Path2.prototype.length = function () {
  2685. var result = this._length;
  2686. if (!this.closed) {
  2687. var lastPoint = this._points[this._points.length - 1];
  2688. var firstPoint = this._points[0];
  2689. result += (firstPoint.subtract(lastPoint).length());
  2690. }
  2691. return result;
  2692. };
  2693. Path2.prototype.getPoints = function () {
  2694. return this._points;
  2695. };
  2696. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2697. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2698. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2699. return Vector2.Zero();
  2700. }
  2701. var lengthPosition = normalizedLengthPosition * this.length();
  2702. var previousOffset = 0;
  2703. for (var i = 0; i < this._points.length; i++) {
  2704. var j = (i + 1) % this._points.length;
  2705. var a = this._points[i];
  2706. var b = this._points[j];
  2707. var bToA = b.subtract(a);
  2708. var nextOffset = (bToA.length() + previousOffset);
  2709. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2710. var dir = bToA.normalize();
  2711. var localOffset = lengthPosition - previousOffset;
  2712. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2713. }
  2714. previousOffset = nextOffset;
  2715. }
  2716. BABYLON.Tools.Error("internal error");
  2717. return Vector2.Zero();
  2718. };
  2719. Path2.StartingAt = function (x, y) {
  2720. return new Path2(x, y);
  2721. };
  2722. return Path2;
  2723. })();
  2724. BABYLON.Path2 = Path2;
  2725. var Path3D = (function () {
  2726. /**
  2727. * new Path3D(path, normal, raw)
  2728. * path : an array of Vector3, the curve axis of the Path3D
  2729. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2730. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2731. */
  2732. function Path3D(path, firstNormal, raw) {
  2733. this.path = path;
  2734. this._curve = new Array();
  2735. this._distances = new Array();
  2736. this._tangents = new Array();
  2737. this._normals = new Array();
  2738. this._binormals = new Array();
  2739. for (var p = 0; p < path.length; p++) {
  2740. this._curve[p] = path[p].clone(); // hard copy
  2741. }
  2742. this._raw = raw || false;
  2743. this._compute(firstNormal);
  2744. }
  2745. Path3D.prototype.getCurve = function () {
  2746. return this._curve;
  2747. };
  2748. Path3D.prototype.getTangents = function () {
  2749. return this._tangents;
  2750. };
  2751. Path3D.prototype.getNormals = function () {
  2752. return this._normals;
  2753. };
  2754. Path3D.prototype.getBinormals = function () {
  2755. return this._binormals;
  2756. };
  2757. Path3D.prototype.getDistances = function () {
  2758. return this._distances;
  2759. };
  2760. Path3D.prototype.update = function (path, firstNormal) {
  2761. for (var p = 0; p < path.length; p++) {
  2762. this._curve[p].x = path[p].x;
  2763. this._curve[p].y = path[p].y;
  2764. this._curve[p].z = path[p].z;
  2765. }
  2766. this._compute(firstNormal);
  2767. return this;
  2768. };
  2769. // private function compute() : computes tangents, normals and binormals
  2770. Path3D.prototype._compute = function (firstNormal) {
  2771. var l = this._curve.length;
  2772. // first and last tangents
  2773. this._tangents[0] = this._getFirstNonNullVector(0);
  2774. if (!this._raw) {
  2775. this._tangents[0].normalize();
  2776. }
  2777. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2778. if (!this._raw) {
  2779. this._tangents[l - 1].normalize();
  2780. }
  2781. // normals and binormals at first point : arbitrary vector with _normalVector()
  2782. var tg0 = this._tangents[0];
  2783. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2784. this._normals[0] = pp0;
  2785. if (!this._raw) {
  2786. this._normals[0].normalize();
  2787. }
  2788. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2789. if (!this._raw) {
  2790. this._binormals[0].normalize();
  2791. }
  2792. this._distances[0] = 0;
  2793. // normals and binormals : next points
  2794. var prev; // previous vector (segment)
  2795. var cur; // current vector (segment)
  2796. var curTang; // current tangent
  2797. // previous normal
  2798. var prevBinor; // previous binormal
  2799. for (var i = 1; i < l; i++) {
  2800. // tangents
  2801. prev = this._getLastNonNullVector(i);
  2802. if (i < l - 1) {
  2803. cur = this._getFirstNonNullVector(i);
  2804. this._tangents[i] = prev.add(cur);
  2805. this._tangents[i].normalize();
  2806. }
  2807. this._distances[i] = this._distances[i - 1] + prev.length();
  2808. // normals and binormals
  2809. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2810. curTang = this._tangents[i];
  2811. prevBinor = this._binormals[i - 1];
  2812. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2813. if (!this._raw) {
  2814. this._normals[i].normalize();
  2815. }
  2816. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2817. if (!this._raw) {
  2818. this._binormals[i].normalize();
  2819. }
  2820. }
  2821. };
  2822. // private function getFirstNonNullVector(index)
  2823. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2824. Path3D.prototype._getFirstNonNullVector = function (index) {
  2825. var i = 1;
  2826. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2827. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2828. i++;
  2829. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2830. }
  2831. return nNVector;
  2832. };
  2833. // private function getLastNonNullVector(index)
  2834. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2835. Path3D.prototype._getLastNonNullVector = function (index) {
  2836. var i = 1;
  2837. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2838. while (nLVector.length() === 0 && index > i + 1) {
  2839. i++;
  2840. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2841. }
  2842. return nLVector;
  2843. };
  2844. // private function normalVector(v0, vt, va) :
  2845. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2846. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2847. Path3D.prototype._normalVector = function (v0, vt, va) {
  2848. var normal0;
  2849. if (va === undefined || va === null) {
  2850. var point;
  2851. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2852. point = new Vector3(0, -1, 0);
  2853. }
  2854. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2855. point = new Vector3(1, 0, 0);
  2856. }
  2857. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2858. point = new Vector3(0, 0, 1);
  2859. }
  2860. normal0 = Vector3.Cross(vt, point);
  2861. }
  2862. else {
  2863. normal0 = Vector3.Cross(vt, va);
  2864. Vector3.CrossToRef(normal0, vt, normal0);
  2865. }
  2866. normal0.normalize();
  2867. return normal0;
  2868. };
  2869. return Path3D;
  2870. })();
  2871. BABYLON.Path3D = Path3D;
  2872. var Curve3 = (function () {
  2873. function Curve3(points) {
  2874. this._length = 0;
  2875. this._points = points;
  2876. this._length = this._computeLength(points);
  2877. }
  2878. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2879. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2880. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2881. var bez = new Array();
  2882. var equation = function (t, val0, val1, val2) {
  2883. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2884. return res;
  2885. };
  2886. for (var i = 0; i <= nbPoints; i++) {
  2887. 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)));
  2888. }
  2889. return new Curve3(bez);
  2890. };
  2891. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2892. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2893. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2894. var bez = new Array();
  2895. var equation = function (t, val0, val1, val2, val3) {
  2896. 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;
  2897. return res;
  2898. };
  2899. for (var i = 0; i <= nbPoints; i++) {
  2900. 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)));
  2901. }
  2902. return new Curve3(bez);
  2903. };
  2904. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2905. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2906. var hermite = new Array();
  2907. var step = 1 / nbPoints;
  2908. for (var i = 0; i <= nbPoints; i++) {
  2909. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2910. }
  2911. return new Curve3(hermite);
  2912. };
  2913. Curve3.prototype.getPoints = function () {
  2914. return this._points;
  2915. };
  2916. Curve3.prototype.length = function () {
  2917. return this._length;
  2918. };
  2919. Curve3.prototype.continue = function (curve) {
  2920. var lastPoint = this._points[this._points.length - 1];
  2921. var continuedPoints = this._points.slice();
  2922. var curvePoints = curve.getPoints();
  2923. for (var i = 1; i < curvePoints.length; i++) {
  2924. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2925. }
  2926. var continuedCurve = new Curve3(continuedPoints);
  2927. return continuedCurve;
  2928. };
  2929. Curve3.prototype._computeLength = function (path) {
  2930. var l = 0;
  2931. for (var i = 1; i < path.length; i++) {
  2932. l += (path[i].subtract(path[i - 1])).length();
  2933. }
  2934. return l;
  2935. };
  2936. return Curve3;
  2937. })();
  2938. BABYLON.Curve3 = Curve3;
  2939. // SphericalHarmonics
  2940. var SphericalHarmonics = (function () {
  2941. function SphericalHarmonics() {
  2942. this.L00 = Vector3.Zero();
  2943. this.L1_1 = Vector3.Zero();
  2944. this.L10 = Vector3.Zero();
  2945. this.L11 = Vector3.Zero();
  2946. this.L2_2 = Vector3.Zero();
  2947. this.L2_1 = Vector3.Zero();
  2948. this.L20 = Vector3.Zero();
  2949. this.L21 = Vector3.Zero();
  2950. this.L22 = Vector3.Zero();
  2951. }
  2952. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2953. var colorVector = new Vector3(color.r, color.g, color.b);
  2954. var c = colorVector.scale(deltaSolidAngle);
  2955. this.L00 = this.L00.add(c.scale(0.282095));
  2956. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2957. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2958. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2959. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2960. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2961. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2962. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2963. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2964. };
  2965. SphericalHarmonics.prototype.scale = function (scale) {
  2966. this.L00 = this.L00.scale(scale);
  2967. this.L1_1 = this.L1_1.scale(scale);
  2968. this.L10 = this.L10.scale(scale);
  2969. this.L11 = this.L11.scale(scale);
  2970. this.L2_2 = this.L2_2.scale(scale);
  2971. this.L2_1 = this.L2_1.scale(scale);
  2972. this.L20 = this.L20.scale(scale);
  2973. this.L21 = this.L21.scale(scale);
  2974. this.L22 = this.L22.scale(scale);
  2975. };
  2976. return SphericalHarmonics;
  2977. })();
  2978. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2979. // SphericalPolynomial
  2980. var SphericalPolynomial = (function () {
  2981. function SphericalPolynomial() {
  2982. this.x = Vector3.Zero();
  2983. this.y = Vector3.Zero();
  2984. this.z = Vector3.Zero();
  2985. this.xx = Vector3.Zero();
  2986. this.yy = Vector3.Zero();
  2987. this.zz = Vector3.Zero();
  2988. this.xy = Vector3.Zero();
  2989. this.yz = Vector3.Zero();
  2990. this.zx = Vector3.Zero();
  2991. }
  2992. SphericalPolynomial.prototype.addAmbient = function (color) {
  2993. var colorVector = new Vector3(color.r, color.g, color.b);
  2994. this.xx = this.xx.add(colorVector);
  2995. this.yy = this.yy.add(colorVector);
  2996. this.zz = this.zz.add(colorVector);
  2997. };
  2998. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2999. var result = new SphericalPolynomial();
  3000. result.x = harmonics.L11.scale(1.02333);
  3001. result.y = harmonics.L1_1.scale(1.02333);
  3002. result.z = harmonics.L10.scale(1.02333);
  3003. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3004. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3005. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3006. result.yz = harmonics.L2_1.scale(0.858086);
  3007. result.zx = harmonics.L21.scale(0.858086);
  3008. result.xy = harmonics.L2_2.scale(0.858086);
  3009. return result;
  3010. };
  3011. return SphericalPolynomial;
  3012. })();
  3013. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3014. // Vertex formats
  3015. var PositionNormalVertex = (function () {
  3016. function PositionNormalVertex(position, normal) {
  3017. if (position === void 0) { position = Vector3.Zero(); }
  3018. if (normal === void 0) { normal = Vector3.Up(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. }
  3022. PositionNormalVertex.prototype.clone = function () {
  3023. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3024. };
  3025. return PositionNormalVertex;
  3026. })();
  3027. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3028. var PositionNormalTextureVertex = (function () {
  3029. function PositionNormalTextureVertex(position, normal, uv) {
  3030. if (position === void 0) { position = Vector3.Zero(); }
  3031. if (normal === void 0) { normal = Vector3.Up(); }
  3032. if (uv === void 0) { uv = Vector2.Zero(); }
  3033. this.position = position;
  3034. this.normal = normal;
  3035. this.uv = uv;
  3036. }
  3037. PositionNormalTextureVertex.prototype.clone = function () {
  3038. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3039. };
  3040. return PositionNormalTextureVertex;
  3041. })();
  3042. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3043. // Temporary pre-allocated objects for engine internal use
  3044. // usage in any internal function :
  3045. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3046. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3047. var Tmp = (function () {
  3048. function Tmp() {
  3049. }
  3050. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3051. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3052. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3053. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3054. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3055. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3056. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3057. Matrix.Zero(), Matrix.Zero(),
  3058. Matrix.Zero(), Matrix.Zero(),
  3059. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3060. return Tmp;
  3061. })();
  3062. BABYLON.Tmp = Tmp;
  3063. })(BABYLON || (BABYLON = {}));
  3064. var BABYLON;
  3065. (function (BABYLON) {
  3066. function generateSerializableMember(type, sourceName) {
  3067. return function (target, propertyKey) {
  3068. if (!target.__serializableMembers) {
  3069. target.__serializableMembers = {};
  3070. }
  3071. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3072. };
  3073. }
  3074. function serialize(sourceName) {
  3075. return generateSerializableMember(0, sourceName); // value member
  3076. }
  3077. BABYLON.serialize = serialize;
  3078. function serializeAsTexture(sourceName) {
  3079. return generateSerializableMember(1, sourceName); // texture member
  3080. }
  3081. BABYLON.serializeAsTexture = serializeAsTexture;
  3082. function serializeAsColor3(sourceName) {
  3083. return generateSerializableMember(2, sourceName); // color3 member
  3084. }
  3085. BABYLON.serializeAsColor3 = serializeAsColor3;
  3086. function serializeAsFresnelParameters(sourceName) {
  3087. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3088. }
  3089. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3090. function serializeAsVector2(sourceName) {
  3091. return generateSerializableMember(4, sourceName); // vector2 member
  3092. }
  3093. BABYLON.serializeAsVector2 = serializeAsVector2;
  3094. function serializeAsVector3(sourceName) {
  3095. return generateSerializableMember(5, sourceName); // vector3 member
  3096. }
  3097. BABYLON.serializeAsVector3 = serializeAsVector3;
  3098. function serializeAsMeshReference(sourceName) {
  3099. return generateSerializableMember(6, sourceName); // mesh reference member
  3100. }
  3101. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3102. var SerializationHelper = (function () {
  3103. function SerializationHelper() {
  3104. }
  3105. SerializationHelper.Serialize = function (entity, serializationObject) {
  3106. if (!serializationObject) {
  3107. serializationObject = {};
  3108. }
  3109. // Tags
  3110. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3111. // Properties
  3112. for (var property in entity.__serializableMembers) {
  3113. var propertyDescriptor = entity.__serializableMembers[property];
  3114. var targetPropertyName = propertyDescriptor.sourceName || property;
  3115. var propertyType = propertyDescriptor.type;
  3116. var sourceProperty = entity[property];
  3117. if (sourceProperty !== undefined && sourceProperty !== null) {
  3118. switch (propertyType) {
  3119. case 0:
  3120. serializationObject[targetPropertyName] = sourceProperty;
  3121. break;
  3122. case 1:
  3123. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3124. break;
  3125. case 2:
  3126. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3127. break;
  3128. case 3:
  3129. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3130. break;
  3131. case 4:
  3132. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3133. break;
  3134. case 5:
  3135. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3136. break;
  3137. case 6:
  3138. serializationObject[targetPropertyName] = sourceProperty.id;
  3139. break;
  3140. }
  3141. }
  3142. }
  3143. return serializationObject;
  3144. };
  3145. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3146. var destination = creationFunction();
  3147. // Tags
  3148. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3149. // Properties
  3150. for (var property in destination.__serializableMembers) {
  3151. var propertyDescriptor = destination.__serializableMembers[property];
  3152. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3153. var propertyType = propertyDescriptor.type;
  3154. if (sourceProperty !== undefined && sourceProperty !== null) {
  3155. switch (propertyType) {
  3156. case 0:
  3157. destination[property] = sourceProperty;
  3158. break;
  3159. case 1:
  3160. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3161. break;
  3162. case 2:
  3163. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3164. break;
  3165. case 3:
  3166. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3167. break;
  3168. case 4:
  3169. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3170. break;
  3171. case 5:
  3172. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3173. break;
  3174. case 6:
  3175. destination[property] = scene.getLastMeshByID(sourceProperty);
  3176. break;
  3177. }
  3178. }
  3179. }
  3180. return destination;
  3181. };
  3182. SerializationHelper.Clone = function (creationFunction, source) {
  3183. var destination = creationFunction();
  3184. // Tags
  3185. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3186. // Properties
  3187. for (var property in destination.__serializableMembers) {
  3188. var propertyDescriptor = destination.__serializableMembers[property];
  3189. var sourceProperty = source[property];
  3190. var propertyType = propertyDescriptor.type;
  3191. if (sourceProperty !== undefined && sourceProperty !== null) {
  3192. switch (propertyType) {
  3193. case 0: // Value
  3194. case 6:
  3195. destination[property] = sourceProperty;
  3196. break;
  3197. case 1: // Texture
  3198. case 2: // Color3
  3199. case 3: // FresnelParameters
  3200. case 4: // Vector2
  3201. case 5:
  3202. destination[property] = sourceProperty.clone();
  3203. break;
  3204. }
  3205. }
  3206. }
  3207. return destination;
  3208. };
  3209. return SerializationHelper;
  3210. })();
  3211. BABYLON.SerializationHelper = SerializationHelper;
  3212. })(BABYLON || (BABYLON = {}));
  3213. var BABYLON;
  3214. (function (BABYLON) {
  3215. var Database = (function () {
  3216. function Database(urlToScene, callbackManifestChecked) {
  3217. // Handling various flavors of prefixed version of IndexedDB
  3218. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3219. this.callbackManifestChecked = callbackManifestChecked;
  3220. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3221. this.db = null;
  3222. this.enableSceneOffline = false;
  3223. this.enableTexturesOffline = false;
  3224. this.manifestVersionFound = 0;
  3225. this.mustUpdateRessources = false;
  3226. this.hasReachedQuota = false;
  3227. if (!Database.IDBStorageEnabled) {
  3228. this.callbackManifestChecked(true);
  3229. }
  3230. else {
  3231. this.checkManifestFile();
  3232. }
  3233. }
  3234. Database.prototype.checkManifestFile = function () {
  3235. var _this = this;
  3236. function noManifestFile() {
  3237. that.enableSceneOffline = false;
  3238. that.enableTexturesOffline = false;
  3239. that.callbackManifestChecked(false);
  3240. }
  3241. var that = this;
  3242. var timeStampUsed = false;
  3243. var manifestURL = this.currentSceneUrl + ".manifest";
  3244. var xhr = new XMLHttpRequest();
  3245. if (navigator.onLine) {
  3246. // Adding a timestamp to by-pass browsers' cache
  3247. timeStampUsed = true;
  3248. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3249. }
  3250. xhr.open("GET", manifestURL, true);
  3251. xhr.addEventListener("load", function () {
  3252. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3253. try {
  3254. var manifestFile = JSON.parse(xhr.response);
  3255. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3256. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3257. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3258. _this.manifestVersionFound = manifestFile.version;
  3259. }
  3260. if (_this.callbackManifestChecked) {
  3261. _this.callbackManifestChecked(true);
  3262. }
  3263. }
  3264. catch (ex) {
  3265. noManifestFile();
  3266. }
  3267. }
  3268. else {
  3269. noManifestFile();
  3270. }
  3271. }, false);
  3272. xhr.addEventListener("error", function (event) {
  3273. if (timeStampUsed) {
  3274. timeStampUsed = false;
  3275. // Let's retry without the timeStamp
  3276. // It could fail when coupled with HTML5 Offline API
  3277. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3278. xhr.open("GET", retryManifestURL, true);
  3279. xhr.send();
  3280. }
  3281. else {
  3282. noManifestFile();
  3283. }
  3284. }, false);
  3285. try {
  3286. xhr.send();
  3287. }
  3288. catch (ex) {
  3289. BABYLON.Tools.Error("Error on XHR send request.");
  3290. that.callbackManifestChecked(false);
  3291. }
  3292. };
  3293. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3294. var _this = this;
  3295. function handleError() {
  3296. that.isSupported = false;
  3297. if (errorCallback)
  3298. errorCallback();
  3299. }
  3300. var that = this;
  3301. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3302. // Your browser doesn't support IndexedDB
  3303. this.isSupported = false;
  3304. if (errorCallback)
  3305. errorCallback();
  3306. }
  3307. else {
  3308. // If the DB hasn't been opened or created yet
  3309. if (!this.db) {
  3310. this.hasReachedQuota = false;
  3311. this.isSupported = true;
  3312. var request = this.idbFactory.open("babylonjs", 1);
  3313. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3314. request.onerror = function (event) {
  3315. handleError();
  3316. };
  3317. // executes when a version change transaction cannot complete due to other active transactions
  3318. request.onblocked = function (event) {
  3319. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3320. handleError();
  3321. };
  3322. // DB has been opened successfully
  3323. request.onsuccess = function (event) {
  3324. _this.db = request.result;
  3325. successCallback();
  3326. };
  3327. // Initialization of the DB. Creating Scenes & Textures stores
  3328. request.onupgradeneeded = function (event) {
  3329. _this.db = (event.target).result;
  3330. try {
  3331. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3332. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3333. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3334. }
  3335. catch (ex) {
  3336. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3337. handleError();
  3338. }
  3339. };
  3340. }
  3341. else {
  3342. if (successCallback)
  3343. successCallback();
  3344. }
  3345. }
  3346. };
  3347. Database.prototype.loadImageFromDB = function (url, image) {
  3348. var _this = this;
  3349. var completeURL = Database.ReturnFullUrlLocation(url);
  3350. var saveAndLoadImage = function () {
  3351. if (!_this.hasReachedQuota && _this.db !== null) {
  3352. // the texture is not yet in the DB, let's try to save it
  3353. _this._saveImageIntoDBAsync(completeURL, image);
  3354. }
  3355. else {
  3356. image.src = url;
  3357. }
  3358. };
  3359. if (!this.mustUpdateRessources) {
  3360. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3361. }
  3362. else {
  3363. saveAndLoadImage();
  3364. }
  3365. };
  3366. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3367. if (this.isSupported && this.db !== null) {
  3368. var texture;
  3369. var transaction = this.db.transaction(["textures"]);
  3370. transaction.onabort = function (event) {
  3371. image.src = url;
  3372. };
  3373. transaction.oncomplete = function (event) {
  3374. var blobTextureURL;
  3375. if (texture) {
  3376. var URL = window.URL || window.webkitURL;
  3377. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3378. image.onerror = function () {
  3379. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3380. image.src = url;
  3381. };
  3382. image.src = blobTextureURL;
  3383. }
  3384. else {
  3385. notInDBCallback();
  3386. }
  3387. };
  3388. var getRequest = transaction.objectStore("textures").get(url);
  3389. getRequest.onsuccess = function (event) {
  3390. texture = (event.target).result;
  3391. };
  3392. getRequest.onerror = function (event) {
  3393. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3394. image.src = url;
  3395. };
  3396. }
  3397. else {
  3398. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3399. image.src = url;
  3400. }
  3401. };
  3402. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3403. var _this = this;
  3404. if (this.isSupported) {
  3405. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3406. var generateBlobUrl = function () {
  3407. var blobTextureURL;
  3408. if (blob) {
  3409. var URL = window.URL || window.webkitURL;
  3410. try {
  3411. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3412. }
  3413. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3414. catch (ex) {
  3415. blobTextureURL = URL.createObjectURL(blob);
  3416. }
  3417. }
  3418. image.src = blobTextureURL;
  3419. };
  3420. if (Database.IsUASupportingBlobStorage) {
  3421. var xhr = new XMLHttpRequest(), blob;
  3422. xhr.open("GET", url, true);
  3423. xhr.responseType = "blob";
  3424. xhr.addEventListener("load", function () {
  3425. if (xhr.status === 200) {
  3426. // Blob as response (XHR2)
  3427. blob = xhr.response;
  3428. var transaction = _this.db.transaction(["textures"], "readwrite");
  3429. // the transaction could abort because of a QuotaExceededError error
  3430. transaction.onabort = function (event) {
  3431. try {
  3432. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3433. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3434. this.hasReachedQuota = true;
  3435. }
  3436. }
  3437. catch (ex) { }
  3438. generateBlobUrl();
  3439. };
  3440. transaction.oncomplete = function (event) {
  3441. generateBlobUrl();
  3442. };
  3443. var newTexture = { textureUrl: url, data: blob };
  3444. try {
  3445. // Put the blob into the dabase
  3446. var addRequest = transaction.objectStore("textures").put(newTexture);
  3447. addRequest.onsuccess = function (event) {
  3448. };
  3449. addRequest.onerror = function (event) {
  3450. generateBlobUrl();
  3451. };
  3452. }
  3453. catch (ex) {
  3454. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3455. if (ex.code === 25) {
  3456. Database.IsUASupportingBlobStorage = false;
  3457. }
  3458. image.src = url;
  3459. }
  3460. }
  3461. else {
  3462. image.src = url;
  3463. }
  3464. }, false);
  3465. xhr.addEventListener("error", function (event) {
  3466. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3467. image.src = url;
  3468. }, false);
  3469. xhr.send();
  3470. }
  3471. else {
  3472. image.src = url;
  3473. }
  3474. }
  3475. else {
  3476. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3477. image.src = url;
  3478. }
  3479. };
  3480. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3481. var _this = this;
  3482. var updateVersion = function (event) {
  3483. // the version is not yet in the DB or we need to update it
  3484. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3485. };
  3486. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3487. };
  3488. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3489. var _this = this;
  3490. if (this.isSupported) {
  3491. var version;
  3492. try {
  3493. var transaction = this.db.transaction(["versions"]);
  3494. transaction.oncomplete = function (event) {
  3495. if (version) {
  3496. // If the version in the JSON file is > than the version in DB
  3497. if (_this.manifestVersionFound > version.data) {
  3498. _this.mustUpdateRessources = true;
  3499. updateInDBCallback();
  3500. }
  3501. else {
  3502. callback(version.data);
  3503. }
  3504. }
  3505. else {
  3506. _this.mustUpdateRessources = true;
  3507. updateInDBCallback();
  3508. }
  3509. };
  3510. transaction.onabort = function (event) {
  3511. callback(-1);
  3512. };
  3513. var getRequest = transaction.objectStore("versions").get(url);
  3514. getRequest.onsuccess = function (event) {
  3515. version = (event.target).result;
  3516. };
  3517. getRequest.onerror = function (event) {
  3518. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3519. callback(-1);
  3520. };
  3521. }
  3522. catch (ex) {
  3523. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3524. callback(-1);
  3525. }
  3526. }
  3527. else {
  3528. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3529. callback(-1);
  3530. }
  3531. };
  3532. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3533. var _this = this;
  3534. if (this.isSupported && !this.hasReachedQuota) {
  3535. try {
  3536. // Open a transaction to the database
  3537. var transaction = this.db.transaction(["versions"], "readwrite");
  3538. // the transaction could abort because of a QuotaExceededError error
  3539. transaction.onabort = function (event) {
  3540. try {
  3541. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3542. _this.hasReachedQuota = true;
  3543. }
  3544. }
  3545. catch (ex) { }
  3546. callback(-1);
  3547. };
  3548. transaction.oncomplete = function (event) {
  3549. callback(_this.manifestVersionFound);
  3550. };
  3551. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3552. // Put the scene into the database
  3553. var addRequest = transaction.objectStore("versions").put(newVersion);
  3554. addRequest.onsuccess = function (event) {
  3555. };
  3556. addRequest.onerror = function (event) {
  3557. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3558. };
  3559. }
  3560. catch (ex) {
  3561. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3562. callback(-1);
  3563. }
  3564. }
  3565. else {
  3566. callback(-1);
  3567. }
  3568. };
  3569. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3570. var _this = this;
  3571. var completeUrl = Database.ReturnFullUrlLocation(url);
  3572. var saveAndLoadFile = function (event) {
  3573. // the scene is not yet in the DB, let's try to save it
  3574. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3575. };
  3576. this._checkVersionFromDB(completeUrl, function (version) {
  3577. if (version !== -1) {
  3578. if (!_this.mustUpdateRessources) {
  3579. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3580. }
  3581. else {
  3582. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3583. }
  3584. }
  3585. else {
  3586. errorCallback();
  3587. }
  3588. });
  3589. };
  3590. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3591. if (this.isSupported) {
  3592. var targetStore;
  3593. if (url.indexOf(".babylon") !== -1) {
  3594. targetStore = "scenes";
  3595. }
  3596. else {
  3597. targetStore = "textures";
  3598. }
  3599. var file;
  3600. var transaction = this.db.transaction([targetStore]);
  3601. transaction.oncomplete = function (event) {
  3602. if (file) {
  3603. callback(file.data);
  3604. }
  3605. else {
  3606. notInDBCallback();
  3607. }
  3608. };
  3609. transaction.onabort = function (event) {
  3610. notInDBCallback();
  3611. };
  3612. var getRequest = transaction.objectStore(targetStore).get(url);
  3613. getRequest.onsuccess = function (event) {
  3614. file = (event.target).result;
  3615. };
  3616. getRequest.onerror = function (event) {
  3617. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3618. notInDBCallback();
  3619. };
  3620. }
  3621. else {
  3622. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3623. callback();
  3624. }
  3625. };
  3626. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3627. var _this = this;
  3628. if (this.isSupported) {
  3629. var targetStore;
  3630. if (url.indexOf(".babylon") !== -1) {
  3631. targetStore = "scenes";
  3632. }
  3633. else {
  3634. targetStore = "textures";
  3635. }
  3636. // Create XHR
  3637. var xhr = new XMLHttpRequest(), fileData;
  3638. xhr.open("GET", url, true);
  3639. if (useArrayBuffer) {
  3640. xhr.responseType = "arraybuffer";
  3641. }
  3642. xhr.onprogress = progressCallback;
  3643. xhr.addEventListener("load", function () {
  3644. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3645. // Blob as response (XHR2)
  3646. //fileData = xhr.responseText;
  3647. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3648. if (!_this.hasReachedQuota) {
  3649. // Open a transaction to the database
  3650. var transaction = _this.db.transaction([targetStore], "readwrite");
  3651. // the transaction could abort because of a QuotaExceededError error
  3652. transaction.onabort = function (event) {
  3653. try {
  3654. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3655. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3656. this.hasReachedQuota = true;
  3657. }
  3658. }
  3659. catch (ex) { }
  3660. callback(fileData);
  3661. };
  3662. transaction.oncomplete = function (event) {
  3663. callback(fileData);
  3664. };
  3665. var newFile;
  3666. if (targetStore === "scenes") {
  3667. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3668. }
  3669. else {
  3670. newFile = { textureUrl: url, data: fileData };
  3671. }
  3672. try {
  3673. // Put the scene into the database
  3674. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3675. addRequest.onsuccess = function (event) {
  3676. };
  3677. addRequest.onerror = function (event) {
  3678. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3679. };
  3680. }
  3681. catch (ex) {
  3682. callback(fileData);
  3683. }
  3684. }
  3685. else {
  3686. callback(fileData);
  3687. }
  3688. }
  3689. else {
  3690. callback();
  3691. }
  3692. }, false);
  3693. xhr.addEventListener("error", function (event) {
  3694. BABYLON.Tools.Error("error on XHR request.");
  3695. callback();
  3696. }, false);
  3697. xhr.send();
  3698. }
  3699. else {
  3700. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3701. callback();
  3702. }
  3703. };
  3704. Database.IsUASupportingBlobStorage = true;
  3705. Database.IDBStorageEnabled = true;
  3706. Database.parseURL = function (url) {
  3707. var a = document.createElement('a');
  3708. a.href = url;
  3709. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3710. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3711. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3712. return absLocation;
  3713. };
  3714. Database.ReturnFullUrlLocation = function (url) {
  3715. if (url.indexOf("http:/") === -1) {
  3716. return (Database.parseURL(window.location.href) + url);
  3717. }
  3718. else {
  3719. return url;
  3720. }
  3721. };
  3722. return Database;
  3723. })();
  3724. BABYLON.Database = Database;
  3725. })(BABYLON || (BABYLON = {}));
  3726. var BABYLON;
  3727. (function (BABYLON) {
  3728. var Internals;
  3729. (function (Internals) {
  3730. /*
  3731. * Based on jsTGALoader - Javascript loader for TGA file
  3732. * By Vincent Thibault
  3733. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3734. */
  3735. var TGATools = (function () {
  3736. function TGATools() {
  3737. }
  3738. TGATools.GetTGAHeader = function (data) {
  3739. var offset = 0;
  3740. var header = {
  3741. id_length: data[offset++],
  3742. colormap_type: data[offset++],
  3743. image_type: data[offset++],
  3744. colormap_index: data[offset++] | data[offset++] << 8,
  3745. colormap_length: data[offset++] | data[offset++] << 8,
  3746. colormap_size: data[offset++],
  3747. origin: [
  3748. data[offset++] | data[offset++] << 8,
  3749. data[offset++] | data[offset++] << 8
  3750. ],
  3751. width: data[offset++] | data[offset++] << 8,
  3752. height: data[offset++] | data[offset++] << 8,
  3753. pixel_size: data[offset++],
  3754. flags: data[offset++]
  3755. };
  3756. return header;
  3757. };
  3758. TGATools.UploadContent = function (gl, data) {
  3759. // Not enough data to contain header ?
  3760. if (data.length < 19) {
  3761. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3762. return;
  3763. }
  3764. // Read Header
  3765. var offset = 18;
  3766. var header = TGATools.GetTGAHeader(data);
  3767. // Assume it's a valid Targa file.
  3768. if (header.id_length + offset > data.length) {
  3769. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3770. return;
  3771. }
  3772. // Skip not needed data
  3773. offset += header.id_length;
  3774. var use_rle = false;
  3775. var use_pal = false;
  3776. var use_rgb = false;
  3777. var use_grey = false;
  3778. // Get some informations.
  3779. switch (header.image_type) {
  3780. case TGATools._TYPE_RLE_INDEXED:
  3781. use_rle = true;
  3782. case TGATools._TYPE_INDEXED:
  3783. use_pal = true;
  3784. break;
  3785. case TGATools._TYPE_RLE_RGB:
  3786. use_rle = true;
  3787. case TGATools._TYPE_RGB:
  3788. use_rgb = true;
  3789. break;
  3790. case TGATools._TYPE_RLE_GREY:
  3791. use_rle = true;
  3792. case TGATools._TYPE_GREY:
  3793. use_grey = true;
  3794. break;
  3795. }
  3796. var pixel_data;
  3797. var numAlphaBits = header.flags & 0xf;
  3798. var pixel_size = header.pixel_size >> 3;
  3799. var pixel_total = header.width * header.height * pixel_size;
  3800. // Read palettes
  3801. var palettes;
  3802. if (use_pal) {
  3803. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3804. }
  3805. // Read LRE
  3806. if (use_rle) {
  3807. pixel_data = new Uint8Array(pixel_total);
  3808. var c, count, i;
  3809. var localOffset = 0;
  3810. var pixels = new Uint8Array(pixel_size);
  3811. while (offset < pixel_total && localOffset < pixel_total) {
  3812. c = data[offset++];
  3813. count = (c & 0x7f) + 1;
  3814. // RLE pixels
  3815. if (c & 0x80) {
  3816. // Bind pixel tmp array
  3817. for (i = 0; i < pixel_size; ++i) {
  3818. pixels[i] = data[offset++];
  3819. }
  3820. // Copy pixel array
  3821. for (i = 0; i < count; ++i) {
  3822. pixel_data.set(pixels, localOffset + i * pixel_size);
  3823. }
  3824. localOffset += pixel_size * count;
  3825. }
  3826. else {
  3827. count *= pixel_size;
  3828. for (i = 0; i < count; ++i) {
  3829. pixel_data[localOffset + i] = data[offset++];
  3830. }
  3831. localOffset += count;
  3832. }
  3833. }
  3834. }
  3835. else {
  3836. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3837. }
  3838. // Load to texture
  3839. var x_start, y_start, x_step, y_step, y_end, x_end;
  3840. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3841. default:
  3842. case TGATools._ORIGIN_UL:
  3843. x_start = 0;
  3844. x_step = 1;
  3845. x_end = header.width;
  3846. y_start = 0;
  3847. y_step = 1;
  3848. y_end = header.height;
  3849. break;
  3850. case TGATools._ORIGIN_BL:
  3851. x_start = 0;
  3852. x_step = 1;
  3853. x_end = header.width;
  3854. y_start = header.height - 1;
  3855. y_step = -1;
  3856. y_end = -1;
  3857. break;
  3858. case TGATools._ORIGIN_UR:
  3859. x_start = header.width - 1;
  3860. x_step = -1;
  3861. x_end = -1;
  3862. y_start = 0;
  3863. y_step = 1;
  3864. y_end = header.height;
  3865. break;
  3866. case TGATools._ORIGIN_BR:
  3867. x_start = header.width - 1;
  3868. x_step = -1;
  3869. x_end = -1;
  3870. y_start = header.height - 1;
  3871. y_step = -1;
  3872. y_end = -1;
  3873. break;
  3874. }
  3875. // Load the specify method
  3876. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3877. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3878. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3879. };
  3880. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3881. var image = pixel_data, colormap = palettes;
  3882. var width = header.width, height = header.height;
  3883. var color, i = 0, x, y;
  3884. var imageData = new Uint8Array(width * height * 4);
  3885. for (y = y_start; y !== y_end; y += y_step) {
  3886. for (x = x_start; x !== x_end; x += x_step, i++) {
  3887. color = image[i];
  3888. imageData[(x + width * y) * 4 + 3] = 255;
  3889. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3890. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3891. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3892. }
  3893. }
  3894. return imageData;
  3895. };
  3896. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3897. var image = pixel_data;
  3898. var width = header.width, height = header.height;
  3899. var color, i = 0, x, y;
  3900. var imageData = new Uint8Array(width * height * 4);
  3901. for (y = y_start; y !== y_end; y += y_step) {
  3902. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3903. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3904. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3905. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3906. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3907. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3908. }
  3909. }
  3910. return imageData;
  3911. };
  3912. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3913. var image = pixel_data;
  3914. var width = header.width, height = header.height;
  3915. var i = 0, x, y;
  3916. var imageData = new Uint8Array(width * height * 4);
  3917. for (y = y_start; y !== y_end; y += y_step) {
  3918. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3919. imageData[(x + width * y) * 4 + 3] = 255;
  3920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3923. }
  3924. }
  3925. return imageData;
  3926. };
  3927. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3928. var image = pixel_data;
  3929. var width = header.width, height = header.height;
  3930. var i = 0, x, y;
  3931. var imageData = new Uint8Array(width * height * 4);
  3932. for (y = y_start; y !== y_end; y += y_step) {
  3933. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3934. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3935. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3936. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3937. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3938. }
  3939. }
  3940. return imageData;
  3941. };
  3942. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3943. var image = pixel_data;
  3944. var width = header.width, height = header.height;
  3945. var color, i = 0, x, y;
  3946. var imageData = new Uint8Array(width * height * 4);
  3947. for (y = y_start; y !== y_end; y += y_step) {
  3948. for (x = x_start; x !== x_end; x += x_step, i++) {
  3949. color = image[i];
  3950. imageData[(x + width * y) * 4 + 0] = color;
  3951. imageData[(x + width * y) * 4 + 1] = color;
  3952. imageData[(x + width * y) * 4 + 2] = color;
  3953. imageData[(x + width * y) * 4 + 3] = 255;
  3954. }
  3955. }
  3956. return imageData;
  3957. };
  3958. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3959. var image = pixel_data;
  3960. var width = header.width, height = header.height;
  3961. var i = 0, x, y;
  3962. var imageData = new Uint8Array(width * height * 4);
  3963. for (y = y_start; y !== y_end; y += y_step) {
  3964. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3965. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3966. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3967. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3968. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3969. }
  3970. }
  3971. return imageData;
  3972. };
  3973. TGATools._TYPE_NO_DATA = 0;
  3974. TGATools._TYPE_INDEXED = 1;
  3975. TGATools._TYPE_RGB = 2;
  3976. TGATools._TYPE_GREY = 3;
  3977. TGATools._TYPE_RLE_INDEXED = 9;
  3978. TGATools._TYPE_RLE_RGB = 10;
  3979. TGATools._TYPE_RLE_GREY = 11;
  3980. TGATools._ORIGIN_MASK = 0x30;
  3981. TGATools._ORIGIN_SHIFT = 0x04;
  3982. TGATools._ORIGIN_BL = 0x00;
  3983. TGATools._ORIGIN_BR = 0x01;
  3984. TGATools._ORIGIN_UL = 0x02;
  3985. TGATools._ORIGIN_UR = 0x03;
  3986. return TGATools;
  3987. })();
  3988. Internals.TGATools = TGATools;
  3989. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3990. })(BABYLON || (BABYLON = {}));
  3991. var BABYLON;
  3992. (function (BABYLON) {
  3993. var SmartArray = (function () {
  3994. function SmartArray(capacity) {
  3995. this.length = 0;
  3996. this._duplicateId = 0;
  3997. this.data = new Array(capacity);
  3998. this._id = SmartArray._GlobalId++;
  3999. }
  4000. SmartArray.prototype.push = function (value) {
  4001. this.data[this.length++] = value;
  4002. if (this.length > this.data.length) {
  4003. this.data.length *= 2;
  4004. }
  4005. if (!value.__smartArrayFlags) {
  4006. value.__smartArrayFlags = {};
  4007. }
  4008. value.__smartArrayFlags[this._id] = this._duplicateId;
  4009. };
  4010. SmartArray.prototype.pushNoDuplicate = function (value) {
  4011. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4012. return;
  4013. }
  4014. this.push(value);
  4015. };
  4016. SmartArray.prototype.sort = function (compareFn) {
  4017. this.data.sort(compareFn);
  4018. };
  4019. SmartArray.prototype.reset = function () {
  4020. this.length = 0;
  4021. this._duplicateId++;
  4022. };
  4023. SmartArray.prototype.concat = function (array) {
  4024. if (array.length === 0) {
  4025. return;
  4026. }
  4027. if (this.length + array.length > this.data.length) {
  4028. this.data.length = (this.length + array.length) * 2;
  4029. }
  4030. for (var index = 0; index < array.length; index++) {
  4031. this.data[this.length++] = (array.data || array)[index];
  4032. }
  4033. };
  4034. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4035. if (array.length === 0) {
  4036. return;
  4037. }
  4038. if (this.length + array.length > this.data.length) {
  4039. this.data.length = (this.length + array.length) * 2;
  4040. }
  4041. for (var index = 0; index < array.length; index++) {
  4042. var item = (array.data || array)[index];
  4043. this.pushNoDuplicate(item);
  4044. }
  4045. };
  4046. SmartArray.prototype.indexOf = function (value) {
  4047. var position = this.data.indexOf(value);
  4048. if (position >= this.length) {
  4049. return -1;
  4050. }
  4051. return position;
  4052. };
  4053. // Statics
  4054. SmartArray._GlobalId = 0;
  4055. return SmartArray;
  4056. })();
  4057. BABYLON.SmartArray = SmartArray;
  4058. })(BABYLON || (BABYLON = {}));
  4059. var BABYLON;
  4060. (function (BABYLON) {
  4061. var SmartCollection = (function () {
  4062. function SmartCollection(capacity) {
  4063. if (capacity === void 0) { capacity = 10; }
  4064. this.count = 0;
  4065. this._initialCapacity = capacity;
  4066. this.items = {};
  4067. this._keys = new Array(this._initialCapacity);
  4068. }
  4069. SmartCollection.prototype.add = function (key, item) {
  4070. if (this.items[key] != undefined) {
  4071. return -1;
  4072. }
  4073. this.items[key] = item;
  4074. //literal keys are always strings, but we keep source type of key in _keys array
  4075. this._keys[this.count++] = key;
  4076. if (this.count > this._keys.length) {
  4077. this._keys.length *= 2;
  4078. }
  4079. return this.count;
  4080. };
  4081. SmartCollection.prototype.remove = function (key) {
  4082. if (this.items[key] == undefined) {
  4083. return -1;
  4084. }
  4085. return this.removeItemOfIndex(this.indexOf(key));
  4086. };
  4087. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4088. if (index < this.count && index > -1) {
  4089. delete this.items[this._keys[index]];
  4090. //here, shifting by hand is better optimised than .splice
  4091. while (index < this.count) {
  4092. this._keys[index] = this._keys[index + 1];
  4093. index++;
  4094. }
  4095. }
  4096. else {
  4097. return -1;
  4098. }
  4099. return --this.count;
  4100. };
  4101. SmartCollection.prototype.indexOf = function (key) {
  4102. for (var i = 0; i !== this.count; i++) {
  4103. if (this._keys[i] === key) {
  4104. return i;
  4105. }
  4106. }
  4107. return -1;
  4108. };
  4109. SmartCollection.prototype.item = function (key) {
  4110. return this.items[key];
  4111. };
  4112. SmartCollection.prototype.getAllKeys = function () {
  4113. if (this.count > 0) {
  4114. var keys = new Array(this.count);
  4115. for (var i = 0; i < this.count; i++) {
  4116. keys[i] = this._keys[i];
  4117. }
  4118. return keys;
  4119. }
  4120. else {
  4121. return undefined;
  4122. }
  4123. };
  4124. SmartCollection.prototype.getKeyByIndex = function (index) {
  4125. if (index < this.count && index > -1) {
  4126. return this._keys[index];
  4127. }
  4128. else {
  4129. return undefined;
  4130. }
  4131. };
  4132. SmartCollection.prototype.getItemByIndex = function (index) {
  4133. if (index < this.count && index > -1) {
  4134. return this.items[this._keys[index]];
  4135. }
  4136. else {
  4137. return undefined;
  4138. }
  4139. };
  4140. SmartCollection.prototype.empty = function () {
  4141. if (this.count > 0) {
  4142. this.count = 0;
  4143. this.items = {};
  4144. this._keys = new Array(this._initialCapacity);
  4145. }
  4146. };
  4147. SmartCollection.prototype.forEach = function (block) {
  4148. var key;
  4149. for (key in this.items) {
  4150. if (this.items.hasOwnProperty(key)) {
  4151. block(this.items[key]);
  4152. }
  4153. }
  4154. };
  4155. return SmartCollection;
  4156. })();
  4157. BABYLON.SmartCollection = SmartCollection;
  4158. })(BABYLON || (BABYLON = {}));
  4159. var BABYLON;
  4160. (function (BABYLON) {
  4161. // Screenshots
  4162. var screenshotCanvas;
  4163. var cloneValue = function (source, destinationObject) {
  4164. if (!source)
  4165. return null;
  4166. if (source instanceof BABYLON.Mesh) {
  4167. return null;
  4168. }
  4169. if (source instanceof BABYLON.SubMesh) {
  4170. return source.clone(destinationObject);
  4171. }
  4172. else if (source.clone) {
  4173. return source.clone();
  4174. }
  4175. return null;
  4176. };
  4177. var Tools = (function () {
  4178. function Tools() {
  4179. }
  4180. Tools.Instantiate = function (className) {
  4181. var arr = className.split(".");
  4182. var fn = (window || this);
  4183. for (var i = 0, len = arr.length; i < len; i++) {
  4184. fn = fn[arr[i]];
  4185. }
  4186. if (typeof fn !== "function") {
  4187. return null;
  4188. }
  4189. return fn;
  4190. };
  4191. Tools.ToHex = function (i) {
  4192. var str = i.toString(16);
  4193. if (i <= 15) {
  4194. return ("0" + str).toUpperCase();
  4195. }
  4196. return str.toUpperCase();
  4197. };
  4198. Tools.SetImmediate = function (action) {
  4199. if (window.setImmediate) {
  4200. window.setImmediate(action);
  4201. }
  4202. else {
  4203. setTimeout(action, 1);
  4204. }
  4205. };
  4206. Tools.IsExponentOfTwo = function (value) {
  4207. var count = 1;
  4208. do {
  4209. count *= 2;
  4210. } while (count < value);
  4211. return count === value;
  4212. };
  4213. Tools.GetExponentOfTwo = function (value, max) {
  4214. var count = 1;
  4215. do {
  4216. count *= 2;
  4217. } while (count < value);
  4218. if (count > max)
  4219. count = max;
  4220. return count;
  4221. };
  4222. Tools.GetFilename = function (path) {
  4223. var index = path.lastIndexOf("/");
  4224. if (index < 0)
  4225. return path;
  4226. return path.substring(index + 1);
  4227. };
  4228. Tools.GetDOMTextContent = function (element) {
  4229. var result = "";
  4230. var child = element.firstChild;
  4231. while (child) {
  4232. if (child.nodeType === 3) {
  4233. result += child.textContent;
  4234. }
  4235. child = child.nextSibling;
  4236. }
  4237. return result;
  4238. };
  4239. Tools.ToDegrees = function (angle) {
  4240. return angle * 180 / Math.PI;
  4241. };
  4242. Tools.ToRadians = function (angle) {
  4243. return angle * Math.PI / 180;
  4244. };
  4245. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4246. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4247. var output = "";
  4248. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4249. var i = 0;
  4250. var bytes = new Uint8Array(buffer);
  4251. while (i < bytes.length) {
  4252. chr1 = bytes[i++];
  4253. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4254. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4255. enc1 = chr1 >> 2;
  4256. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4257. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4258. enc4 = chr3 & 63;
  4259. if (isNaN(chr2)) {
  4260. enc3 = enc4 = 64;
  4261. }
  4262. else if (isNaN(chr3)) {
  4263. enc4 = 64;
  4264. }
  4265. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4266. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4267. }
  4268. return "data:image/png;base64," + output;
  4269. };
  4270. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4271. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4272. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4273. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4274. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4275. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4276. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4277. }
  4278. return {
  4279. minimum: minimum,
  4280. maximum: maximum
  4281. };
  4282. };
  4283. Tools.ExtractMinAndMax = function (positions, start, count) {
  4284. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4285. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4286. for (var index = start; index < start + count; index++) {
  4287. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4288. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4289. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4290. }
  4291. return {
  4292. minimum: minimum,
  4293. maximum: maximum
  4294. };
  4295. };
  4296. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4297. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4298. return undefined;
  4299. return Array.isArray(obj) ? obj : [obj];
  4300. };
  4301. // Misc.
  4302. Tools.GetPointerPrefix = function () {
  4303. var eventPrefix = "pointer";
  4304. // Check if pointer events are supported
  4305. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4306. eventPrefix = "mouse";
  4307. }
  4308. return eventPrefix;
  4309. };
  4310. Tools.QueueNewFrame = function (func) {
  4311. if (window.requestAnimationFrame)
  4312. window.requestAnimationFrame(func);
  4313. else if (window.msRequestAnimationFrame)
  4314. window.msRequestAnimationFrame(func);
  4315. else if (window.webkitRequestAnimationFrame)
  4316. window.webkitRequestAnimationFrame(func);
  4317. else if (window.mozRequestAnimationFrame)
  4318. window.mozRequestAnimationFrame(func);
  4319. else if (window.oRequestAnimationFrame)
  4320. window.oRequestAnimationFrame(func);
  4321. else {
  4322. window.setTimeout(func, 16);
  4323. }
  4324. };
  4325. Tools.RequestFullscreen = function (element) {
  4326. if (element.requestFullscreen)
  4327. element.requestFullscreen();
  4328. else if (element.msRequestFullscreen)
  4329. element.msRequestFullscreen();
  4330. else if (element.webkitRequestFullscreen)
  4331. element.webkitRequestFullscreen();
  4332. else if (element.mozRequestFullScreen)
  4333. element.mozRequestFullScreen();
  4334. };
  4335. Tools.ExitFullscreen = function () {
  4336. if (document.exitFullscreen) {
  4337. document.exitFullscreen();
  4338. }
  4339. else if (document.mozCancelFullScreen) {
  4340. document.mozCancelFullScreen();
  4341. }
  4342. else if (document.webkitCancelFullScreen) {
  4343. document.webkitCancelFullScreen();
  4344. }
  4345. else if (document.msCancelFullScreen) {
  4346. document.msCancelFullScreen();
  4347. }
  4348. };
  4349. // External files
  4350. Tools.CleanUrl = function (url) {
  4351. url = url.replace(/#/mg, "%23");
  4352. return url;
  4353. };
  4354. Tools.LoadImage = function (url, onload, onerror, database) {
  4355. if (url instanceof ArrayBuffer) {
  4356. url = Tools.EncodeArrayBufferTobase64(url);
  4357. }
  4358. url = Tools.CleanUrl(url);
  4359. var img = new Image();
  4360. if (url.substr(0, 5) !== "data:") {
  4361. if (Tools.CorsBehavior) {
  4362. switch (typeof (Tools.CorsBehavior)) {
  4363. case "function":
  4364. var result = Tools.CorsBehavior(url);
  4365. if (result) {
  4366. img.crossOrigin = result;
  4367. }
  4368. break;
  4369. case "string":
  4370. default:
  4371. img.crossOrigin = Tools.CorsBehavior;
  4372. break;
  4373. }
  4374. }
  4375. }
  4376. img.onload = function () {
  4377. onload(img);
  4378. };
  4379. img.onerror = function (err) {
  4380. Tools.Error("Error while trying to load texture: " + url);
  4381. if (Tools.UseFallbackTexture) {
  4382. 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";
  4383. onload(img);
  4384. }
  4385. else {
  4386. onerror();
  4387. }
  4388. };
  4389. var noIndexedDB = function () {
  4390. img.src = url;
  4391. };
  4392. var loadFromIndexedDB = function () {
  4393. database.loadImageFromDB(url, img);
  4394. };
  4395. //ANY database to do!
  4396. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4397. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4398. }
  4399. else {
  4400. if (url.indexOf("file:") === -1) {
  4401. noIndexedDB();
  4402. }
  4403. else {
  4404. try {
  4405. var textureName = url.substring(5);
  4406. var blobURL;
  4407. try {
  4408. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4409. }
  4410. catch (ex) {
  4411. // Chrome doesn't support oneTimeOnly parameter
  4412. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4413. }
  4414. img.src = blobURL;
  4415. }
  4416. catch (e) {
  4417. img.src = null;
  4418. }
  4419. }
  4420. }
  4421. return img;
  4422. };
  4423. //ANY
  4424. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4425. url = Tools.CleanUrl(url);
  4426. var noIndexedDB = function () {
  4427. var request = new XMLHttpRequest();
  4428. var loadUrl = Tools.BaseUrl + url;
  4429. request.open('GET', loadUrl, true);
  4430. if (useArrayBuffer) {
  4431. request.responseType = "arraybuffer";
  4432. }
  4433. request.onprogress = progressCallBack;
  4434. request.onreadystatechange = function () {
  4435. if (request.readyState === 4) {
  4436. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4437. callback(!useArrayBuffer ? request.responseText : request.response);
  4438. }
  4439. else {
  4440. if (onError) {
  4441. onError();
  4442. }
  4443. else {
  4444. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4445. }
  4446. }
  4447. }
  4448. };
  4449. request.send(null);
  4450. };
  4451. var loadFromIndexedDB = function () {
  4452. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4453. };
  4454. if (url.indexOf("file:") !== -1) {
  4455. var fileName = url.substring(5);
  4456. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4457. }
  4458. else {
  4459. // Caching all files
  4460. if (database && database.enableSceneOffline) {
  4461. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4462. }
  4463. else {
  4464. noIndexedDB();
  4465. }
  4466. }
  4467. };
  4468. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4469. var reader = new FileReader();
  4470. reader.onload = function (e) {
  4471. //target doesn't have result from ts 1.3
  4472. callback(e.target['result']);
  4473. };
  4474. reader.onprogress = progressCallback;
  4475. reader.readAsDataURL(fileToLoad);
  4476. };
  4477. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4478. var reader = new FileReader();
  4479. reader.onerror = function (e) {
  4480. Tools.Log("Error while reading file: " + fileToLoad.name);
  4481. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4482. };
  4483. reader.onload = function (e) {
  4484. //target doesn't have result from ts 1.3
  4485. callback(e.target['result']);
  4486. };
  4487. reader.onprogress = progressCallBack;
  4488. if (!useArrayBuffer) {
  4489. // Asynchronous read
  4490. reader.readAsText(fileToLoad);
  4491. }
  4492. else {
  4493. reader.readAsArrayBuffer(fileToLoad);
  4494. }
  4495. };
  4496. //returns a downloadable url to a file content.
  4497. Tools.FileAsURL = function (content) {
  4498. var fileBlob = new Blob([content]);
  4499. var url = window.URL || window.webkitURL;
  4500. var link = url.createObjectURL(fileBlob);
  4501. return link;
  4502. };
  4503. // Misc.
  4504. Tools.Clamp = function (value, min, max) {
  4505. if (min === void 0) { min = 0; }
  4506. if (max === void 0) { max = 1; }
  4507. return Math.min(max, Math.max(min, value));
  4508. };
  4509. // Returns -1 when value is a negative number and
  4510. // +1 when value is a positive number.
  4511. Tools.Sign = function (value) {
  4512. value = +value; // convert to a number
  4513. if (value === 0 || isNaN(value))
  4514. return value;
  4515. return value > 0 ? 1 : -1;
  4516. };
  4517. Tools.Format = function (value, decimals) {
  4518. if (decimals === void 0) { decimals = 2; }
  4519. return value.toFixed(decimals);
  4520. };
  4521. Tools.CheckExtends = function (v, min, max) {
  4522. if (v.x < min.x)
  4523. min.x = v.x;
  4524. if (v.y < min.y)
  4525. min.y = v.y;
  4526. if (v.z < min.z)
  4527. min.z = v.z;
  4528. if (v.x > max.x)
  4529. max.x = v.x;
  4530. if (v.y > max.y)
  4531. max.y = v.y;
  4532. if (v.z > max.z)
  4533. max.z = v.z;
  4534. };
  4535. Tools.WithinEpsilon = function (a, b, epsilon) {
  4536. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4537. var num = a - b;
  4538. return -epsilon <= num && num <= epsilon;
  4539. };
  4540. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4541. for (var prop in source) {
  4542. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4543. continue;
  4544. }
  4545. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4546. continue;
  4547. }
  4548. var sourceValue = source[prop];
  4549. var typeOfSourceValue = typeof sourceValue;
  4550. if (typeOfSourceValue === "function") {
  4551. continue;
  4552. }
  4553. if (typeOfSourceValue === "object") {
  4554. if (sourceValue instanceof Array) {
  4555. destination[prop] = [];
  4556. if (sourceValue.length > 0) {
  4557. if (typeof sourceValue[0] == "object") {
  4558. for (var index = 0; index < sourceValue.length; index++) {
  4559. var clonedValue = cloneValue(sourceValue[index], destination);
  4560. if (destination[prop].indexOf(clonedValue) === -1) {
  4561. destination[prop].push(clonedValue);
  4562. }
  4563. }
  4564. }
  4565. else {
  4566. destination[prop] = sourceValue.slice(0);
  4567. }
  4568. }
  4569. }
  4570. else {
  4571. destination[prop] = cloneValue(sourceValue, destination);
  4572. }
  4573. }
  4574. else {
  4575. destination[prop] = sourceValue;
  4576. }
  4577. }
  4578. };
  4579. Tools.IsEmpty = function (obj) {
  4580. for (var i in obj) {
  4581. return false;
  4582. }
  4583. return true;
  4584. };
  4585. Tools.RegisterTopRootEvents = function (events) {
  4586. for (var index = 0; index < events.length; index++) {
  4587. var event = events[index];
  4588. window.addEventListener(event.name, event.handler, false);
  4589. try {
  4590. if (window.parent) {
  4591. window.parent.addEventListener(event.name, event.handler, false);
  4592. }
  4593. }
  4594. catch (e) {
  4595. }
  4596. }
  4597. };
  4598. Tools.UnregisterTopRootEvents = function (events) {
  4599. for (var index = 0; index < events.length; index++) {
  4600. var event = events[index];
  4601. window.removeEventListener(event.name, event.handler);
  4602. try {
  4603. if (window.parent) {
  4604. window.parent.removeEventListener(event.name, event.handler);
  4605. }
  4606. }
  4607. catch (e) {
  4608. }
  4609. }
  4610. };
  4611. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4612. // Read the contents of the framebuffer
  4613. var numberOfChannelsByLine = width * 4;
  4614. var halfHeight = height / 2;
  4615. //Reading datas from WebGL
  4616. var data = engine.readPixels(0, 0, width, height);
  4617. //To flip image on Y axis.
  4618. for (var i = 0; i < halfHeight; i++) {
  4619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4620. var currentCell = j + i * numberOfChannelsByLine;
  4621. var targetLine = height - i - 1;
  4622. var targetCell = j + targetLine * numberOfChannelsByLine;
  4623. var temp = data[currentCell];
  4624. data[currentCell] = data[targetCell];
  4625. data[targetCell] = temp;
  4626. }
  4627. }
  4628. // Create a 2D canvas to store the result
  4629. if (!screenshotCanvas) {
  4630. screenshotCanvas = document.createElement('canvas');
  4631. }
  4632. screenshotCanvas.width = width;
  4633. screenshotCanvas.height = height;
  4634. var context = screenshotCanvas.getContext('2d');
  4635. // Copy the pixels to a 2D canvas
  4636. var imageData = context.createImageData(width, height);
  4637. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4638. var castData = imageData.data;
  4639. castData.set(data);
  4640. context.putImageData(imageData, 0, 0);
  4641. var base64Image = screenshotCanvas.toDataURL();
  4642. if (successCallback) {
  4643. successCallback(base64Image);
  4644. }
  4645. else {
  4646. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4647. if (("download" in document.createElement("a"))) {
  4648. var a = window.document.createElement("a");
  4649. a.href = base64Image;
  4650. var date = new Date();
  4651. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4652. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4653. window.document.body.appendChild(a);
  4654. a.addEventListener("click", function () {
  4655. a.parentElement.removeChild(a);
  4656. });
  4657. a.click();
  4658. }
  4659. else {
  4660. var newWindow = window.open("");
  4661. var img = newWindow.document.createElement("img");
  4662. img.src = base64Image;
  4663. newWindow.document.body.appendChild(img);
  4664. }
  4665. }
  4666. };
  4667. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4668. var width;
  4669. var height;
  4670. //If a precision value is specified
  4671. if (size.precision) {
  4672. width = Math.round(engine.getRenderWidth() * size.precision);
  4673. height = Math.round(width / engine.getAspectRatio(camera));
  4674. size = { width: width, height: height };
  4675. }
  4676. else if (size.width && size.height) {
  4677. width = size.width;
  4678. height = size.height;
  4679. }
  4680. else if (size.width && !size.height) {
  4681. width = size.width;
  4682. height = Math.round(width / engine.getAspectRatio(camera));
  4683. size = { width: width, height: height };
  4684. }
  4685. else if (size.height && !size.width) {
  4686. height = size.height;
  4687. width = Math.round(height * engine.getAspectRatio(camera));
  4688. size = { width: width, height: height };
  4689. }
  4690. else if (!isNaN(size)) {
  4691. height = size;
  4692. width = size;
  4693. }
  4694. else {
  4695. Tools.Error("Invalid 'size' parameter !");
  4696. return;
  4697. }
  4698. var scene = camera.getScene();
  4699. var previousCamera = null;
  4700. if (scene.activeCamera !== camera) {
  4701. previousCamera = scene.activeCamera;
  4702. scene.activeCamera = camera;
  4703. }
  4704. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4705. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4706. texture.renderList = scene.meshes;
  4707. texture.onAfterRender = function () {
  4708. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4709. };
  4710. scene.incrementRenderId();
  4711. texture.render(true);
  4712. texture.dispose();
  4713. if (previousCamera) {
  4714. scene.activeCamera = previousCamera;
  4715. }
  4716. camera.getProjectionMatrix(true); // Force cache refresh;
  4717. };
  4718. // XHR response validator for local file scenario
  4719. Tools.ValidateXHRData = function (xhr, dataType) {
  4720. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4721. if (dataType === void 0) { dataType = 7; }
  4722. try {
  4723. if (dataType & 1) {
  4724. if (xhr.responseText && xhr.responseText.length > 0) {
  4725. return true;
  4726. }
  4727. else if (dataType === 1) {
  4728. return false;
  4729. }
  4730. }
  4731. if (dataType & 2) {
  4732. // Check header width and height since there is no "TGA" magic number
  4733. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4734. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4735. return true;
  4736. }
  4737. else if (dataType === 2) {
  4738. return false;
  4739. }
  4740. }
  4741. if (dataType & 4) {
  4742. // Check for the "DDS" magic number
  4743. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4744. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4745. return true;
  4746. }
  4747. else {
  4748. return false;
  4749. }
  4750. }
  4751. }
  4752. catch (e) {
  4753. }
  4754. return false;
  4755. };
  4756. Object.defineProperty(Tools, "NoneLogLevel", {
  4757. get: function () {
  4758. return Tools._NoneLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "MessageLogLevel", {
  4764. get: function () {
  4765. return Tools._MessageLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "WarningLogLevel", {
  4771. get: function () {
  4772. return Tools._WarningLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Object.defineProperty(Tools, "ErrorLogLevel", {
  4778. get: function () {
  4779. return Tools._ErrorLogLevel;
  4780. },
  4781. enumerable: true,
  4782. configurable: true
  4783. });
  4784. Object.defineProperty(Tools, "AllLogLevel", {
  4785. get: function () {
  4786. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4787. },
  4788. enumerable: true,
  4789. configurable: true
  4790. });
  4791. Tools._AddLogEntry = function (entry) {
  4792. Tools._LogCache = entry + Tools._LogCache;
  4793. if (Tools.OnNewCacheEntry) {
  4794. Tools.OnNewCacheEntry(entry);
  4795. }
  4796. };
  4797. Tools._FormatMessage = function (message) {
  4798. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4799. var date = new Date();
  4800. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4801. };
  4802. Tools._LogDisabled = function (message) {
  4803. // nothing to do
  4804. };
  4805. Tools._LogEnabled = function (message) {
  4806. var formattedMessage = Tools._FormatMessage(message);
  4807. console.log("BJS - " + formattedMessage);
  4808. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4809. Tools._AddLogEntry(entry);
  4810. };
  4811. Tools._WarnDisabled = function (message) {
  4812. // nothing to do
  4813. };
  4814. Tools._WarnEnabled = function (message) {
  4815. var formattedMessage = Tools._FormatMessage(message);
  4816. console.warn("BJS - " + formattedMessage);
  4817. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4818. Tools._AddLogEntry(entry);
  4819. };
  4820. Tools._ErrorDisabled = function (message) {
  4821. // nothing to do
  4822. };
  4823. Tools._ErrorEnabled = function (message) {
  4824. Tools.errorsCount++;
  4825. var formattedMessage = Tools._FormatMessage(message);
  4826. console.error("BJS - " + formattedMessage);
  4827. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4828. Tools._AddLogEntry(entry);
  4829. };
  4830. Object.defineProperty(Tools, "LogCache", {
  4831. get: function () {
  4832. return Tools._LogCache;
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. Tools.ClearLogCache = function () {
  4838. Tools._LogCache = "";
  4839. Tools.errorsCount = 0;
  4840. };
  4841. Object.defineProperty(Tools, "LogLevels", {
  4842. set: function (level) {
  4843. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4844. Tools.Log = Tools._LogEnabled;
  4845. }
  4846. else {
  4847. Tools.Log = Tools._LogDisabled;
  4848. }
  4849. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4850. Tools.Warn = Tools._WarnEnabled;
  4851. }
  4852. else {
  4853. Tools.Warn = Tools._WarnDisabled;
  4854. }
  4855. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4856. Tools.Error = Tools._ErrorEnabled;
  4857. }
  4858. else {
  4859. Tools.Error = Tools._ErrorDisabled;
  4860. }
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceNoneLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4873. get: function () {
  4874. return Tools._PerformanceUserMarkLogLevel;
  4875. },
  4876. enumerable: true,
  4877. configurable: true
  4878. });
  4879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4880. get: function () {
  4881. return Tools._PerformanceConsoleLogLevel;
  4882. },
  4883. enumerable: true,
  4884. configurable: true
  4885. });
  4886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4887. set: function (level) {
  4888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4891. return;
  4892. }
  4893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4896. return;
  4897. }
  4898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4900. },
  4901. enumerable: true,
  4902. configurable: true
  4903. });
  4904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4905. };
  4906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4907. };
  4908. Tools._StartUserMark = function (counterName, condition) {
  4909. if (condition === void 0) { condition = true; }
  4910. if (!condition || !Tools._performance.mark) {
  4911. return;
  4912. }
  4913. Tools._performance.mark(counterName + "-Begin");
  4914. };
  4915. Tools._EndUserMark = function (counterName, condition) {
  4916. if (condition === void 0) { condition = true; }
  4917. if (!condition || !Tools._performance.mark) {
  4918. return;
  4919. }
  4920. Tools._performance.mark(counterName + "-End");
  4921. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4922. };
  4923. Tools._StartPerformanceConsole = function (counterName, condition) {
  4924. if (condition === void 0) { condition = true; }
  4925. if (!condition) {
  4926. return;
  4927. }
  4928. Tools._StartUserMark(counterName, condition);
  4929. if (console.time) {
  4930. console.time(counterName);
  4931. }
  4932. };
  4933. Tools._EndPerformanceConsole = function (counterName, condition) {
  4934. if (condition === void 0) { condition = true; }
  4935. if (!condition) {
  4936. return;
  4937. }
  4938. Tools._EndUserMark(counterName, condition);
  4939. if (console.time) {
  4940. console.timeEnd(counterName);
  4941. }
  4942. };
  4943. Object.defineProperty(Tools, "Now", {
  4944. get: function () {
  4945. if (window.performance && window.performance.now) {
  4946. return window.performance.now();
  4947. }
  4948. return new Date().getTime();
  4949. },
  4950. enumerable: true,
  4951. configurable: true
  4952. });
  4953. Tools.BaseUrl = "";
  4954. Tools.CorsBehavior = "anonymous";
  4955. Tools.UseFallbackTexture = true;
  4956. // Logs
  4957. Tools._NoneLogLevel = 0;
  4958. Tools._MessageLogLevel = 1;
  4959. Tools._WarningLogLevel = 2;
  4960. Tools._ErrorLogLevel = 4;
  4961. Tools._LogCache = "";
  4962. Tools.errorsCount = 0;
  4963. Tools.Log = Tools._LogEnabled;
  4964. Tools.Warn = Tools._WarnEnabled;
  4965. Tools.Error = Tools._ErrorEnabled;
  4966. // Performances
  4967. Tools._PerformanceNoneLogLevel = 0;
  4968. Tools._PerformanceUserMarkLogLevel = 1;
  4969. Tools._PerformanceConsoleLogLevel = 2;
  4970. Tools._performance = window.performance;
  4971. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4972. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4973. return Tools;
  4974. })();
  4975. BABYLON.Tools = Tools;
  4976. /**
  4977. * An implementation of a loop for asynchronous functions.
  4978. */
  4979. var AsyncLoop = (function () {
  4980. /**
  4981. * Constroctor.
  4982. * @param iterations the number of iterations.
  4983. * @param _fn the function to run each iteration
  4984. * @param _successCallback the callback that will be called upon succesful execution
  4985. * @param offset starting offset.
  4986. */
  4987. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4988. if (offset === void 0) { offset = 0; }
  4989. this.iterations = iterations;
  4990. this._fn = _fn;
  4991. this._successCallback = _successCallback;
  4992. this.index = offset - 1;
  4993. this._done = false;
  4994. }
  4995. /**
  4996. * Execute the next iteration. Must be called after the last iteration was finished.
  4997. */
  4998. AsyncLoop.prototype.executeNext = function () {
  4999. if (!this._done) {
  5000. if (this.index + 1 < this.iterations) {
  5001. ++this.index;
  5002. this._fn(this);
  5003. }
  5004. else {
  5005. this.breakLoop();
  5006. }
  5007. }
  5008. };
  5009. /**
  5010. * Break the loop and run the success callback.
  5011. */
  5012. AsyncLoop.prototype.breakLoop = function () {
  5013. this._done = true;
  5014. this._successCallback();
  5015. };
  5016. /**
  5017. * Helper function
  5018. */
  5019. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5020. if (offset === void 0) { offset = 0; }
  5021. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5022. loop.executeNext();
  5023. return loop;
  5024. };
  5025. /**
  5026. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5027. * @param iterations total number of iterations
  5028. * @param syncedIterations number of synchronous iterations in each async iteration.
  5029. * @param fn the function to call each iteration.
  5030. * @param callback a success call back that will be called when iterating stops.
  5031. * @param breakFunction a break condition (optional)
  5032. * @param timeout timeout settings for the setTimeout function. default - 0.
  5033. * @constructor
  5034. */
  5035. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5036. if (timeout === void 0) { timeout = 0; }
  5037. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5038. if (breakFunction && breakFunction())
  5039. loop.breakLoop();
  5040. else {
  5041. setTimeout(function () {
  5042. for (var i = 0; i < syncedIterations; ++i) {
  5043. var iteration = (loop.index * syncedIterations) + i;
  5044. if (iteration >= iterations)
  5045. break;
  5046. fn(iteration);
  5047. if (breakFunction && breakFunction()) {
  5048. loop.breakLoop();
  5049. break;
  5050. }
  5051. }
  5052. loop.executeNext();
  5053. }, timeout);
  5054. }
  5055. }, callback);
  5056. };
  5057. return AsyncLoop;
  5058. })();
  5059. BABYLON.AsyncLoop = AsyncLoop;
  5060. })(BABYLON || (BABYLON = {}));
  5061. var BABYLON;
  5062. (function (BABYLON) {
  5063. var Internals;
  5064. (function (Internals) {
  5065. var _AlphaState = (function () {
  5066. function _AlphaState() {
  5067. this._isAlphaBlendDirty = false;
  5068. this._isBlendFunctionParametersDirty = false;
  5069. this._alphaBlend = false;
  5070. this._blendFunctionParameters = new Array(4);
  5071. }
  5072. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5073. get: function () {
  5074. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5080. get: function () {
  5081. return this._alphaBlend;
  5082. },
  5083. set: function (value) {
  5084. if (this._alphaBlend === value) {
  5085. return;
  5086. }
  5087. this._alphaBlend = value;
  5088. this._isAlphaBlendDirty = true;
  5089. },
  5090. enumerable: true,
  5091. configurable: true
  5092. });
  5093. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5094. if (this._blendFunctionParameters[0] === value0 &&
  5095. this._blendFunctionParameters[1] === value1 &&
  5096. this._blendFunctionParameters[2] === value2 &&
  5097. this._blendFunctionParameters[3] === value3) {
  5098. return;
  5099. }
  5100. this._blendFunctionParameters[0] = value0;
  5101. this._blendFunctionParameters[1] = value1;
  5102. this._blendFunctionParameters[2] = value2;
  5103. this._blendFunctionParameters[3] = value3;
  5104. this._isBlendFunctionParametersDirty = true;
  5105. };
  5106. _AlphaState.prototype.reset = function () {
  5107. this._alphaBlend = false;
  5108. this._blendFunctionParameters[0] = null;
  5109. this._blendFunctionParameters[1] = null;
  5110. this._blendFunctionParameters[2] = null;
  5111. this._blendFunctionParameters[3] = null;
  5112. this._isAlphaBlendDirty = true;
  5113. this._isBlendFunctionParametersDirty = false;
  5114. };
  5115. _AlphaState.prototype.apply = function (gl) {
  5116. if (!this.isDirty) {
  5117. return;
  5118. }
  5119. // Alpha blend
  5120. if (this._isAlphaBlendDirty) {
  5121. if (this._alphaBlend) {
  5122. gl.enable(gl.BLEND);
  5123. }
  5124. else {
  5125. gl.disable(gl.BLEND);
  5126. }
  5127. this._isAlphaBlendDirty = false;
  5128. }
  5129. // Alpha function
  5130. if (this._isBlendFunctionParametersDirty) {
  5131. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5132. this._isBlendFunctionParametersDirty = false;
  5133. }
  5134. };
  5135. return _AlphaState;
  5136. })();
  5137. Internals._AlphaState = _AlphaState;
  5138. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5139. })(BABYLON || (BABYLON = {}));
  5140. var BABYLON;
  5141. (function (BABYLON) {
  5142. var Internals;
  5143. (function (Internals) {
  5144. var _DepthCullingState = (function () {
  5145. function _DepthCullingState() {
  5146. this._isDepthTestDirty = false;
  5147. this._isDepthMaskDirty = false;
  5148. this._isDepthFuncDirty = false;
  5149. this._isCullFaceDirty = false;
  5150. this._isCullDirty = false;
  5151. this._isZOffsetDirty = false;
  5152. }
  5153. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5154. get: function () {
  5155. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5161. get: function () {
  5162. return this._zOffset;
  5163. },
  5164. set: function (value) {
  5165. if (this._zOffset === value) {
  5166. return;
  5167. }
  5168. this._zOffset = value;
  5169. this._isZOffsetDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5175. get: function () {
  5176. return this._cullFace;
  5177. },
  5178. set: function (value) {
  5179. if (this._cullFace === value) {
  5180. return;
  5181. }
  5182. this._cullFace = value;
  5183. this._isCullFaceDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5189. get: function () {
  5190. return this._cull;
  5191. },
  5192. set: function (value) {
  5193. if (this._cull === value) {
  5194. return;
  5195. }
  5196. this._cull = value;
  5197. this._isCullDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5203. get: function () {
  5204. return this._depthFunc;
  5205. },
  5206. set: function (value) {
  5207. if (this._depthFunc === value) {
  5208. return;
  5209. }
  5210. this._depthFunc = value;
  5211. this._isDepthFuncDirty = true;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5217. get: function () {
  5218. return this._depthMask;
  5219. },
  5220. set: function (value) {
  5221. if (this._depthMask === value) {
  5222. return;
  5223. }
  5224. this._depthMask = value;
  5225. this._isDepthMaskDirty = true;
  5226. },
  5227. enumerable: true,
  5228. configurable: true
  5229. });
  5230. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5231. get: function () {
  5232. return this._depthTest;
  5233. },
  5234. set: function (value) {
  5235. if (this._depthTest === value) {
  5236. return;
  5237. }
  5238. this._depthTest = value;
  5239. this._isDepthTestDirty = true;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. _DepthCullingState.prototype.reset = function () {
  5245. this._depthMask = true;
  5246. this._depthTest = true;
  5247. this._depthFunc = null;
  5248. this._cull = null;
  5249. this._cullFace = null;
  5250. this._zOffset = 0;
  5251. this._isDepthTestDirty = true;
  5252. this._isDepthMaskDirty = true;
  5253. this._isDepthFuncDirty = false;
  5254. this._isCullFaceDirty = false;
  5255. this._isCullDirty = false;
  5256. this._isZOffsetDirty = false;
  5257. };
  5258. _DepthCullingState.prototype.apply = function (gl) {
  5259. if (!this.isDirty) {
  5260. return;
  5261. }
  5262. // Cull
  5263. if (this._isCullDirty) {
  5264. if (this.cull) {
  5265. gl.enable(gl.CULL_FACE);
  5266. }
  5267. else {
  5268. gl.disable(gl.CULL_FACE);
  5269. }
  5270. this._isCullDirty = false;
  5271. }
  5272. // Cull face
  5273. if (this._isCullFaceDirty) {
  5274. gl.cullFace(this.cullFace);
  5275. this._isCullFaceDirty = false;
  5276. }
  5277. // Depth mask
  5278. if (this._isDepthMaskDirty) {
  5279. gl.depthMask(this.depthMask);
  5280. this._isDepthMaskDirty = false;
  5281. }
  5282. // Depth test
  5283. if (this._isDepthTestDirty) {
  5284. if (this.depthTest) {
  5285. gl.enable(gl.DEPTH_TEST);
  5286. }
  5287. else {
  5288. gl.disable(gl.DEPTH_TEST);
  5289. }
  5290. this._isDepthTestDirty = false;
  5291. }
  5292. // Depth func
  5293. if (this._isDepthFuncDirty) {
  5294. gl.depthFunc(this.depthFunc);
  5295. this._isDepthFuncDirty = false;
  5296. }
  5297. // zOffset
  5298. if (this._isZOffsetDirty) {
  5299. if (this.zOffset) {
  5300. gl.enable(gl.POLYGON_OFFSET_FILL);
  5301. gl.polygonOffset(this.zOffset, 0);
  5302. }
  5303. else {
  5304. gl.disable(gl.POLYGON_OFFSET_FILL);
  5305. }
  5306. this._isZOffsetDirty = false;
  5307. }
  5308. };
  5309. return _DepthCullingState;
  5310. })();
  5311. Internals._DepthCullingState = _DepthCullingState;
  5312. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5313. })(BABYLON || (BABYLON = {}));
  5314. var BABYLON;
  5315. (function (BABYLON) {
  5316. var compileShader = function (gl, source, type, defines) {
  5317. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5318. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5319. gl.compileShader(shader);
  5320. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5321. throw new Error(gl.getShaderInfoLog(shader));
  5322. }
  5323. return shader;
  5324. };
  5325. var getWebGLTextureType = function (gl, type) {
  5326. var textureType = gl.UNSIGNED_BYTE;
  5327. if (type === Engine.TEXTURETYPE_FLOAT)
  5328. textureType = gl.FLOAT;
  5329. return textureType;
  5330. };
  5331. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5332. var magFilter = gl.NEAREST;
  5333. var minFilter = gl.NEAREST;
  5334. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5335. magFilter = gl.LINEAR;
  5336. if (generateMipMaps) {
  5337. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5338. }
  5339. else {
  5340. minFilter = gl.LINEAR;
  5341. }
  5342. }
  5343. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5344. magFilter = gl.LINEAR;
  5345. if (generateMipMaps) {
  5346. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5347. }
  5348. else {
  5349. minFilter = gl.LINEAR;
  5350. }
  5351. }
  5352. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5353. magFilter = gl.NEAREST;
  5354. if (generateMipMaps) {
  5355. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5356. }
  5357. else {
  5358. minFilter = gl.NEAREST;
  5359. }
  5360. }
  5361. return {
  5362. min: minFilter,
  5363. mag: magFilter
  5364. };
  5365. };
  5366. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5368. var engine = scene.getEngine();
  5369. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5370. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5371. gl.bindTexture(gl.TEXTURE_2D, texture);
  5372. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5373. texture._baseWidth = width;
  5374. texture._baseHeight = height;
  5375. texture._width = potWidth;
  5376. texture._height = potHeight;
  5377. texture.isReady = true;
  5378. processFunction(potWidth, potHeight);
  5379. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5382. if (!noMipmap && !isCompressed) {
  5383. gl.generateMipmap(gl.TEXTURE_2D);
  5384. }
  5385. gl.bindTexture(gl.TEXTURE_2D, null);
  5386. engine.resetTextureCache();
  5387. scene._removePendingData(texture);
  5388. if (onLoad) {
  5389. onLoad();
  5390. }
  5391. };
  5392. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5393. var img;
  5394. var onload = function () {
  5395. loadedImages[index] = img;
  5396. loadedImages._internalCount++;
  5397. scene._removePendingData(img);
  5398. if (loadedImages._internalCount === 6) {
  5399. onfinish(loadedImages);
  5400. }
  5401. };
  5402. var onerror = function () {
  5403. scene._removePendingData(img);
  5404. };
  5405. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5406. scene._addPendingData(img);
  5407. };
  5408. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5409. var loadedImages = [];
  5410. loadedImages._internalCount = 0;
  5411. for (var index = 0; index < 6; index++) {
  5412. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5413. }
  5414. };
  5415. var EngineCapabilities = (function () {
  5416. function EngineCapabilities() {
  5417. }
  5418. return EngineCapabilities;
  5419. })();
  5420. BABYLON.EngineCapabilities = EngineCapabilities;
  5421. /**
  5422. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5423. */
  5424. var Engine = (function () {
  5425. /**
  5426. * @constructor
  5427. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5428. * @param {boolean} [antialias] - enable antialias
  5429. * @param options - further options to be sent to the getContext function
  5430. */
  5431. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5432. var _this = this;
  5433. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5434. // Public members
  5435. this.isFullscreen = false;
  5436. this.isPointerLock = false;
  5437. this.cullBackFaces = true;
  5438. this.renderEvenInBackground = true;
  5439. // To enable/disable IDB support and avoid XHR on .manifest
  5440. this.enableOfflineSupport = true;
  5441. this.scenes = new Array();
  5442. this._windowIsBackground = false;
  5443. this._webGLVersion = "1.0";
  5444. this._drawCalls = 0;
  5445. this._renderingQueueLaunched = false;
  5446. this._activeRenderLoops = [];
  5447. // FPS
  5448. this.fpsRange = 60;
  5449. this.previousFramesDuration = [];
  5450. this.fps = 60;
  5451. this.deltaTime = 0;
  5452. // States
  5453. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5454. this._alphaState = new BABYLON.Internals._AlphaState();
  5455. this._alphaMode = Engine.ALPHA_DISABLE;
  5456. // Cache
  5457. this._loadedTexturesCache = new Array();
  5458. this._maxTextureChannels = 16;
  5459. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5460. this._compiledEffects = {};
  5461. this._uintIndicesCurrentlySet = false;
  5462. this._renderingCanvas = canvas;
  5463. options = options || {};
  5464. options.antialias = antialias;
  5465. if (options.preserveDrawingBuffer === undefined) {
  5466. options.preserveDrawingBuffer = false;
  5467. }
  5468. // GL
  5469. //try {
  5470. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5471. // if (this._gl) {
  5472. // this._webGLVersion = "2.0";
  5473. // }
  5474. //} catch (e) {
  5475. // // Do nothing
  5476. //}
  5477. if (!this._gl) {
  5478. try {
  5479. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5480. }
  5481. catch (e) {
  5482. throw new Error("WebGL not supported");
  5483. }
  5484. }
  5485. if (!this._gl) {
  5486. throw new Error("WebGL not supported");
  5487. }
  5488. this._onBlur = function () {
  5489. _this._windowIsBackground = true;
  5490. };
  5491. this._onFocus = function () {
  5492. _this._windowIsBackground = false;
  5493. };
  5494. window.addEventListener("blur", this._onBlur);
  5495. window.addEventListener("focus", this._onFocus);
  5496. // Viewport
  5497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5499. this.resize();
  5500. // Caps
  5501. this._caps = new EngineCapabilities();
  5502. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5503. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5504. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5505. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5506. // Infos
  5507. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5508. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5509. if (rendererInfo != null) {
  5510. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5511. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5512. }
  5513. if (!this._glVendor) {
  5514. this._glVendor = "Unknown vendor";
  5515. }
  5516. if (!this._glRenderer) {
  5517. this._glRenderer = "Unknown renderer";
  5518. }
  5519. // Extensions
  5520. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5521. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5522. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5523. 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');
  5524. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5525. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5526. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5527. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5528. this._caps.highPrecisionShaderSupported = true;
  5529. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5530. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5531. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5532. if (this._gl.getShaderPrecisionFormat) {
  5533. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5534. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5535. }
  5536. // Depth buffer
  5537. this.setDepthBuffer(true);
  5538. this.setDepthFunctionToLessOrEqual();
  5539. this.setDepthWrite(true);
  5540. // Fullscreen
  5541. this._onFullscreenChange = function () {
  5542. if (document.fullscreen !== undefined) {
  5543. _this.isFullscreen = document.fullscreen;
  5544. }
  5545. else if (document.mozFullScreen !== undefined) {
  5546. _this.isFullscreen = document.mozFullScreen;
  5547. }
  5548. else if (document.webkitIsFullScreen !== undefined) {
  5549. _this.isFullscreen = document.webkitIsFullScreen;
  5550. }
  5551. else if (document.msIsFullScreen !== undefined) {
  5552. _this.isFullscreen = document.msIsFullScreen;
  5553. }
  5554. // Pointer lock
  5555. if (_this.isFullscreen && _this._pointerLockRequested) {
  5556. canvas.requestPointerLock = canvas.requestPointerLock ||
  5557. canvas.msRequestPointerLock ||
  5558. canvas.mozRequestPointerLock ||
  5559. canvas.webkitRequestPointerLock;
  5560. if (canvas.requestPointerLock) {
  5561. canvas.requestPointerLock();
  5562. }
  5563. }
  5564. };
  5565. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5566. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5567. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5568. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5569. // Pointer lock
  5570. this._onPointerLockChange = function () {
  5571. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5572. document.webkitPointerLockElement === canvas ||
  5573. document.msPointerLockElement === canvas ||
  5574. document.pointerLockElement === canvas);
  5575. };
  5576. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5577. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5578. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5579. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5580. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5581. Engine.audioEngine = new BABYLON.AudioEngine();
  5582. }
  5583. //default loading screen
  5584. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5585. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5586. }
  5587. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5588. get: function () {
  5589. return Engine._ALPHA_DISABLE;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5595. get: function () {
  5596. return Engine._ALPHA_ONEONE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "ALPHA_ADD", {
  5602. get: function () {
  5603. return Engine._ALPHA_ADD;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5609. get: function () {
  5610. return Engine._ALPHA_COMBINE;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5616. get: function () {
  5617. return Engine._ALPHA_SUBTRACT;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5623. get: function () {
  5624. return Engine._ALPHA_MULTIPLY;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5630. get: function () {
  5631. return Engine._ALPHA_MAXIMIZED;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5637. get: function () {
  5638. return Engine._DELAYLOADSTATE_NONE;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5644. get: function () {
  5645. return Engine._DELAYLOADSTATE_LOADED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5651. get: function () {
  5652. return Engine._DELAYLOADSTATE_LOADING;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5658. get: function () {
  5659. return Engine._DELAYLOADSTATE_NOTLOADED;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5665. get: function () {
  5666. return Engine._TEXTUREFORMAT_ALPHA;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5672. get: function () {
  5673. return Engine._TEXTUREFORMAT_LUMINANCE;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5686. get: function () {
  5687. return Engine._TEXTUREFORMAT_RGB;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5693. get: function () {
  5694. return Engine._TEXTUREFORMAT_RGBA;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5700. get: function () {
  5701. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5707. get: function () {
  5708. return Engine._TEXTURETYPE_FLOAT;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Object.defineProperty(Engine, "Version", {
  5714. get: function () {
  5715. return "2.4.0-alpha";
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5721. get: function () {
  5722. return this._webGLVersion;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Engine.prototype._prepareWorkingCanvas = function () {
  5728. if (this._workingCanvas) {
  5729. return;
  5730. }
  5731. this._workingCanvas = document.createElement("canvas");
  5732. this._workingContext = this._workingCanvas.getContext("2d");
  5733. };
  5734. Engine.prototype.resetTextureCache = function () {
  5735. for (var index = 0; index < this._maxTextureChannels; index++) {
  5736. this._activeTexturesCache[index] = null;
  5737. }
  5738. };
  5739. Engine.prototype.getGlInfo = function () {
  5740. return {
  5741. vendor: this._glVendor,
  5742. renderer: this._glRenderer,
  5743. version: this._glVersion
  5744. };
  5745. };
  5746. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5747. if (useScreen === void 0) { useScreen = false; }
  5748. var viewport = camera.viewport;
  5749. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5750. };
  5751. Engine.prototype.getRenderWidth = function (useScreen) {
  5752. if (useScreen === void 0) { useScreen = false; }
  5753. if (!useScreen && this._currentRenderTarget) {
  5754. return this._currentRenderTarget._width;
  5755. }
  5756. return this._renderingCanvas.width;
  5757. };
  5758. Engine.prototype.getRenderHeight = function (useScreen) {
  5759. if (useScreen === void 0) { useScreen = false; }
  5760. if (!useScreen && this._currentRenderTarget) {
  5761. return this._currentRenderTarget._height;
  5762. }
  5763. return this._renderingCanvas.height;
  5764. };
  5765. Engine.prototype.getRenderingCanvas = function () {
  5766. return this._renderingCanvas;
  5767. };
  5768. Engine.prototype.getRenderingCanvasClientRect = function () {
  5769. return this._renderingCanvas.getBoundingClientRect();
  5770. };
  5771. Engine.prototype.setHardwareScalingLevel = function (level) {
  5772. this._hardwareScalingLevel = level;
  5773. this.resize();
  5774. };
  5775. Engine.prototype.getHardwareScalingLevel = function () {
  5776. return this._hardwareScalingLevel;
  5777. };
  5778. Engine.prototype.getLoadedTexturesCache = function () {
  5779. return this._loadedTexturesCache;
  5780. };
  5781. Engine.prototype.getCaps = function () {
  5782. return this._caps;
  5783. };
  5784. Object.defineProperty(Engine.prototype, "drawCalls", {
  5785. get: function () {
  5786. return this._drawCalls;
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. // Methods
  5792. Engine.prototype.resetDrawCalls = function () {
  5793. this._drawCalls = 0;
  5794. };
  5795. Engine.prototype.setDepthFunctionToGreater = function () {
  5796. this._depthCullingState.depthFunc = this._gl.GREATER;
  5797. };
  5798. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5799. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5800. };
  5801. Engine.prototype.setDepthFunctionToLess = function () {
  5802. this._depthCullingState.depthFunc = this._gl.LESS;
  5803. };
  5804. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5805. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5806. };
  5807. /**
  5808. * stop executing a render loop function and remove it from the execution array
  5809. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5810. */
  5811. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5812. if (!renderFunction) {
  5813. this._activeRenderLoops = [];
  5814. return;
  5815. }
  5816. var index = this._activeRenderLoops.indexOf(renderFunction);
  5817. if (index >= 0) {
  5818. this._activeRenderLoops.splice(index, 1);
  5819. }
  5820. };
  5821. Engine.prototype._renderLoop = function () {
  5822. var shouldRender = true;
  5823. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5824. shouldRender = false;
  5825. }
  5826. if (shouldRender) {
  5827. // Start new frame
  5828. this.beginFrame();
  5829. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5830. var renderFunction = this._activeRenderLoops[index];
  5831. renderFunction();
  5832. }
  5833. // Present
  5834. this.endFrame();
  5835. }
  5836. if (this._activeRenderLoops.length > 0) {
  5837. // Register new frame
  5838. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5839. }
  5840. else {
  5841. this._renderingQueueLaunched = false;
  5842. }
  5843. };
  5844. /**
  5845. * Register and execute a render loop. The engine can have more than one render function.
  5846. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5847. * @example
  5848. * engine.runRenderLoop(function () {
  5849. * scene.render()
  5850. * })
  5851. */
  5852. Engine.prototype.runRenderLoop = function (renderFunction) {
  5853. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5854. return;
  5855. }
  5856. this._activeRenderLoops.push(renderFunction);
  5857. if (!this._renderingQueueLaunched) {
  5858. this._renderingQueueLaunched = true;
  5859. this._bindedRenderFunction = this._renderLoop.bind(this);
  5860. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5861. }
  5862. };
  5863. /**
  5864. * Toggle full screen mode.
  5865. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5866. */
  5867. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5868. if (this.isFullscreen) {
  5869. BABYLON.Tools.ExitFullscreen();
  5870. }
  5871. else {
  5872. this._pointerLockRequested = requestPointerLock;
  5873. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5874. }
  5875. };
  5876. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5877. this.applyStates();
  5878. if (backBuffer) {
  5879. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5880. }
  5881. if (depthStencil && this._depthCullingState.depthMask) {
  5882. this._gl.clearDepth(1.0);
  5883. }
  5884. var mode = 0;
  5885. if (backBuffer) {
  5886. mode |= this._gl.COLOR_BUFFER_BIT;
  5887. }
  5888. if (depthStencil && this._depthCullingState.depthMask) {
  5889. mode |= this._gl.DEPTH_BUFFER_BIT;
  5890. }
  5891. this._gl.clear(mode);
  5892. };
  5893. /**
  5894. * Set the WebGL's viewport
  5895. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5896. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5897. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5898. */
  5899. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5900. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5901. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5902. var x = viewport.x || 0;
  5903. var y = viewport.y || 0;
  5904. this._cachedViewport = viewport;
  5905. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5906. };
  5907. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5908. this._cachedViewport = null;
  5909. this._gl.viewport(x, y, width, height);
  5910. };
  5911. Engine.prototype.beginFrame = function () {
  5912. this._measureFps();
  5913. };
  5914. Engine.prototype.endFrame = function () {
  5915. //this.flushFramebuffer();
  5916. };
  5917. /**
  5918. * resize the view according to the canvas' size.
  5919. * @example
  5920. * window.addEventListener("resize", function () {
  5921. * engine.resize();
  5922. * });
  5923. */
  5924. Engine.prototype.resize = function () {
  5925. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5926. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5927. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5928. for (var index = 0; index < this.scenes.length; index++) {
  5929. var scene = this.scenes[index];
  5930. if (scene.debugLayer.isVisible()) {
  5931. scene.debugLayer._syncPositions();
  5932. }
  5933. }
  5934. };
  5935. /**
  5936. * force a specific size of the canvas
  5937. * @param {number} width - the new canvas' width
  5938. * @param {number} height - the new canvas' height
  5939. */
  5940. Engine.prototype.setSize = function (width, height) {
  5941. this._renderingCanvas.width = width;
  5942. this._renderingCanvas.height = height;
  5943. for (var index = 0; index < this.scenes.length; index++) {
  5944. var scene = this.scenes[index];
  5945. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5946. var cam = scene.cameras[camIndex];
  5947. cam._currentRenderId = 0;
  5948. }
  5949. }
  5950. };
  5951. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5952. this._currentRenderTarget = texture;
  5953. var gl = this._gl;
  5954. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5955. if (texture.isCube) {
  5956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5957. }
  5958. else {
  5959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5960. }
  5961. this._gl.viewport(0, 0, texture._width, texture._height);
  5962. this.wipeCaches();
  5963. };
  5964. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5965. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5966. this._currentRenderTarget = null;
  5967. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5968. var gl = this._gl;
  5969. gl.bindTexture(gl.TEXTURE_2D, texture);
  5970. gl.generateMipmap(gl.TEXTURE_2D);
  5971. gl.bindTexture(gl.TEXTURE_2D, null);
  5972. }
  5973. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5974. };
  5975. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5976. if (texture.generateMipMaps) {
  5977. var gl = this._gl;
  5978. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5979. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5980. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5981. }
  5982. };
  5983. Engine.prototype.flushFramebuffer = function () {
  5984. this._gl.flush();
  5985. };
  5986. Engine.prototype.restoreDefaultFramebuffer = function () {
  5987. this._currentRenderTarget = null;
  5988. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5989. this.setViewport(this._cachedViewport);
  5990. this.wipeCaches();
  5991. };
  5992. // VBOs
  5993. Engine.prototype._resetVertexBufferBinding = function () {
  5994. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5995. this._cachedVertexBuffers = null;
  5996. };
  5997. Engine.prototype.createVertexBuffer = function (vertices) {
  5998. var vbo = this._gl.createBuffer();
  5999. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6000. if (vertices instanceof Float32Array) {
  6001. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6002. }
  6003. else {
  6004. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6005. }
  6006. this._resetVertexBufferBinding();
  6007. vbo.references = 1;
  6008. return vbo;
  6009. };
  6010. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6011. var vbo = this._gl.createBuffer();
  6012. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6013. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6014. this._resetVertexBufferBinding();
  6015. vbo.references = 1;
  6016. return vbo;
  6017. };
  6018. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6019. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6020. if (offset === undefined) {
  6021. offset = 0;
  6022. }
  6023. if (vertices instanceof Float32Array) {
  6024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6025. }
  6026. else {
  6027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6028. }
  6029. this._resetVertexBufferBinding();
  6030. };
  6031. Engine.prototype._resetIndexBufferBinding = function () {
  6032. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6033. this._cachedIndexBuffer = null;
  6034. };
  6035. Engine.prototype.createIndexBuffer = function (indices) {
  6036. var vbo = this._gl.createBuffer();
  6037. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6038. // Check for 32 bits indices
  6039. var arrayBuffer;
  6040. var need32Bits = false;
  6041. if (this._caps.uintIndices) {
  6042. for (var index = 0; index < indices.length; index++) {
  6043. if (indices[index] > 65535) {
  6044. need32Bits = true;
  6045. break;
  6046. }
  6047. }
  6048. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6049. }
  6050. else {
  6051. arrayBuffer = new Uint16Array(indices);
  6052. }
  6053. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6054. this._resetIndexBufferBinding();
  6055. vbo.references = 1;
  6056. vbo.is32Bits = need32Bits;
  6057. return vbo;
  6058. };
  6059. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6060. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6061. this._cachedVertexBuffers = vertexBuffer;
  6062. this._cachedEffectForVertexBuffers = effect;
  6063. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6064. var offset = 0;
  6065. for (var index = 0; index < vertexDeclaration.length; index++) {
  6066. var order = effect.getAttributeLocation(index);
  6067. if (order >= 0) {
  6068. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6069. }
  6070. offset += vertexDeclaration[index] * 4;
  6071. }
  6072. }
  6073. if (this._cachedIndexBuffer !== indexBuffer) {
  6074. this._cachedIndexBuffer = indexBuffer;
  6075. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6076. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6077. }
  6078. };
  6079. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6080. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6081. this._cachedVertexBuffers = vertexBuffers;
  6082. this._cachedEffectForVertexBuffers = effect;
  6083. var attributes = effect.getAttributesNames();
  6084. for (var index = 0; index < attributes.length; index++) {
  6085. var order = effect.getAttributeLocation(index);
  6086. if (order >= 0) {
  6087. var vertexBuffer = vertexBuffers[attributes[index]];
  6088. if (!vertexBuffer) {
  6089. continue;
  6090. }
  6091. var stride = vertexBuffer.getStrideSize();
  6092. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6093. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6094. }
  6095. }
  6096. }
  6097. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6098. this._cachedIndexBuffer = indexBuffer;
  6099. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6100. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6101. }
  6102. };
  6103. Engine.prototype._releaseBuffer = function (buffer) {
  6104. buffer.references--;
  6105. if (buffer.references === 0) {
  6106. this._gl.deleteBuffer(buffer);
  6107. return true;
  6108. }
  6109. return false;
  6110. };
  6111. Engine.prototype.createInstancesBuffer = function (capacity) {
  6112. var buffer = this._gl.createBuffer();
  6113. buffer.capacity = capacity;
  6114. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6115. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6116. return buffer;
  6117. };
  6118. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6119. this._gl.deleteBuffer(buffer);
  6120. };
  6121. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6122. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6123. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6124. for (var index = 0; index < 4; index++) {
  6125. var offsetLocation = offsetLocations[index];
  6126. this._gl.enableVertexAttribArray(offsetLocation);
  6127. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6128. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6129. }
  6130. };
  6131. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6132. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6133. for (var index = 0; index < 4; index++) {
  6134. var offsetLocation = offsetLocations[index];
  6135. this._gl.disableVertexAttribArray(offsetLocation);
  6136. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6137. }
  6138. };
  6139. Engine.prototype.applyStates = function () {
  6140. this._depthCullingState.apply(this._gl);
  6141. this._alphaState.apply(this._gl);
  6142. };
  6143. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6144. // Apply states
  6145. this.applyStates();
  6146. this._drawCalls++;
  6147. // Render
  6148. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6149. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6150. if (instancesCount) {
  6151. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6152. return;
  6153. }
  6154. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6155. };
  6156. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6157. // Apply states
  6158. this.applyStates();
  6159. this._drawCalls++;
  6160. if (instancesCount) {
  6161. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6162. return;
  6163. }
  6164. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6165. };
  6166. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6167. // Apply states
  6168. this.applyStates();
  6169. this._drawCalls++;
  6170. if (instancesCount) {
  6171. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6172. return;
  6173. }
  6174. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6175. };
  6176. // Shaders
  6177. Engine.prototype._releaseEffect = function (effect) {
  6178. if (this._compiledEffects[effect._key]) {
  6179. delete this._compiledEffects[effect._key];
  6180. if (effect.getProgram()) {
  6181. this._gl.deleteProgram(effect.getProgram());
  6182. }
  6183. }
  6184. };
  6185. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6186. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6187. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6188. var name = vertex + "+" + fragment + "@" + defines;
  6189. if (this._compiledEffects[name]) {
  6190. return this._compiledEffects[name];
  6191. }
  6192. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6193. effect._key = name;
  6194. this._compiledEffects[name] = effect;
  6195. return effect;
  6196. };
  6197. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6198. if (uniformsNames === void 0) { uniformsNames = []; }
  6199. if (samplers === void 0) { samplers = []; }
  6200. if (defines === void 0) { defines = ""; }
  6201. return this.createEffect({
  6202. vertex: "particles",
  6203. fragmentElement: fragmentName
  6204. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6205. };
  6206. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6207. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6208. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6209. var shaderProgram = this._gl.createProgram();
  6210. this._gl.attachShader(shaderProgram, vertexShader);
  6211. this._gl.attachShader(shaderProgram, fragmentShader);
  6212. this._gl.linkProgram(shaderProgram);
  6213. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6214. if (!linked) {
  6215. var error = this._gl.getProgramInfoLog(shaderProgram);
  6216. if (error) {
  6217. throw new Error(error);
  6218. }
  6219. }
  6220. this._gl.deleteShader(vertexShader);
  6221. this._gl.deleteShader(fragmentShader);
  6222. return shaderProgram;
  6223. };
  6224. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6225. var results = [];
  6226. for (var index = 0; index < uniformsNames.length; index++) {
  6227. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6228. }
  6229. return results;
  6230. };
  6231. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6232. var results = [];
  6233. for (var index = 0; index < attributesNames.length; index++) {
  6234. try {
  6235. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6236. }
  6237. catch (e) {
  6238. results.push(-1);
  6239. }
  6240. }
  6241. return results;
  6242. };
  6243. Engine.prototype.enableEffect = function (effect) {
  6244. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6245. if (effect && effect.onBind) {
  6246. effect.onBind(effect);
  6247. }
  6248. return;
  6249. }
  6250. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6251. // Use program
  6252. this._gl.useProgram(effect.getProgram());
  6253. for (var i in this._vertexAttribArrays) {
  6254. //make sure this is a number)
  6255. var iAsNumber = +i;
  6256. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6257. continue;
  6258. }
  6259. this._vertexAttribArrays[iAsNumber] = false;
  6260. this._gl.disableVertexAttribArray(iAsNumber);
  6261. }
  6262. var attributesCount = effect.getAttributesCount();
  6263. for (var index = 0; index < attributesCount; index++) {
  6264. // Attributes
  6265. var order = effect.getAttributeLocation(index);
  6266. if (order >= 0) {
  6267. this._vertexAttribArrays[order] = true;
  6268. this._gl.enableVertexAttribArray(order);
  6269. }
  6270. }
  6271. this._currentEffect = effect;
  6272. if (effect.onBind) {
  6273. effect.onBind(effect);
  6274. }
  6275. };
  6276. Engine.prototype.setArray = function (uniform, array) {
  6277. if (!uniform)
  6278. return;
  6279. this._gl.uniform1fv(uniform, array);
  6280. };
  6281. Engine.prototype.setArray2 = function (uniform, array) {
  6282. if (!uniform || array.length % 2 !== 0)
  6283. return;
  6284. this._gl.uniform2fv(uniform, array);
  6285. };
  6286. Engine.prototype.setArray3 = function (uniform, array) {
  6287. if (!uniform || array.length % 3 !== 0)
  6288. return;
  6289. this._gl.uniform3fv(uniform, array);
  6290. };
  6291. Engine.prototype.setArray4 = function (uniform, array) {
  6292. if (!uniform || array.length % 4 !== 0)
  6293. return;
  6294. this._gl.uniform4fv(uniform, array);
  6295. };
  6296. Engine.prototype.setMatrices = function (uniform, matrices) {
  6297. if (!uniform)
  6298. return;
  6299. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6300. };
  6301. Engine.prototype.setMatrix = function (uniform, matrix) {
  6302. if (!uniform)
  6303. return;
  6304. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6305. };
  6306. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6307. if (!uniform)
  6308. return;
  6309. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6310. };
  6311. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6312. if (!uniform)
  6313. return;
  6314. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6315. };
  6316. Engine.prototype.setFloat = function (uniform, value) {
  6317. if (!uniform)
  6318. return;
  6319. this._gl.uniform1f(uniform, value);
  6320. };
  6321. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6322. if (!uniform)
  6323. return;
  6324. this._gl.uniform2f(uniform, x, y);
  6325. };
  6326. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6327. if (!uniform)
  6328. return;
  6329. this._gl.uniform3f(uniform, x, y, z);
  6330. };
  6331. Engine.prototype.setBool = function (uniform, bool) {
  6332. if (!uniform)
  6333. return;
  6334. this._gl.uniform1i(uniform, bool);
  6335. };
  6336. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6337. if (!uniform)
  6338. return;
  6339. this._gl.uniform4f(uniform, x, y, z, w);
  6340. };
  6341. Engine.prototype.setColor3 = function (uniform, color3) {
  6342. if (!uniform)
  6343. return;
  6344. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6345. };
  6346. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6347. if (!uniform)
  6348. return;
  6349. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6350. };
  6351. // States
  6352. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6353. if (zOffset === void 0) { zOffset = 0; }
  6354. if (reverseSide === void 0) { reverseSide = false; }
  6355. // Culling
  6356. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6357. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6358. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6359. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6360. if (culling) {
  6361. this._depthCullingState.cullFace = cullFace;
  6362. this._depthCullingState.cull = true;
  6363. }
  6364. else {
  6365. this._depthCullingState.cull = false;
  6366. }
  6367. }
  6368. // Z offset
  6369. this._depthCullingState.zOffset = zOffset;
  6370. };
  6371. Engine.prototype.setDepthBuffer = function (enable) {
  6372. this._depthCullingState.depthTest = enable;
  6373. };
  6374. Engine.prototype.getDepthWrite = function () {
  6375. return this._depthCullingState.depthMask;
  6376. };
  6377. Engine.prototype.setDepthWrite = function (enable) {
  6378. this._depthCullingState.depthMask = enable;
  6379. };
  6380. Engine.prototype.setColorWrite = function (enable) {
  6381. this._gl.colorMask(enable, enable, enable, enable);
  6382. };
  6383. Engine.prototype.setAlphaMode = function (mode) {
  6384. if (this._alphaMode === mode) {
  6385. return;
  6386. }
  6387. switch (mode) {
  6388. case Engine.ALPHA_DISABLE:
  6389. this.setDepthWrite(true);
  6390. this._alphaState.alphaBlend = false;
  6391. break;
  6392. case Engine.ALPHA_COMBINE:
  6393. this.setDepthWrite(false);
  6394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6395. this._alphaState.alphaBlend = true;
  6396. break;
  6397. case Engine.ALPHA_ONEONE:
  6398. this.setDepthWrite(false);
  6399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6400. this._alphaState.alphaBlend = true;
  6401. break;
  6402. case Engine.ALPHA_ADD:
  6403. this.setDepthWrite(false);
  6404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6405. this._alphaState.alphaBlend = true;
  6406. break;
  6407. case Engine.ALPHA_SUBTRACT:
  6408. this.setDepthWrite(false);
  6409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6410. this._alphaState.alphaBlend = true;
  6411. break;
  6412. case Engine.ALPHA_MULTIPLY:
  6413. this.setDepthWrite(false);
  6414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6415. this._alphaState.alphaBlend = true;
  6416. break;
  6417. case Engine.ALPHA_MAXIMIZED:
  6418. this.setDepthWrite(false);
  6419. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6420. this._alphaState.alphaBlend = true;
  6421. break;
  6422. }
  6423. this._alphaMode = mode;
  6424. };
  6425. Engine.prototype.getAlphaMode = function () {
  6426. return this._alphaMode;
  6427. };
  6428. Engine.prototype.setAlphaTesting = function (enable) {
  6429. this._alphaTest = enable;
  6430. };
  6431. Engine.prototype.getAlphaTesting = function () {
  6432. return this._alphaTest;
  6433. };
  6434. // Textures
  6435. Engine.prototype.wipeCaches = function () {
  6436. this.resetTextureCache();
  6437. this._currentEffect = null;
  6438. this._depthCullingState.reset();
  6439. this._alphaState.reset();
  6440. this._cachedVertexBuffers = null;
  6441. this._cachedIndexBuffer = null;
  6442. this._cachedEffectForVertexBuffers = null;
  6443. };
  6444. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6445. var gl = this._gl;
  6446. gl.bindTexture(gl.TEXTURE_2D, texture);
  6447. var magFilter = gl.NEAREST;
  6448. var minFilter = gl.NEAREST;
  6449. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6450. magFilter = gl.LINEAR;
  6451. minFilter = gl.LINEAR;
  6452. }
  6453. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6454. magFilter = gl.LINEAR;
  6455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6456. }
  6457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6459. gl.bindTexture(gl.TEXTURE_2D, null);
  6460. texture.samplingMode = samplingMode;
  6461. };
  6462. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6463. var _this = this;
  6464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6465. if (onLoad === void 0) { onLoad = null; }
  6466. if (onError === void 0) { onError = null; }
  6467. if (buffer === void 0) { buffer = null; }
  6468. var texture = this._gl.createTexture();
  6469. var extension;
  6470. var fromData = false;
  6471. if (url.substr(0, 5) === "data:") {
  6472. fromData = true;
  6473. }
  6474. if (!fromData)
  6475. extension = url.substr(url.length - 4, 4).toLowerCase();
  6476. else {
  6477. var oldUrl = url;
  6478. fromData = oldUrl.split(':');
  6479. url = oldUrl;
  6480. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6481. }
  6482. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6483. var isTGA = (extension === ".tga");
  6484. scene._addPendingData(texture);
  6485. texture.url = url;
  6486. texture.noMipmap = noMipmap;
  6487. texture.references = 1;
  6488. texture.samplingMode = samplingMode;
  6489. this._loadedTexturesCache.push(texture);
  6490. var onerror = function () {
  6491. scene._removePendingData(texture);
  6492. if (onError) {
  6493. onError();
  6494. }
  6495. };
  6496. var callback;
  6497. if (isTGA) {
  6498. callback = function (arrayBuffer) {
  6499. var data = new Uint8Array(arrayBuffer);
  6500. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6501. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6502. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6503. }, onLoad, samplingMode);
  6504. };
  6505. if (!(fromData instanceof Array))
  6506. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6507. callback(arrayBuffer);
  6508. }, onerror, scene.database, true);
  6509. else
  6510. callback(buffer);
  6511. }
  6512. else if (isDDS) {
  6513. callback = function (data) {
  6514. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6515. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6516. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6517. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6518. }, onLoad, samplingMode);
  6519. };
  6520. if (!(fromData instanceof Array))
  6521. BABYLON.Tools.LoadFile(url, function (data) {
  6522. callback(data);
  6523. }, onerror, scene.database, true);
  6524. else
  6525. callback(buffer);
  6526. }
  6527. else {
  6528. var onload = function (img) {
  6529. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6530. var isPot = (img.width === potWidth && img.height === potHeight);
  6531. if (!isPot) {
  6532. _this._prepareWorkingCanvas();
  6533. _this._workingCanvas.width = potWidth;
  6534. _this._workingCanvas.height = potHeight;
  6535. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6536. _this._workingContext.imageSmoothingEnabled = false;
  6537. _this._workingContext.mozImageSmoothingEnabled = false;
  6538. _this._workingContext.oImageSmoothingEnabled = false;
  6539. _this._workingContext.webkitImageSmoothingEnabled = false;
  6540. _this._workingContext.msImageSmoothingEnabled = false;
  6541. }
  6542. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6543. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6544. _this._workingContext.imageSmoothingEnabled = true;
  6545. _this._workingContext.mozImageSmoothingEnabled = true;
  6546. _this._workingContext.oImageSmoothingEnabled = true;
  6547. _this._workingContext.webkitImageSmoothingEnabled = true;
  6548. _this._workingContext.msImageSmoothingEnabled = true;
  6549. }
  6550. }
  6551. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6552. }, onLoad, samplingMode);
  6553. };
  6554. if (!(fromData instanceof Array))
  6555. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6556. else
  6557. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6558. }
  6559. return texture;
  6560. };
  6561. Engine.prototype._getInternalFormat = function (format) {
  6562. var internalFormat = this._gl.RGBA;
  6563. switch (format) {
  6564. case Engine.TEXTUREFORMAT_ALPHA:
  6565. internalFormat = this._gl.ALPHA;
  6566. break;
  6567. case Engine.TEXTUREFORMAT_LUMINANCE:
  6568. internalFormat = this._gl.LUMINANCE;
  6569. break;
  6570. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6571. internalFormat = this._gl.LUMINANCE_ALPHA;
  6572. break;
  6573. case Engine.TEXTUREFORMAT_RGB:
  6574. internalFormat = this._gl.RGB;
  6575. break;
  6576. case Engine.TEXTUREFORMAT_RGBA:
  6577. internalFormat = this._gl.RGBA;
  6578. break;
  6579. }
  6580. return internalFormat;
  6581. };
  6582. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6583. if (compression === void 0) { compression = null; }
  6584. var internalFormat = this._getInternalFormat(format);
  6585. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6586. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6587. if (compression) {
  6588. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6589. }
  6590. else {
  6591. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6592. }
  6593. if (texture.generateMipMaps) {
  6594. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6595. }
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. this.resetTextureCache();
  6598. texture.isReady = true;
  6599. };
  6600. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6601. if (compression === void 0) { compression = null; }
  6602. var texture = this._gl.createTexture();
  6603. texture._baseWidth = width;
  6604. texture._baseHeight = height;
  6605. texture._width = width;
  6606. texture._height = height;
  6607. texture.references = 1;
  6608. this.updateRawTexture(texture, data, format, invertY, compression);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6610. // Filters
  6611. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6612. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6614. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6615. texture.samplingMode = samplingMode;
  6616. this._loadedTexturesCache.push(texture);
  6617. return texture;
  6618. };
  6619. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6620. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6621. var texture = this._gl.createTexture();
  6622. texture._baseWidth = width;
  6623. texture._baseHeight = height;
  6624. if (forceExponantOfTwo) {
  6625. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6626. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6627. }
  6628. this.resetTextureCache();
  6629. texture._width = width;
  6630. texture._height = height;
  6631. texture.isReady = false;
  6632. texture.generateMipMaps = generateMipMaps;
  6633. texture.references = 1;
  6634. texture.samplingMode = samplingMode;
  6635. this.updateTextureSamplingMode(samplingMode, texture);
  6636. this._loadedTexturesCache.push(texture);
  6637. return texture;
  6638. };
  6639. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6640. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6641. if (texture.isCube) {
  6642. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6643. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6644. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6645. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6646. }
  6647. else {
  6648. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6650. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6651. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6652. }
  6653. };
  6654. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6655. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6656. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6657. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6658. if (texture.generateMipMaps) {
  6659. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6660. }
  6661. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6662. this.resetTextureCache();
  6663. texture.isReady = true;
  6664. };
  6665. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6666. if (texture._isDisabled) {
  6667. return;
  6668. }
  6669. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6670. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6671. try {
  6672. // Testing video texture support
  6673. if (this._videoTextureSupported === undefined) {
  6674. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6675. if (this._gl.getError() !== 0) {
  6676. this._videoTextureSupported = false;
  6677. }
  6678. else {
  6679. this._videoTextureSupported = true;
  6680. }
  6681. }
  6682. // Copy video through the current working canvas if video texture is not supported
  6683. if (!this._videoTextureSupported) {
  6684. if (!texture._workingCanvas) {
  6685. texture._workingCanvas = document.createElement("canvas");
  6686. texture._workingContext = texture._workingCanvas.getContext("2d");
  6687. texture._workingCanvas.width = texture._width;
  6688. texture._workingCanvas.height = texture._height;
  6689. }
  6690. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6692. }
  6693. else {
  6694. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6695. }
  6696. if (texture.generateMipMaps) {
  6697. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6698. }
  6699. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6700. this.resetTextureCache();
  6701. texture.isReady = true;
  6702. }
  6703. catch (ex) {
  6704. // Something unexpected
  6705. // Let's disable the texture
  6706. texture._isDisabled = true;
  6707. }
  6708. };
  6709. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6710. // old version had a "generateMipMaps" arg instead of options.
  6711. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6712. // in the same way, generateDepthBuffer is defaulted to true
  6713. var generateMipMaps = false;
  6714. var generateDepthBuffer = true;
  6715. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6716. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6717. if (options !== undefined) {
  6718. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6719. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6720. type = options.type === undefined ? type : options.type;
  6721. if (options.samplingMode !== undefined) {
  6722. samplingMode = options.samplingMode;
  6723. }
  6724. if (type === Engine.TEXTURETYPE_FLOAT) {
  6725. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6726. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6727. }
  6728. }
  6729. var gl = this._gl;
  6730. var texture = gl.createTexture();
  6731. gl.bindTexture(gl.TEXTURE_2D, texture);
  6732. var width = size.width || size;
  6733. var height = size.height || size;
  6734. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6735. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6736. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6737. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6738. }
  6739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6743. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6744. var depthBuffer;
  6745. // Create the depth buffer
  6746. if (generateDepthBuffer) {
  6747. depthBuffer = gl.createRenderbuffer();
  6748. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6749. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6750. }
  6751. // Create the framebuffer
  6752. var framebuffer = gl.createFramebuffer();
  6753. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6754. if (generateDepthBuffer) {
  6755. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6756. }
  6757. if (generateMipMaps) {
  6758. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6759. }
  6760. // Unbind
  6761. gl.bindTexture(gl.TEXTURE_2D, null);
  6762. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6763. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6764. texture._framebuffer = framebuffer;
  6765. if (generateDepthBuffer) {
  6766. texture._depthBuffer = depthBuffer;
  6767. }
  6768. texture._width = width;
  6769. texture._height = height;
  6770. texture.isReady = true;
  6771. texture.generateMipMaps = generateMipMaps;
  6772. texture.references = 1;
  6773. texture.samplingMode = samplingMode;
  6774. this.resetTextureCache();
  6775. this._loadedTexturesCache.push(texture);
  6776. return texture;
  6777. };
  6778. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6779. var gl = this._gl;
  6780. var texture = gl.createTexture();
  6781. var generateMipMaps = true;
  6782. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6783. if (options !== undefined) {
  6784. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6785. if (options.samplingMode !== undefined) {
  6786. samplingMode = options.samplingMode;
  6787. }
  6788. }
  6789. texture.isCube = true;
  6790. texture.references = 1;
  6791. texture.generateMipMaps = generateMipMaps;
  6792. texture.references = 1;
  6793. texture.samplingMode = samplingMode;
  6794. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6795. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6796. for (var face = 0; face < 6; face++) {
  6797. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6798. }
  6799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6803. // Create the depth buffer
  6804. var depthBuffer = gl.createRenderbuffer();
  6805. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6806. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6807. // Create the framebuffer
  6808. var framebuffer = gl.createFramebuffer();
  6809. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6810. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6811. // Mipmaps
  6812. if (texture.generateMipMaps) {
  6813. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6815. }
  6816. // Unbind
  6817. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6818. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6819. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6820. texture._framebuffer = framebuffer;
  6821. texture._depthBuffer = depthBuffer;
  6822. this.resetTextureCache();
  6823. texture._width = size;
  6824. texture._height = size;
  6825. texture.isReady = true;
  6826. return texture;
  6827. };
  6828. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6829. var _this = this;
  6830. var gl = this._gl;
  6831. var texture = gl.createTexture();
  6832. texture.isCube = true;
  6833. texture.url = rootUrl;
  6834. texture.references = 1;
  6835. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6836. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6837. if (isDDS) {
  6838. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6839. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6840. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6841. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6842. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6843. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6844. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. }
  6847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6851. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6852. _this.resetTextureCache();
  6853. texture._width = info.width;
  6854. texture._height = info.height;
  6855. texture.isReady = true;
  6856. }, null, null, true);
  6857. }
  6858. else {
  6859. cascadeLoad(rootUrl, scene, function (imgs) {
  6860. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6861. var height = width;
  6862. _this._prepareWorkingCanvas();
  6863. _this._workingCanvas.width = width;
  6864. _this._workingCanvas.height = height;
  6865. var faces = [
  6866. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6867. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6868. ];
  6869. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6870. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6871. for (var index = 0; index < faces.length; index++) {
  6872. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6873. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6874. }
  6875. if (!noMipmap) {
  6876. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6877. }
  6878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6882. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6883. _this.resetTextureCache();
  6884. texture._width = width;
  6885. texture._height = height;
  6886. texture.isReady = true;
  6887. }, files);
  6888. }
  6889. return texture;
  6890. };
  6891. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6892. var _this = this;
  6893. var gl = this._gl;
  6894. var texture = gl.createTexture();
  6895. scene._addPendingData(texture);
  6896. texture.isCube = true;
  6897. texture.references = 1;
  6898. texture.url = url;
  6899. var internalFormat = this._getInternalFormat(format);
  6900. var textureType = gl.UNSIGNED_BYTE;
  6901. if (type === Engine.TEXTURETYPE_FLOAT) {
  6902. textureType = gl.FLOAT;
  6903. }
  6904. var width = size;
  6905. var height = width;
  6906. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6907. texture._width = width;
  6908. texture._height = height;
  6909. var onerror = function () {
  6910. scene._removePendingData(texture);
  6911. };
  6912. var internalCallback = function (data) {
  6913. var rgbeDataArrays = callback(data);
  6914. var facesIndex = [
  6915. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6916. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6917. ];
  6918. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6919. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6920. if (!noMipmap && isPot) {
  6921. if (mipmmapGenerator) {
  6922. var arrayTemp = [];
  6923. // Data are known to be in +X +Y +Z -X -Y -Z
  6924. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6925. arrayTemp.push(rgbeDataArrays[0]); // +X
  6926. arrayTemp.push(rgbeDataArrays[3]); // -X
  6927. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6928. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6929. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6930. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6931. var mipData = mipmmapGenerator(arrayTemp);
  6932. for (var level = 0; level < mipData.length; level++) {
  6933. var mipSize = width >> level;
  6934. // mipData is order in +X -X +Y -Y +Z -Z
  6935. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6936. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6937. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6938. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6939. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6940. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6941. }
  6942. }
  6943. else {
  6944. // Data are known to be in +X +Y +Z -X -Y -Z
  6945. for (var index = 0; index < facesIndex.length; index++) {
  6946. var faceData = rgbeDataArrays[index];
  6947. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6948. }
  6949. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6950. }
  6951. }
  6952. else {
  6953. noMipmap = true;
  6954. }
  6955. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6958. }
  6959. else {
  6960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6962. }
  6963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6965. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6966. texture.isReady = true;
  6967. _this.resetTextureCache();
  6968. scene._removePendingData(texture);
  6969. };
  6970. BABYLON.Tools.LoadFile(url, function (data) {
  6971. internalCallback(data);
  6972. }, onerror, scene.database, true);
  6973. return texture;
  6974. };
  6975. ;
  6976. Engine.prototype._releaseTexture = function (texture) {
  6977. var gl = this._gl;
  6978. if (texture._framebuffer) {
  6979. gl.deleteFramebuffer(texture._framebuffer);
  6980. }
  6981. if (texture._depthBuffer) {
  6982. gl.deleteRenderbuffer(texture._depthBuffer);
  6983. }
  6984. gl.deleteTexture(texture);
  6985. // Unbind channels
  6986. this.unbindAllTextures();
  6987. var index = this._loadedTexturesCache.indexOf(texture);
  6988. if (index !== -1) {
  6989. this._loadedTexturesCache.splice(index, 1);
  6990. }
  6991. };
  6992. Engine.prototype.bindSamplers = function (effect) {
  6993. this._gl.useProgram(effect.getProgram());
  6994. var samplers = effect.getSamplers();
  6995. for (var index = 0; index < samplers.length; index++) {
  6996. var uniform = effect.getUniform(samplers[index]);
  6997. this._gl.uniform1i(uniform, index);
  6998. }
  6999. this._currentEffect = null;
  7000. };
  7001. Engine.prototype._bindTexture = function (channel, texture) {
  7002. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7003. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7004. this._activeTexturesCache[channel] = null;
  7005. };
  7006. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7007. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7008. };
  7009. Engine.prototype.unbindAllTextures = function () {
  7010. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7011. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7012. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7013. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7014. this._activeTexturesCache[channel] = null;
  7015. }
  7016. };
  7017. Engine.prototype.setTexture = function (channel, texture) {
  7018. if (channel < 0) {
  7019. return;
  7020. }
  7021. // Not ready?
  7022. if (!texture || !texture.isReady()) {
  7023. if (this._activeTexturesCache[channel] != null) {
  7024. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7025. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7026. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7027. this._activeTexturesCache[channel] = null;
  7028. }
  7029. return;
  7030. }
  7031. // Video
  7032. var alreadyActivated = false;
  7033. if (texture instanceof BABYLON.VideoTexture) {
  7034. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7035. alreadyActivated = true;
  7036. texture.update();
  7037. }
  7038. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7039. texture.delayLoad();
  7040. return;
  7041. }
  7042. if (this._activeTexturesCache[channel] === texture) {
  7043. return;
  7044. }
  7045. this._activeTexturesCache[channel] = texture;
  7046. var internalTexture = texture.getInternalTexture();
  7047. if (!alreadyActivated) {
  7048. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7049. }
  7050. if (internalTexture.isCube) {
  7051. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7052. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7053. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7054. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7055. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7056. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7057. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7058. }
  7059. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7060. }
  7061. else {
  7062. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7063. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7064. internalTexture._cachedWrapU = texture.wrapU;
  7065. switch (texture.wrapU) {
  7066. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7067. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7068. break;
  7069. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7070. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7071. break;
  7072. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7073. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7074. break;
  7075. }
  7076. }
  7077. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7078. internalTexture._cachedWrapV = texture.wrapV;
  7079. switch (texture.wrapV) {
  7080. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7081. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7082. break;
  7083. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7085. break;
  7086. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7087. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7088. break;
  7089. }
  7090. }
  7091. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7092. }
  7093. };
  7094. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7095. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7096. var value = texture.anisotropicFilteringLevel;
  7097. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7098. value = 1;
  7099. }
  7100. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7101. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7102. texture._cachedAnisotropicFilteringLevel = value;
  7103. }
  7104. };
  7105. Engine.prototype.readPixels = function (x, y, width, height) {
  7106. var data = new Uint8Array(height * width * 4);
  7107. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7108. return data;
  7109. };
  7110. Engine.prototype.releaseInternalTexture = function (texture) {
  7111. if (!texture) {
  7112. return;
  7113. }
  7114. texture.references--;
  7115. // Final reference ?
  7116. if (texture.references === 0) {
  7117. var texturesCache = this.getLoadedTexturesCache();
  7118. var index = texturesCache.indexOf(texture);
  7119. if (index > -1) {
  7120. texturesCache.splice(index, 1);
  7121. }
  7122. this._releaseTexture(texture);
  7123. }
  7124. };
  7125. // Dispose
  7126. Engine.prototype.dispose = function () {
  7127. this.hideLoadingUI();
  7128. this.stopRenderLoop();
  7129. // Release scenes
  7130. while (this.scenes.length) {
  7131. this.scenes[0].dispose();
  7132. }
  7133. // Release audio engine
  7134. Engine.audioEngine.dispose();
  7135. // Release effects
  7136. for (var name in this._compiledEffects) {
  7137. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7138. }
  7139. // Unbind
  7140. for (var i in this._vertexAttribArrays) {
  7141. //making sure this is a string
  7142. var iAsNumber = +i;
  7143. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7144. continue;
  7145. }
  7146. this._gl.disableVertexAttribArray(iAsNumber);
  7147. }
  7148. this._gl = null;
  7149. // Events
  7150. window.removeEventListener("blur", this._onBlur);
  7151. window.removeEventListener("focus", this._onFocus);
  7152. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7153. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7154. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7155. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7156. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7157. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7158. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7159. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7160. };
  7161. // Loading screen
  7162. Engine.prototype.displayLoadingUI = function () {
  7163. this._loadingScreen.displayLoadingUI();
  7164. };
  7165. Engine.prototype.hideLoadingUI = function () {
  7166. this._loadingScreen.hideLoadingUI();
  7167. };
  7168. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7169. get: function () {
  7170. return this._loadingScreen;
  7171. },
  7172. set: function (loadingScreen) {
  7173. this._loadingScreen = loadingScreen;
  7174. },
  7175. enumerable: true,
  7176. configurable: true
  7177. });
  7178. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7179. set: function (text) {
  7180. this._loadingScreen.loadingUIText = text;
  7181. },
  7182. enumerable: true,
  7183. configurable: true
  7184. });
  7185. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7186. set: function (color) {
  7187. this._loadingScreen.loadingUIBackgroundColor = color;
  7188. },
  7189. enumerable: true,
  7190. configurable: true
  7191. });
  7192. // FPS
  7193. Engine.prototype.getFps = function () {
  7194. return this.fps;
  7195. };
  7196. Engine.prototype.getDeltaTime = function () {
  7197. return this.deltaTime;
  7198. };
  7199. Engine.prototype._measureFps = function () {
  7200. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7201. var length = this.previousFramesDuration.length;
  7202. if (length >= 2) {
  7203. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7204. }
  7205. if (length >= this.fpsRange) {
  7206. if (length > this.fpsRange) {
  7207. this.previousFramesDuration.splice(0, 1);
  7208. length = this.previousFramesDuration.length;
  7209. }
  7210. var sum = 0;
  7211. for (var id = 0; id < length - 1; id++) {
  7212. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7213. }
  7214. this.fps = 1000.0 / (sum / (length - 1));
  7215. }
  7216. };
  7217. // Statics
  7218. Engine.isSupported = function () {
  7219. try {
  7220. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7221. if (navigator.isCocoonJS) {
  7222. return true;
  7223. }
  7224. var tempcanvas = document.createElement("canvas");
  7225. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7226. return gl != null && !!window.WebGLRenderingContext;
  7227. }
  7228. catch (e) {
  7229. return false;
  7230. }
  7231. };
  7232. // Const statics
  7233. Engine._ALPHA_DISABLE = 0;
  7234. Engine._ALPHA_ADD = 1;
  7235. Engine._ALPHA_COMBINE = 2;
  7236. Engine._ALPHA_SUBTRACT = 3;
  7237. Engine._ALPHA_MULTIPLY = 4;
  7238. Engine._ALPHA_MAXIMIZED = 5;
  7239. Engine._ALPHA_ONEONE = 6;
  7240. Engine._DELAYLOADSTATE_NONE = 0;
  7241. Engine._DELAYLOADSTATE_LOADED = 1;
  7242. Engine._DELAYLOADSTATE_LOADING = 2;
  7243. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7244. Engine._TEXTUREFORMAT_ALPHA = 0;
  7245. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7246. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7247. Engine._TEXTUREFORMAT_RGB = 4;
  7248. Engine._TEXTUREFORMAT_RGBA = 5;
  7249. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7250. Engine._TEXTURETYPE_FLOAT = 1;
  7251. // Updatable statics so stick with vars here
  7252. Engine.Epsilon = 0.001;
  7253. Engine.CollisionsEpsilon = 0.001;
  7254. Engine.CodeRepository = "src/";
  7255. Engine.ShadersRepository = "src/Shaders/";
  7256. return Engine;
  7257. })();
  7258. BABYLON.Engine = Engine;
  7259. })(BABYLON || (BABYLON = {}));
  7260. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7261. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7262. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7263. 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;
  7264. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7265. };
  7266. var BABYLON;
  7267. (function (BABYLON) {
  7268. /**
  7269. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7270. */
  7271. var Node = (function () {
  7272. /**
  7273. * @constructor
  7274. * @param {string} name - the name and id to be given to this node
  7275. * @param {BABYLON.Scene} the scene this node will be added to
  7276. */
  7277. function Node(name, scene) {
  7278. this.state = "";
  7279. this.animations = new Array();
  7280. this._ranges = {};
  7281. this._childrenFlag = -1;
  7282. this._isEnabled = true;
  7283. this._isReady = true;
  7284. this._currentRenderId = -1;
  7285. this._parentRenderId = -1;
  7286. this.name = name;
  7287. this.id = name;
  7288. this._scene = scene;
  7289. this._initCache();
  7290. }
  7291. Node.prototype.getScene = function () {
  7292. return this._scene;
  7293. };
  7294. Node.prototype.getEngine = function () {
  7295. return this._scene.getEngine();
  7296. };
  7297. // override it in derived class
  7298. Node.prototype.getWorldMatrix = function () {
  7299. return BABYLON.Matrix.Identity();
  7300. };
  7301. // override it in derived class if you add new variables to the cache
  7302. // and call the parent class method
  7303. Node.prototype._initCache = function () {
  7304. this._cache = {};
  7305. this._cache.parent = undefined;
  7306. };
  7307. Node.prototype.updateCache = function (force) {
  7308. if (!force && this.isSynchronized())
  7309. return;
  7310. this._cache.parent = this.parent;
  7311. this._updateCache();
  7312. };
  7313. // override it in derived class if you add new variables to the cache
  7314. // and call the parent class method if !ignoreParentClass
  7315. Node.prototype._updateCache = function (ignoreParentClass) {
  7316. };
  7317. // override it in derived class if you add new variables to the cache
  7318. Node.prototype._isSynchronized = function () {
  7319. return true;
  7320. };
  7321. Node.prototype._markSyncedWithParent = function () {
  7322. this._parentRenderId = this.parent._currentRenderId;
  7323. };
  7324. Node.prototype.isSynchronizedWithParent = function () {
  7325. if (!this.parent) {
  7326. return true;
  7327. }
  7328. if (this._parentRenderId !== this.parent._currentRenderId) {
  7329. return false;
  7330. }
  7331. return this.parent.isSynchronized();
  7332. };
  7333. Node.prototype.isSynchronized = function (updateCache) {
  7334. var check = this.hasNewParent();
  7335. check = check || !this.isSynchronizedWithParent();
  7336. check = check || !this._isSynchronized();
  7337. if (updateCache)
  7338. this.updateCache(true);
  7339. return !check;
  7340. };
  7341. Node.prototype.hasNewParent = function (update) {
  7342. if (this._cache.parent === this.parent)
  7343. return false;
  7344. if (update)
  7345. this._cache.parent = this.parent;
  7346. return true;
  7347. };
  7348. /**
  7349. * Is this node ready to be used/rendered
  7350. * @return {boolean} is it ready
  7351. */
  7352. Node.prototype.isReady = function () {
  7353. return this._isReady;
  7354. };
  7355. /**
  7356. * Is this node enabled.
  7357. * If the node has a parent and is enabled, the parent will be inspected as well.
  7358. * @return {boolean} whether this node (and its parent) is enabled.
  7359. * @see setEnabled
  7360. */
  7361. Node.prototype.isEnabled = function () {
  7362. if (!this._isEnabled) {
  7363. return false;
  7364. }
  7365. if (this.parent) {
  7366. return this.parent.isEnabled();
  7367. }
  7368. return true;
  7369. };
  7370. /**
  7371. * Set the enabled state of this node.
  7372. * @param {boolean} value - the new enabled state
  7373. * @see isEnabled
  7374. */
  7375. Node.prototype.setEnabled = function (value) {
  7376. this._isEnabled = value;
  7377. };
  7378. /**
  7379. * Is this node a descendant of the given node.
  7380. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7381. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7382. * @see parent
  7383. */
  7384. Node.prototype.isDescendantOf = function (ancestor) {
  7385. if (this.parent) {
  7386. if (this.parent === ancestor) {
  7387. return true;
  7388. }
  7389. return this.parent.isDescendantOf(ancestor);
  7390. }
  7391. return false;
  7392. };
  7393. Node.prototype._getDescendants = function (list, results, directDecendantsOnly) {
  7394. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7395. for (var index = 0; index < list.length; index++) {
  7396. var item = list[index];
  7397. if ((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) {
  7398. results.push(item);
  7399. }
  7400. }
  7401. };
  7402. /**
  7403. * Will return all nodes that have this node as parent.
  7404. * @return {BABYLON.Node[]} all children nodes of all types.
  7405. */
  7406. Node.prototype.getDescendants = function (directDecendantsOnly) {
  7407. var results = [];
  7408. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7409. this._getDescendants(this._scene.lights, results, directDecendantsOnly);
  7410. this._getDescendants(this._scene.cameras, results, directDecendantsOnly);
  7411. return results;
  7412. };
  7413. /**
  7414. * @Deprecated, legacy support.
  7415. * use getDecendants instead.
  7416. */
  7417. Node.prototype.getChildren = function () {
  7418. return this.getDescendants(true);
  7419. };
  7420. /**
  7421. * Get all child-meshes of this node.
  7422. */
  7423. Node.prototype.getChildMeshes = function (directDecendantsOnly) {
  7424. var results = [];
  7425. this._getDescendants(this._scene.meshes, results, false);
  7426. return results;
  7427. };
  7428. Node.prototype._setReady = function (state) {
  7429. if (state === this._isReady) {
  7430. return;
  7431. }
  7432. if (!state) {
  7433. this._isReady = false;
  7434. return;
  7435. }
  7436. this._isReady = true;
  7437. if (this.onReady) {
  7438. this.onReady(this);
  7439. }
  7440. };
  7441. Node.prototype.getAnimationByName = function (name) {
  7442. for (var i = 0; i < this.animations.length; i++) {
  7443. var animation = this.animations[i];
  7444. if (animation.name === name) {
  7445. return animation;
  7446. }
  7447. }
  7448. return null;
  7449. };
  7450. Node.prototype.createAnimationRange = function (name, from, to) {
  7451. // check name not already in use
  7452. if (!this._ranges[name]) {
  7453. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7454. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7455. if (this.animations[i]) {
  7456. this.animations[i].createRange(name, from, to);
  7457. }
  7458. }
  7459. }
  7460. };
  7461. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7462. if (deleteFrames === void 0) { deleteFrames = true; }
  7463. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7464. if (this.animations[i]) {
  7465. this.animations[i].deleteRange(name, deleteFrames);
  7466. }
  7467. }
  7468. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7469. };
  7470. Node.prototype.getAnimationRange = function (name) {
  7471. return this._ranges[name];
  7472. };
  7473. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7474. var range = this.getAnimationRange(name);
  7475. if (!range) {
  7476. return null;
  7477. }
  7478. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7479. };
  7480. Node.prototype.serializeAnimationRanges = function () {
  7481. var serializationRanges = [];
  7482. for (var name in this._ranges) {
  7483. var range = {};
  7484. range.name = name;
  7485. range.from = this._ranges[name].from;
  7486. range.to = this._ranges[name].to;
  7487. serializationRanges.push(range);
  7488. }
  7489. return serializationRanges;
  7490. };
  7491. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7492. if (parsedNode.ranges) {
  7493. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7494. var data = parsedNode.ranges[index];
  7495. node.createAnimationRange(data.name, data.from, data.to);
  7496. }
  7497. }
  7498. };
  7499. __decorate([
  7500. BABYLON.serialize()
  7501. ], Node.prototype, "name", void 0);
  7502. __decorate([
  7503. BABYLON.serialize()
  7504. ], Node.prototype, "id", void 0);
  7505. __decorate([
  7506. BABYLON.serialize()
  7507. ], Node.prototype, "uniqueId", void 0);
  7508. __decorate([
  7509. BABYLON.serialize()
  7510. ], Node.prototype, "state", void 0);
  7511. return Node;
  7512. })();
  7513. BABYLON.Node = Node;
  7514. })(BABYLON || (BABYLON = {}));
  7515. var BABYLON;
  7516. (function (BABYLON) {
  7517. var FilesInput = (function () {
  7518. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7519. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7520. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7521. this._engine = p_engine;
  7522. this._canvas = p_canvas;
  7523. this._currentScene = p_scene;
  7524. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7525. this._progressCallback = p_progressCallback;
  7526. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7527. this._textureLoadingCallback = p_textureLoadingCallback;
  7528. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7529. }
  7530. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7531. var _this = this;
  7532. if (p_elementToMonitor) {
  7533. this._elementToMonitor = p_elementToMonitor;
  7534. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7535. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7536. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7537. }
  7538. };
  7539. FilesInput.prototype.renderFunction = function () {
  7540. if (this._additionnalRenderLoopLogicCallback) {
  7541. this._additionnalRenderLoopLogicCallback();
  7542. }
  7543. if (this._currentScene) {
  7544. if (this._textureLoadingCallback) {
  7545. var remaining = this._currentScene.getWaitingItemsCount();
  7546. if (remaining > 0) {
  7547. this._textureLoadingCallback(remaining);
  7548. }
  7549. }
  7550. this._currentScene.render();
  7551. }
  7552. };
  7553. FilesInput.prototype.drag = function (e) {
  7554. e.stopPropagation();
  7555. e.preventDefault();
  7556. };
  7557. FilesInput.prototype.drop = function (eventDrop) {
  7558. eventDrop.stopPropagation();
  7559. eventDrop.preventDefault();
  7560. this.loadFiles(eventDrop);
  7561. };
  7562. FilesInput.prototype.loadFiles = function (event) {
  7563. if (this._startingProcessingFilesCallback)
  7564. this._startingProcessingFilesCallback();
  7565. // Handling data transfer via drag'n'drop
  7566. if (event && event.dataTransfer && event.dataTransfer.files) {
  7567. this._filesToLoad = event.dataTransfer.files;
  7568. }
  7569. // Handling files from input files
  7570. if (event && event.target && event.target.files) {
  7571. this._filesToLoad = event.target.files;
  7572. }
  7573. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7574. for (var i = 0; i < this._filesToLoad.length; i++) {
  7575. switch (this._filesToLoad[i].type) {
  7576. case "image/jpeg":
  7577. case "image/png":
  7578. case "image/bmp":
  7579. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7580. break;
  7581. case "image/targa":
  7582. case "image/vnd.ms-dds":
  7583. case "audio/wav":
  7584. case "audio/x-wav":
  7585. case "audio/mp3":
  7586. case "audio/mpeg":
  7587. case "audio/mpeg3":
  7588. case "audio/x-mpeg-3":
  7589. case "audio/ogg":
  7590. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7591. break;
  7592. default:
  7593. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7594. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7595. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7596. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7597. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7598. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7599. this._sceneFileToLoad = this._filesToLoad[i];
  7600. }
  7601. break;
  7602. }
  7603. }
  7604. this.reload();
  7605. }
  7606. };
  7607. FilesInput.prototype.reload = function () {
  7608. var _this = this;
  7609. var that = this;
  7610. // If a ".babylon" file has been provided
  7611. if (this._sceneFileToLoad) {
  7612. if (this._currentScene) {
  7613. if (BABYLON.Tools.errorsCount > 0) {
  7614. BABYLON.Tools.ClearLogCache();
  7615. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7616. }
  7617. this._engine.stopRenderLoop();
  7618. this._currentScene.dispose();
  7619. }
  7620. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7621. that._currentScene = newScene;
  7622. // Wait for textures and shaders to be ready
  7623. that._currentScene.executeWhenReady(function () {
  7624. // Attach camera to canvas inputs
  7625. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7626. that._currentScene.createDefaultCameraOrLight();
  7627. }
  7628. that._currentScene.activeCamera.attachControl(that._canvas);
  7629. if (that._sceneLoadedCallback) {
  7630. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7631. }
  7632. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7633. });
  7634. }, function (progress) {
  7635. if (_this._progressCallback) {
  7636. _this._progressCallback(progress);
  7637. }
  7638. });
  7639. }
  7640. else {
  7641. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7642. }
  7643. };
  7644. FilesInput.FilesTextures = new Array();
  7645. FilesInput.FilesToLoad = new Array();
  7646. return FilesInput;
  7647. })();
  7648. BABYLON.FilesInput = FilesInput;
  7649. })(BABYLON || (BABYLON = {}));
  7650. var BABYLON;
  7651. (function (BABYLON) {
  7652. var IntersectionInfo = (function () {
  7653. function IntersectionInfo(bu, bv, distance) {
  7654. this.bu = bu;
  7655. this.bv = bv;
  7656. this.distance = distance;
  7657. this.faceId = 0;
  7658. this.subMeshId = 0;
  7659. }
  7660. return IntersectionInfo;
  7661. })();
  7662. BABYLON.IntersectionInfo = IntersectionInfo;
  7663. var PickingInfo = (function () {
  7664. function PickingInfo() {
  7665. this.hit = false;
  7666. this.distance = 0;
  7667. this.pickedPoint = null;
  7668. this.pickedMesh = null;
  7669. this.bu = 0;
  7670. this.bv = 0;
  7671. this.faceId = -1;
  7672. this.subMeshId = 0;
  7673. this.pickedSprite = null;
  7674. }
  7675. // Methods
  7676. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7677. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7678. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7679. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7680. return null;
  7681. }
  7682. var indices = this.pickedMesh.getIndices();
  7683. var result;
  7684. if (useVerticesNormals) {
  7685. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7686. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7687. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7688. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7689. normal0 = normal0.scale(this.bu);
  7690. normal1 = normal1.scale(this.bv);
  7691. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7692. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7693. }
  7694. else {
  7695. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7696. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7697. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7698. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7699. var p1p2 = vertex1.subtract(vertex2);
  7700. var p3p2 = vertex3.subtract(vertex2);
  7701. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7702. }
  7703. if (useWorldCoordinates) {
  7704. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7705. }
  7706. return BABYLON.Vector3.Normalize(result);
  7707. };
  7708. PickingInfo.prototype.getTextureCoordinates = function () {
  7709. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7710. return null;
  7711. }
  7712. var indices = this.pickedMesh.getIndices();
  7713. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7714. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7715. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7716. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7717. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7718. uv1 = uv1.scale(this.bu);
  7719. uv2 = uv2.scale(this.bv);
  7720. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7721. };
  7722. return PickingInfo;
  7723. })();
  7724. BABYLON.PickingInfo = PickingInfo;
  7725. })(BABYLON || (BABYLON = {}));
  7726. var BABYLON;
  7727. (function (BABYLON) {
  7728. var BoundingSphere = (function () {
  7729. function BoundingSphere(minimum, maximum) {
  7730. this.minimum = minimum;
  7731. this.maximum = maximum;
  7732. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7733. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7734. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7735. this.radius = distance * 0.5;
  7736. this.centerWorld = BABYLON.Vector3.Zero();
  7737. this._update(BABYLON.Matrix.Identity());
  7738. }
  7739. // Methods
  7740. BoundingSphere.prototype._update = function (world) {
  7741. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7742. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7743. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7744. };
  7745. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7746. for (var i = 0; i < 6; i++) {
  7747. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7748. return false;
  7749. }
  7750. return true;
  7751. };
  7752. BoundingSphere.prototype.intersectsPoint = function (point) {
  7753. var x = this.centerWorld.x - point.x;
  7754. var y = this.centerWorld.y - point.y;
  7755. var z = this.centerWorld.z - point.z;
  7756. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7757. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7758. return false;
  7759. return true;
  7760. };
  7761. // Statics
  7762. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7763. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7764. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7765. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7766. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7767. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7768. return false;
  7769. return true;
  7770. };
  7771. return BoundingSphere;
  7772. })();
  7773. BABYLON.BoundingSphere = BoundingSphere;
  7774. })(BABYLON || (BABYLON = {}));
  7775. var BABYLON;
  7776. (function (BABYLON) {
  7777. var BoundingBox = (function () {
  7778. function BoundingBox(minimum, maximum) {
  7779. this.minimum = minimum;
  7780. this.maximum = maximum;
  7781. this.vectors = new Array();
  7782. this.vectorsWorld = new Array();
  7783. // Bounding vectors
  7784. this.vectors.push(this.minimum.clone());
  7785. this.vectors.push(this.maximum.clone());
  7786. this.vectors.push(this.minimum.clone());
  7787. this.vectors[2].x = this.maximum.x;
  7788. this.vectors.push(this.minimum.clone());
  7789. this.vectors[3].y = this.maximum.y;
  7790. this.vectors.push(this.minimum.clone());
  7791. this.vectors[4].z = this.maximum.z;
  7792. this.vectors.push(this.maximum.clone());
  7793. this.vectors[5].z = this.minimum.z;
  7794. this.vectors.push(this.maximum.clone());
  7795. this.vectors[6].x = this.minimum.x;
  7796. this.vectors.push(this.maximum.clone());
  7797. this.vectors[7].y = this.minimum.y;
  7798. // OBB
  7799. this.center = this.maximum.add(this.minimum).scale(0.5);
  7800. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7801. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7802. // World
  7803. for (var index = 0; index < this.vectors.length; index++) {
  7804. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7805. }
  7806. this.minimumWorld = BABYLON.Vector3.Zero();
  7807. this.maximumWorld = BABYLON.Vector3.Zero();
  7808. this._update(BABYLON.Matrix.Identity());
  7809. }
  7810. // Methods
  7811. BoundingBox.prototype.getWorldMatrix = function () {
  7812. return this._worldMatrix;
  7813. };
  7814. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7815. this._worldMatrix.copyFrom(matrix);
  7816. return this;
  7817. };
  7818. BoundingBox.prototype._update = function (world) {
  7819. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7820. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7821. for (var index = 0; index < this.vectors.length; index++) {
  7822. var v = this.vectorsWorld[index];
  7823. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7824. if (v.x < this.minimumWorld.x)
  7825. this.minimumWorld.x = v.x;
  7826. if (v.y < this.minimumWorld.y)
  7827. this.minimumWorld.y = v.y;
  7828. if (v.z < this.minimumWorld.z)
  7829. this.minimumWorld.z = v.z;
  7830. if (v.x > this.maximumWorld.x)
  7831. this.maximumWorld.x = v.x;
  7832. if (v.y > this.maximumWorld.y)
  7833. this.maximumWorld.y = v.y;
  7834. if (v.z > this.maximumWorld.z)
  7835. this.maximumWorld.z = v.z;
  7836. }
  7837. // OBB
  7838. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7839. this.center.scaleInPlace(0.5);
  7840. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7841. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7842. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7843. this._worldMatrix = world;
  7844. };
  7845. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7846. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7847. };
  7848. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7849. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7850. };
  7851. BoundingBox.prototype.intersectsPoint = function (point) {
  7852. var delta = -BABYLON.Engine.Epsilon;
  7853. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7854. return false;
  7855. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7856. return false;
  7857. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7858. return false;
  7859. return true;
  7860. };
  7861. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7862. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7863. };
  7864. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7865. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7866. return false;
  7867. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7868. return false;
  7869. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7870. return false;
  7871. return true;
  7872. };
  7873. // Statics
  7874. BoundingBox.Intersects = function (box0, box1) {
  7875. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7876. return false;
  7877. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7878. return false;
  7879. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7880. return false;
  7881. return true;
  7882. };
  7883. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7884. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7885. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7886. return (num <= (sphereRadius * sphereRadius));
  7887. };
  7888. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7889. for (var p = 0; p < 6; p++) {
  7890. for (var i = 0; i < 8; i++) {
  7891. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7892. return false;
  7893. }
  7894. }
  7895. }
  7896. return true;
  7897. };
  7898. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7899. for (var p = 0; p < 6; p++) {
  7900. var inCount = 8;
  7901. for (var i = 0; i < 8; i++) {
  7902. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7903. --inCount;
  7904. }
  7905. else {
  7906. break;
  7907. }
  7908. }
  7909. if (inCount === 0)
  7910. return false;
  7911. }
  7912. return true;
  7913. };
  7914. return BoundingBox;
  7915. })();
  7916. BABYLON.BoundingBox = BoundingBox;
  7917. })(BABYLON || (BABYLON = {}));
  7918. var BABYLON;
  7919. (function (BABYLON) {
  7920. var computeBoxExtents = function (axis, box) {
  7921. var p = BABYLON.Vector3.Dot(box.center, axis);
  7922. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7923. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7924. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7925. var r = r0 + r1 + r2;
  7926. return {
  7927. min: p - r,
  7928. max: p + r
  7929. };
  7930. };
  7931. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7932. var axisOverlap = function (axis, box0, box1) {
  7933. var result0 = computeBoxExtents(axis, box0);
  7934. var result1 = computeBoxExtents(axis, box1);
  7935. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7936. };
  7937. var BoundingInfo = (function () {
  7938. function BoundingInfo(minimum, maximum) {
  7939. this.minimum = minimum;
  7940. this.maximum = maximum;
  7941. this._isLocked = false;
  7942. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7943. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7944. }
  7945. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7946. get: function () {
  7947. return this._isLocked;
  7948. },
  7949. set: function (value) {
  7950. this._isLocked = value;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. // Methods
  7956. BoundingInfo.prototype.update = function (world) {
  7957. if (this._isLocked) {
  7958. return;
  7959. }
  7960. this.boundingBox._update(world);
  7961. this.boundingSphere._update(world);
  7962. };
  7963. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7964. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7965. return false;
  7966. return this.boundingBox.isInFrustum(frustumPlanes);
  7967. };
  7968. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7969. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7970. };
  7971. BoundingInfo.prototype._checkCollision = function (collider) {
  7972. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7973. };
  7974. BoundingInfo.prototype.intersectsPoint = function (point) {
  7975. if (!this.boundingSphere.centerWorld) {
  7976. return false;
  7977. }
  7978. if (!this.boundingSphere.intersectsPoint(point)) {
  7979. return false;
  7980. }
  7981. if (!this.boundingBox.intersectsPoint(point)) {
  7982. return false;
  7983. }
  7984. return true;
  7985. };
  7986. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7987. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7988. return false;
  7989. }
  7990. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7991. return false;
  7992. }
  7993. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7994. return false;
  7995. }
  7996. if (!precise) {
  7997. return true;
  7998. }
  7999. var box0 = this.boundingBox;
  8000. var box1 = boundingInfo.boundingBox;
  8001. if (!axisOverlap(box0.directions[0], box0, box1))
  8002. return false;
  8003. if (!axisOverlap(box0.directions[1], box0, box1))
  8004. return false;
  8005. if (!axisOverlap(box0.directions[2], box0, box1))
  8006. return false;
  8007. if (!axisOverlap(box1.directions[0], box0, box1))
  8008. return false;
  8009. if (!axisOverlap(box1.directions[1], box0, box1))
  8010. return false;
  8011. if (!axisOverlap(box1.directions[2], box0, box1))
  8012. return false;
  8013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8014. return false;
  8015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8016. return false;
  8017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8018. return false;
  8019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8020. return false;
  8021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8022. return false;
  8023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8024. return false;
  8025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8026. return false;
  8027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8028. return false;
  8029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8030. return false;
  8031. return true;
  8032. };
  8033. return BoundingInfo;
  8034. })();
  8035. BABYLON.BoundingInfo = BoundingInfo;
  8036. })(BABYLON || (BABYLON = {}));
  8037. var BABYLON;
  8038. (function (BABYLON) {
  8039. var AbstractMesh = (function (_super) {
  8040. __extends(AbstractMesh, _super);
  8041. // Constructor
  8042. function AbstractMesh(name, scene) {
  8043. var _this = this;
  8044. _super.call(this, name, scene);
  8045. // Properties
  8046. this.definedFacingForward = true; // orientation for POV movement & rotation
  8047. this.position = new BABYLON.Vector3(0, 0, 0);
  8048. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8049. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8050. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8051. this.visibility = 1.0;
  8052. this.alphaIndex = Number.MAX_VALUE;
  8053. this.infiniteDistance = false;
  8054. this.isVisible = true;
  8055. this.isPickable = true;
  8056. this.showBoundingBox = false;
  8057. this.showSubMeshesBoundingBox = false;
  8058. this.onDispose = null;
  8059. this.isBlocker = false;
  8060. this.renderingGroupId = 0;
  8061. this.receiveShadows = false;
  8062. this.renderOutline = false;
  8063. this.outlineColor = BABYLON.Color3.Red();
  8064. this.outlineWidth = 0.02;
  8065. this.renderOverlay = false;
  8066. this.overlayColor = BABYLON.Color3.Red();
  8067. this.overlayAlpha = 0.5;
  8068. this.hasVertexAlpha = false;
  8069. this.useVertexColors = true;
  8070. this.applyFog = true;
  8071. this.computeBonesUsingShaders = true;
  8072. this.scalingDeterminant = 1;
  8073. this.numBoneInfluencers = 4;
  8074. this.useOctreeForRenderingSelection = true;
  8075. this.useOctreeForPicking = true;
  8076. this.useOctreeForCollisions = true;
  8077. this.layerMask = 0x0FFFFFFF;
  8078. this.alwaysSelectAsActiveMesh = false;
  8079. // Collisions
  8080. this._checkCollisions = false;
  8081. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8082. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8083. this._collider = new BABYLON.Collider();
  8084. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8085. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8086. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8087. // Edges
  8088. this.edgesWidth = 1;
  8089. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8090. // Cache
  8091. this._localWorld = BABYLON.Matrix.Zero();
  8092. this._worldMatrix = BABYLON.Matrix.Zero();
  8093. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8094. this._absolutePosition = BABYLON.Vector3.Zero();
  8095. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8096. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8097. this._isDirty = false;
  8098. this._pivotMatrix = BABYLON.Matrix.Identity();
  8099. this._isDisposed = false;
  8100. this._renderId = 0;
  8101. this._intersectionsInProgress = new Array();
  8102. this._onAfterWorldMatrixUpdate = new Array();
  8103. this._isWorldMatrixFrozen = false;
  8104. this._unIndexed = false;
  8105. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8106. if (collidedMesh === void 0) { collidedMesh = null; }
  8107. //TODO move this to the collision coordinator!
  8108. if (_this.getScene().workerCollisions)
  8109. newPosition.multiplyInPlace(_this._collider.radius);
  8110. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8111. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8112. _this.position.addInPlace(_this._diffPositionForCollisions);
  8113. }
  8114. if (_this.onCollide && collidedMesh) {
  8115. _this.onCollide(collidedMesh);
  8116. }
  8117. if (_this.onCollisionPositionChange) {
  8118. _this.onCollisionPositionChange(_this.position);
  8119. }
  8120. };
  8121. scene.addMesh(this);
  8122. }
  8123. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8124. get: function () {
  8125. return AbstractMesh._BILLBOARDMODE_NONE;
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8131. get: function () {
  8132. return AbstractMesh._BILLBOARDMODE_X;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8138. get: function () {
  8139. return AbstractMesh._BILLBOARDMODE_Y;
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8145. get: function () {
  8146. return AbstractMesh._BILLBOARDMODE_Z;
  8147. },
  8148. enumerable: true,
  8149. configurable: true
  8150. });
  8151. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8152. get: function () {
  8153. return AbstractMesh._BILLBOARDMODE_ALL;
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8159. get: function () {
  8160. return this._skeleton;
  8161. },
  8162. set: function (value) {
  8163. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8164. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8165. }
  8166. if (value && value.needInitialSkinMatrix) {
  8167. value._registerMeshWithPoseMatrix(this);
  8168. }
  8169. this._skeleton = value;
  8170. if (!this._skeleton) {
  8171. this._bonesTransformMatrices = null;
  8172. }
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8178. /**
  8179. * Getting the rotation object.
  8180. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8181. */
  8182. get: function () {
  8183. return this._rotation;
  8184. },
  8185. set: function (newRotation) {
  8186. this._rotation = newRotation;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8192. get: function () {
  8193. return this._scaling;
  8194. },
  8195. set: function (newScaling) {
  8196. this._scaling = newScaling;
  8197. if (this.physicsImpostor) {
  8198. this.physicsImpostor.forceUpdate();
  8199. }
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8205. get: function () {
  8206. return this._rotationQuaternion;
  8207. },
  8208. set: function (quaternion) {
  8209. this._rotationQuaternion = quaternion;
  8210. //reset the rotation vector.
  8211. if (this.rotation.length()) {
  8212. this.rotation.copyFromFloats(0, 0, 0);
  8213. }
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. // Methods
  8219. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8220. this._poseMatrix.copyFrom(matrix);
  8221. };
  8222. AbstractMesh.prototype.getPoseMatrix = function () {
  8223. return this._poseMatrix;
  8224. };
  8225. AbstractMesh.prototype.disableEdgesRendering = function () {
  8226. if (this._edgesRenderer !== undefined) {
  8227. this._edgesRenderer.dispose();
  8228. this._edgesRenderer = undefined;
  8229. }
  8230. };
  8231. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8232. if (epsilon === void 0) { epsilon = 0.95; }
  8233. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8234. this.disableEdgesRendering();
  8235. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8236. };
  8237. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8238. get: function () {
  8239. return false;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. AbstractMesh.prototype.getLOD = function (camera) {
  8245. return this;
  8246. };
  8247. AbstractMesh.prototype.getTotalVertices = function () {
  8248. return 0;
  8249. };
  8250. AbstractMesh.prototype.getIndices = function () {
  8251. return null;
  8252. };
  8253. AbstractMesh.prototype.getVerticesData = function (kind) {
  8254. return null;
  8255. };
  8256. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8257. return false;
  8258. };
  8259. AbstractMesh.prototype.getBoundingInfo = function () {
  8260. if (this._masterMesh) {
  8261. return this._masterMesh.getBoundingInfo();
  8262. }
  8263. if (!this._boundingInfo) {
  8264. this._updateBoundingInfo();
  8265. }
  8266. return this._boundingInfo;
  8267. };
  8268. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8269. get: function () {
  8270. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. AbstractMesh.prototype._preActivate = function () {
  8276. };
  8277. AbstractMesh.prototype._activate = function (renderId) {
  8278. this._renderId = renderId;
  8279. };
  8280. AbstractMesh.prototype.getWorldMatrix = function () {
  8281. if (this._masterMesh) {
  8282. return this._masterMesh.getWorldMatrix();
  8283. }
  8284. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8285. this.computeWorldMatrix();
  8286. }
  8287. return this._worldMatrix;
  8288. };
  8289. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8290. get: function () {
  8291. return this._worldMatrix;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8297. get: function () {
  8298. return this._absolutePosition;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8304. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8305. this.computeWorldMatrix(true);
  8306. this._isWorldMatrixFrozen = true;
  8307. };
  8308. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8309. this._isWorldMatrixFrozen = false;
  8310. this.computeWorldMatrix(true);
  8311. };
  8312. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8313. get: function () {
  8314. return this._isWorldMatrixFrozen;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8320. axis.normalize();
  8321. if (!this.rotationQuaternion) {
  8322. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8323. this.rotation = BABYLON.Vector3.Zero();
  8324. }
  8325. var rotationQuaternion;
  8326. if (!space || space === BABYLON.Space.LOCAL) {
  8327. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8328. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8329. }
  8330. else {
  8331. if (this.parent) {
  8332. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8333. invertParentWorldMatrix.invert();
  8334. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8335. }
  8336. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8337. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8338. }
  8339. };
  8340. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8341. var displacementVector = axis.scale(distance);
  8342. if (!space || space === BABYLON.Space.LOCAL) {
  8343. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8344. this.setPositionWithLocalVector(tempV3);
  8345. }
  8346. else {
  8347. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8348. }
  8349. };
  8350. AbstractMesh.prototype.getAbsolutePosition = function () {
  8351. this.computeWorldMatrix();
  8352. return this._absolutePosition;
  8353. };
  8354. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8355. if (!absolutePosition) {
  8356. return;
  8357. }
  8358. var absolutePositionX;
  8359. var absolutePositionY;
  8360. var absolutePositionZ;
  8361. if (absolutePosition.x === undefined) {
  8362. if (arguments.length < 3) {
  8363. return;
  8364. }
  8365. absolutePositionX = arguments[0];
  8366. absolutePositionY = arguments[1];
  8367. absolutePositionZ = arguments[2];
  8368. }
  8369. else {
  8370. absolutePositionX = absolutePosition.x;
  8371. absolutePositionY = absolutePosition.y;
  8372. absolutePositionZ = absolutePosition.z;
  8373. }
  8374. if (this.parent) {
  8375. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8376. invertParentWorldMatrix.invert();
  8377. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8378. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8379. }
  8380. else {
  8381. this.position.x = absolutePositionX;
  8382. this.position.y = absolutePositionY;
  8383. this.position.z = absolutePositionZ;
  8384. }
  8385. };
  8386. // ================================== Point of View Movement =================================
  8387. /**
  8388. * Perform relative position change from the point of view of behind the front of the mesh.
  8389. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8390. * Supports definition of mesh facing forward or backward.
  8391. * @param {number} amountRight
  8392. * @param {number} amountUp
  8393. * @param {number} amountForward
  8394. */
  8395. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8396. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8397. };
  8398. /**
  8399. * Calculate relative position change from the point of view of behind the front of the mesh.
  8400. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8401. * Supports definition of mesh facing forward or backward.
  8402. * @param {number} amountRight
  8403. * @param {number} amountUp
  8404. * @param {number} amountForward
  8405. */
  8406. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8407. var rotMatrix = new BABYLON.Matrix();
  8408. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8409. rotQuaternion.toRotationMatrix(rotMatrix);
  8410. var translationDelta = BABYLON.Vector3.Zero();
  8411. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8413. return translationDelta;
  8414. };
  8415. // ================================== Point of View Rotation =================================
  8416. /**
  8417. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8418. * Supports definition of mesh facing forward or backward.
  8419. * @param {number} flipBack
  8420. * @param {number} twirlClockwise
  8421. * @param {number} tiltRight
  8422. */
  8423. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8424. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8425. };
  8426. /**
  8427. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8428. * Supports definition of mesh facing forward or backward.
  8429. * @param {number} flipBack
  8430. * @param {number} twirlClockwise
  8431. * @param {number} tiltRight
  8432. */
  8433. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8434. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8435. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8436. };
  8437. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8438. this._pivotMatrix = matrix;
  8439. this._cache.pivotMatrixUpdated = true;
  8440. };
  8441. AbstractMesh.prototype.getPivotMatrix = function () {
  8442. return this._pivotMatrix;
  8443. };
  8444. AbstractMesh.prototype._isSynchronized = function () {
  8445. if (this._isDirty) {
  8446. return false;
  8447. }
  8448. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8449. return false;
  8450. if (this._cache.pivotMatrixUpdated) {
  8451. return false;
  8452. }
  8453. if (this.infiniteDistance) {
  8454. return false;
  8455. }
  8456. if (!this._cache.position.equals(this.position))
  8457. return false;
  8458. if (this.rotationQuaternion) {
  8459. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8460. return false;
  8461. }
  8462. else {
  8463. if (!this._cache.rotation.equals(this.rotation))
  8464. return false;
  8465. }
  8466. if (!this._cache.scaling.equals(this.scaling))
  8467. return false;
  8468. return true;
  8469. };
  8470. AbstractMesh.prototype._initCache = function () {
  8471. _super.prototype._initCache.call(this);
  8472. this._cache.localMatrixUpdated = false;
  8473. this._cache.position = BABYLON.Vector3.Zero();
  8474. this._cache.scaling = BABYLON.Vector3.Zero();
  8475. this._cache.rotation = BABYLON.Vector3.Zero();
  8476. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8477. this._cache.billboardMode = -1;
  8478. };
  8479. AbstractMesh.prototype.markAsDirty = function (property) {
  8480. if (property === "rotation") {
  8481. this.rotationQuaternion = null;
  8482. }
  8483. this._currentRenderId = Number.MAX_VALUE;
  8484. this._isDirty = true;
  8485. };
  8486. AbstractMesh.prototype._updateBoundingInfo = function () {
  8487. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8488. this._boundingInfo.update(this.worldMatrixFromCache);
  8489. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8490. };
  8491. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8492. if (!this.subMeshes) {
  8493. return;
  8494. }
  8495. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8496. var subMesh = this.subMeshes[subIndex];
  8497. if (!subMesh.IsGlobal) {
  8498. subMesh.updateBoundingInfo(matrix);
  8499. }
  8500. }
  8501. };
  8502. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8503. if (this._isWorldMatrixFrozen) {
  8504. return this._worldMatrix;
  8505. }
  8506. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8507. this._currentRenderId = this.getScene().getRenderId();
  8508. return this._worldMatrix;
  8509. }
  8510. this._cache.position.copyFrom(this.position);
  8511. this._cache.scaling.copyFrom(this.scaling);
  8512. this._cache.pivotMatrixUpdated = false;
  8513. this._cache.billboardMode = this.billboardMode;
  8514. this._currentRenderId = this.getScene().getRenderId();
  8515. this._isDirty = false;
  8516. // Scaling
  8517. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8518. // Rotation
  8519. //rotate, if quaternion is set and rotation was used
  8520. if (this.rotationQuaternion) {
  8521. var len = this.rotation.length();
  8522. if (len) {
  8523. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8524. this.rotation.copyFromFloats(0, 0, 0);
  8525. }
  8526. }
  8527. if (this.rotationQuaternion) {
  8528. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8529. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8530. }
  8531. else {
  8532. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8533. this._cache.rotation.copyFrom(this.rotation);
  8534. }
  8535. // Translation
  8536. if (this.infiniteDistance && !this.parent) {
  8537. var camera = this.getScene().activeCamera;
  8538. if (camera) {
  8539. var cameraWorldMatrix = camera.getWorldMatrix();
  8540. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8541. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8542. }
  8543. }
  8544. else {
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8546. }
  8547. // Composing transformations
  8548. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8549. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8550. // Billboarding
  8551. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8552. var localPosition = this.position.clone();
  8553. var zero = this.getScene().activeCamera.globalPosition.clone();
  8554. if (this.parent && this.parent.position) {
  8555. localPosition.addInPlace(this.parent.position);
  8556. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8557. }
  8558. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8559. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8560. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8561. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8562. zero.y = localPosition.y + 0.001;
  8563. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8564. zero.z = localPosition.z + 0.001;
  8565. }
  8566. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8567. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8568. BABYLON.Tmp.Matrix[3].invert();
  8569. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8570. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8571. }
  8572. // Local world
  8573. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8574. // Parent
  8575. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8576. this._markSyncedWithParent();
  8577. if (this._meshToBoneReferal) {
  8578. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8579. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8580. }
  8581. else {
  8582. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8583. }
  8584. }
  8585. else {
  8586. this._worldMatrix.copyFrom(this._localWorld);
  8587. }
  8588. // Bounding info
  8589. this._updateBoundingInfo();
  8590. // Absolute position
  8591. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8592. // Callbacks
  8593. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8594. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8595. }
  8596. if (!this._poseMatrix) {
  8597. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8598. }
  8599. return this._worldMatrix;
  8600. };
  8601. /**
  8602. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8603. * @param func: callback function to add
  8604. */
  8605. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8606. this._onAfterWorldMatrixUpdate.push(func);
  8607. };
  8608. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8609. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8610. if (index > -1) {
  8611. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8612. }
  8613. };
  8614. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8615. this.computeWorldMatrix();
  8616. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8617. };
  8618. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8619. this.computeWorldMatrix();
  8620. var invLocalWorldMatrix = this._localWorld.clone();
  8621. invLocalWorldMatrix.invert();
  8622. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8623. };
  8624. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8625. this.computeWorldMatrix(true);
  8626. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8627. };
  8628. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8629. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8630. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8631. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8632. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8633. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8634. /// <returns>Mesh oriented towards targetMesh</returns>
  8635. yawCor = yawCor || 0; // default to zero if undefined
  8636. pitchCor = pitchCor || 0;
  8637. rollCor = rollCor || 0;
  8638. var dv = targetPoint.subtract(this.position);
  8639. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8640. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8641. var pitch = Math.atan2(dv.y, len);
  8642. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8643. };
  8644. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8645. this._meshToBoneReferal = affectedMesh;
  8646. this.parent = bone;
  8647. if (bone.getWorldMatrix().determinant() < 0) {
  8648. this.scalingDeterminant *= -1;
  8649. }
  8650. };
  8651. AbstractMesh.prototype.detachFromBone = function () {
  8652. if (this.parent.getWorldMatrix().determinant() < 0) {
  8653. this.scalingDeterminant *= -1;
  8654. }
  8655. this._meshToBoneReferal = null;
  8656. this.parent = null;
  8657. };
  8658. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8659. return this._boundingInfo.isInFrustum(frustumPlanes);
  8660. };
  8661. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8662. if (!camera) {
  8663. camera = this.getScene().activeCamera;
  8664. }
  8665. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8666. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8667. return false;
  8668. }
  8669. return true;
  8670. };
  8671. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8672. if (!this._boundingInfo || !mesh._boundingInfo) {
  8673. return false;
  8674. }
  8675. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8676. };
  8677. AbstractMesh.prototype.intersectsPoint = function (point) {
  8678. if (!this._boundingInfo) {
  8679. return false;
  8680. }
  8681. return this._boundingInfo.intersectsPoint(point);
  8682. };
  8683. // Physics
  8684. /**
  8685. * @Deprecated. Use new PhysicsImpostor instead.
  8686. * */
  8687. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8688. //legacy support
  8689. if (impostor.impostor) {
  8690. options = impostor;
  8691. impostor = impostor.impostor;
  8692. }
  8693. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8694. return this.physicsImpostor.physicsBody;
  8695. };
  8696. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8697. return this.physicsImpostor;
  8698. };
  8699. /**
  8700. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8701. */
  8702. AbstractMesh.prototype.getPhysicsMass = function () {
  8703. return this.physicsImpostor.getParam("mass");
  8704. };
  8705. /**
  8706. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8707. */
  8708. AbstractMesh.prototype.getPhysicsFriction = function () {
  8709. return this.physicsImpostor.getParam("friction");
  8710. };
  8711. /**
  8712. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8713. */
  8714. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8715. return this.physicsImpostor.getParam("resitution");
  8716. };
  8717. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8718. if (!camera) {
  8719. camera = this.getScene().activeCamera;
  8720. }
  8721. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8722. };
  8723. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8724. if (!camera) {
  8725. camera = this.getScene().activeCamera;
  8726. }
  8727. return this.absolutePosition.subtract(camera.position).length();
  8728. };
  8729. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8730. if (!this.physicsImpostor) {
  8731. return;
  8732. }
  8733. this.physicsImpostor.applyImpulse(force, contactPoint);
  8734. };
  8735. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8736. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8737. return;
  8738. }
  8739. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8740. mainPivot: pivot1,
  8741. connectedPivot: pivot2,
  8742. nativeParams: options
  8743. });
  8744. };
  8745. /**
  8746. * @Deprecated
  8747. */
  8748. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8749. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8750. this.updatePhysicsBody();
  8751. };
  8752. /**
  8753. * @Deprecated
  8754. * Calling this function is not needed anymore.
  8755. * The physics engine takes care of transofmration automatically.
  8756. */
  8757. AbstractMesh.prototype.updatePhysicsBody = function () {
  8758. //Unneeded
  8759. };
  8760. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8761. // Collisions
  8762. get: function () {
  8763. return this._checkCollisions;
  8764. },
  8765. set: function (collisionEnabled) {
  8766. this._checkCollisions = collisionEnabled;
  8767. if (this.getScene().workerCollisions) {
  8768. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8769. }
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8775. var globalPosition = this.getAbsolutePosition();
  8776. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8777. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8778. this._collider.radius = this.ellipsoid;
  8779. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8780. };
  8781. // Submeshes octree
  8782. /**
  8783. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8784. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8785. */
  8786. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8787. if (maxCapacity === void 0) { maxCapacity = 64; }
  8788. if (maxDepth === void 0) { maxDepth = 2; }
  8789. if (!this._submeshesOctree) {
  8790. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8791. }
  8792. this.computeWorldMatrix(true);
  8793. // Update octree
  8794. var bbox = this.getBoundingInfo().boundingBox;
  8795. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8796. return this._submeshesOctree;
  8797. };
  8798. // Collisions
  8799. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8800. this._generatePointsArray();
  8801. // Transformation
  8802. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8803. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8804. subMesh._lastColliderWorldVertices = [];
  8805. subMesh._trianglePlanes = [];
  8806. var start = subMesh.verticesStart;
  8807. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8808. for (var i = start; i < end; i++) {
  8809. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8810. }
  8811. }
  8812. // Collide
  8813. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8814. if (collider.collisionFound) {
  8815. collider.collidedMesh = this;
  8816. }
  8817. };
  8818. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8819. var subMeshes;
  8820. var len;
  8821. // Octrees
  8822. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8823. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8824. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8825. len = intersections.length;
  8826. subMeshes = intersections.data;
  8827. }
  8828. else {
  8829. subMeshes = this.subMeshes;
  8830. len = subMeshes.length;
  8831. }
  8832. for (var index = 0; index < len; index++) {
  8833. var subMesh = subMeshes[index];
  8834. // Bounding test
  8835. if (len > 1 && !subMesh._checkCollision(collider))
  8836. continue;
  8837. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8838. }
  8839. };
  8840. AbstractMesh.prototype._checkCollision = function (collider) {
  8841. // Bounding box test
  8842. if (!this._boundingInfo._checkCollision(collider))
  8843. return;
  8844. // Transformation matrix
  8845. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8846. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8847. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8848. };
  8849. // Picking
  8850. AbstractMesh.prototype._generatePointsArray = function () {
  8851. return false;
  8852. };
  8853. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8854. var pickingInfo = new BABYLON.PickingInfo();
  8855. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8856. return pickingInfo;
  8857. }
  8858. if (!this._generatePointsArray()) {
  8859. return pickingInfo;
  8860. }
  8861. var intersectInfo = null;
  8862. // Octrees
  8863. var subMeshes;
  8864. var len;
  8865. if (this._submeshesOctree && this.useOctreeForPicking) {
  8866. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8867. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8868. len = intersections.length;
  8869. subMeshes = intersections.data;
  8870. }
  8871. else {
  8872. subMeshes = this.subMeshes;
  8873. len = subMeshes.length;
  8874. }
  8875. for (var index = 0; index < len; index++) {
  8876. var subMesh = subMeshes[index];
  8877. // Bounding test
  8878. if (len > 1 && !subMesh.canIntersects(ray))
  8879. continue;
  8880. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8881. if (currentIntersectInfo) {
  8882. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8883. intersectInfo = currentIntersectInfo;
  8884. intersectInfo.subMeshId = index;
  8885. if (fastCheck) {
  8886. break;
  8887. }
  8888. }
  8889. }
  8890. }
  8891. if (intersectInfo) {
  8892. // Get picked point
  8893. var world = this.getWorldMatrix();
  8894. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8895. var direction = ray.direction.clone();
  8896. direction = direction.scale(intersectInfo.distance);
  8897. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8898. var pickedPoint = worldOrigin.add(worldDirection);
  8899. // Return result
  8900. pickingInfo.hit = true;
  8901. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8902. pickingInfo.pickedPoint = pickedPoint;
  8903. pickingInfo.pickedMesh = this;
  8904. pickingInfo.bu = intersectInfo.bu;
  8905. pickingInfo.bv = intersectInfo.bv;
  8906. pickingInfo.faceId = intersectInfo.faceId;
  8907. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8908. return pickingInfo;
  8909. }
  8910. return pickingInfo;
  8911. };
  8912. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8913. return null;
  8914. };
  8915. AbstractMesh.prototype.releaseSubMeshes = function () {
  8916. if (this.subMeshes) {
  8917. while (this.subMeshes.length) {
  8918. this.subMeshes[0].dispose();
  8919. }
  8920. }
  8921. else {
  8922. this.subMeshes = new Array();
  8923. }
  8924. };
  8925. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8926. var index;
  8927. // Action manager
  8928. if (this.actionManager) {
  8929. this.actionManager.dispose();
  8930. this.actionManager = null;
  8931. }
  8932. // Skeleton
  8933. this.skeleton = null;
  8934. // Animations
  8935. this.getScene().stopAnimation(this);
  8936. // Physics
  8937. if (this.physicsImpostor) {
  8938. this.physicsImpostor.dispose(!doNotRecurse);
  8939. }
  8940. // Intersections in progress
  8941. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8942. var other = this._intersectionsInProgress[index];
  8943. var pos = other._intersectionsInProgress.indexOf(this);
  8944. other._intersectionsInProgress.splice(pos, 1);
  8945. }
  8946. this._intersectionsInProgress = [];
  8947. // Edges
  8948. if (this._edgesRenderer) {
  8949. this._edgesRenderer.dispose();
  8950. this._edgesRenderer = null;
  8951. }
  8952. // SubMeshes
  8953. this.releaseSubMeshes();
  8954. // Remove from scene
  8955. this.getScene().removeMesh(this);
  8956. if (!doNotRecurse) {
  8957. // Particles
  8958. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8959. if (this.getScene().particleSystems[index].emitter === this) {
  8960. this.getScene().particleSystems[index].dispose();
  8961. index--;
  8962. }
  8963. }
  8964. // Children
  8965. var objects = this.getScene().meshes.slice(0);
  8966. for (index = 0; index < objects.length; index++) {
  8967. if (objects[index].parent === this) {
  8968. objects[index].dispose();
  8969. }
  8970. }
  8971. }
  8972. else {
  8973. for (index = 0; index < this.getScene().meshes.length; index++) {
  8974. var obj = this.getScene().meshes[index];
  8975. if (obj.parent === this) {
  8976. obj.parent = null;
  8977. obj.computeWorldMatrix(true);
  8978. }
  8979. }
  8980. }
  8981. this._onAfterWorldMatrixUpdate = [];
  8982. this._isDisposed = true;
  8983. // Callback
  8984. if (this.onDispose) {
  8985. this.onDispose();
  8986. }
  8987. };
  8988. // Statics
  8989. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8990. AbstractMesh._BILLBOARDMODE_X = 1;
  8991. AbstractMesh._BILLBOARDMODE_Y = 2;
  8992. AbstractMesh._BILLBOARDMODE_Z = 4;
  8993. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8994. return AbstractMesh;
  8995. })(BABYLON.Node);
  8996. BABYLON.AbstractMesh = AbstractMesh;
  8997. })(BABYLON || (BABYLON = {}));
  8998. var BABYLON;
  8999. (function (BABYLON) {
  9000. var Light = (function (_super) {
  9001. __extends(Light, _super);
  9002. function Light(name, scene) {
  9003. _super.call(this, name, scene);
  9004. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9005. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9006. this.intensity = 1.0;
  9007. this.range = Number.MAX_VALUE;
  9008. this.includeOnlyWithLayerMask = 0;
  9009. this.includedOnlyMeshes = new Array();
  9010. this.excludedMeshes = new Array();
  9011. this.excludeWithLayerMask = 0;
  9012. // PBR Properties.
  9013. this.radius = 0.00001;
  9014. this._excludedMeshesIds = new Array();
  9015. this._includedOnlyMeshesIds = new Array();
  9016. scene.addLight(this);
  9017. }
  9018. Light.prototype.getShadowGenerator = function () {
  9019. return this._shadowGenerator;
  9020. };
  9021. Light.prototype.getAbsolutePosition = function () {
  9022. return BABYLON.Vector3.Zero();
  9023. };
  9024. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9025. };
  9026. Light.prototype._getWorldMatrix = function () {
  9027. return BABYLON.Matrix.Identity();
  9028. };
  9029. Light.prototype.canAffectMesh = function (mesh) {
  9030. if (!mesh) {
  9031. return true;
  9032. }
  9033. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9034. return false;
  9035. }
  9036. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9037. return false;
  9038. }
  9039. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9040. return false;
  9041. }
  9042. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9043. return false;
  9044. }
  9045. return true;
  9046. };
  9047. Light.prototype.getWorldMatrix = function () {
  9048. this._currentRenderId = this.getScene().getRenderId();
  9049. var worldMatrix = this._getWorldMatrix();
  9050. if (this.parent && this.parent.getWorldMatrix) {
  9051. if (!this._parentedWorldMatrix) {
  9052. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9053. }
  9054. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9055. this._markSyncedWithParent();
  9056. return this._parentedWorldMatrix;
  9057. }
  9058. return worldMatrix;
  9059. };
  9060. Light.prototype.dispose = function () {
  9061. if (this._shadowGenerator) {
  9062. this._shadowGenerator.dispose();
  9063. this._shadowGenerator = null;
  9064. }
  9065. // Animations
  9066. this.getScene().stopAnimation(this);
  9067. // Remove from scene
  9068. this.getScene().removeLight(this);
  9069. };
  9070. Light.prototype.getTypeID = function () {
  9071. return 0;
  9072. };
  9073. Light.prototype.clone = function (name) {
  9074. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9075. };
  9076. Light.prototype.serialize = function () {
  9077. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9078. // Type
  9079. serializationObject.type = this.getTypeID();
  9080. // Parent
  9081. if (this.parent) {
  9082. serializationObject.parentId = this.parent.id;
  9083. }
  9084. return serializationObject;
  9085. };
  9086. Light.GetConstructorFromName = function (type, name, scene) {
  9087. switch (type) {
  9088. case 0:
  9089. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9090. case 1:
  9091. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9092. case 2:
  9093. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9094. case 3:
  9095. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9096. }
  9097. };
  9098. Light.Parse = function (parsedLight, scene) {
  9099. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9100. // Inclusion / exclusions
  9101. if (parsedLight.excludedMeshesIds) {
  9102. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9103. }
  9104. if (parsedLight.includedOnlyMeshesIds) {
  9105. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9106. }
  9107. // Parent
  9108. if (parsedLight.parentId) {
  9109. light._waitingParentId = parsedLight.parentId;
  9110. }
  9111. // Animations
  9112. if (parsedLight.animations) {
  9113. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9114. var parsedAnimation = parsedLight.animations[animationIndex];
  9115. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9116. }
  9117. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9118. }
  9119. if (parsedLight.autoAnimate) {
  9120. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9121. }
  9122. return light;
  9123. };
  9124. __decorate([
  9125. BABYLON.serializeAsColor3()
  9126. ], Light.prototype, "diffuse", void 0);
  9127. __decorate([
  9128. BABYLON.serializeAsColor3()
  9129. ], Light.prototype, "specular", void 0);
  9130. __decorate([
  9131. BABYLON.serialize()
  9132. ], Light.prototype, "intensity", void 0);
  9133. __decorate([
  9134. BABYLON.serialize()
  9135. ], Light.prototype, "range", void 0);
  9136. __decorate([
  9137. BABYLON.serialize()
  9138. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9139. __decorate([
  9140. BABYLON.serialize()
  9141. ], Light.prototype, "radius", void 0);
  9142. return Light;
  9143. })(BABYLON.Node);
  9144. BABYLON.Light = Light;
  9145. })(BABYLON || (BABYLON = {}));
  9146. var BABYLON;
  9147. (function (BABYLON) {
  9148. var PointLight = (function (_super) {
  9149. __extends(PointLight, _super);
  9150. function PointLight(name, position, scene) {
  9151. _super.call(this, name, scene);
  9152. this.position = position;
  9153. }
  9154. PointLight.prototype.getAbsolutePosition = function () {
  9155. return this.transformedPosition ? this.transformedPosition : this.position;
  9156. };
  9157. PointLight.prototype.computeTransformedPosition = function () {
  9158. if (this.parent && this.parent.getWorldMatrix) {
  9159. if (!this.transformedPosition) {
  9160. this.transformedPosition = BABYLON.Vector3.Zero();
  9161. }
  9162. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9163. return true;
  9164. }
  9165. return false;
  9166. };
  9167. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9168. if (this.parent && this.parent.getWorldMatrix) {
  9169. this.computeTransformedPosition();
  9170. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9171. return;
  9172. }
  9173. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9174. };
  9175. PointLight.prototype.needCube = function () {
  9176. return true;
  9177. };
  9178. PointLight.prototype.supportsVSM = function () {
  9179. return false;
  9180. };
  9181. PointLight.prototype.needRefreshPerFrame = function () {
  9182. return false;
  9183. };
  9184. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9185. switch (faceIndex) {
  9186. case 0:
  9187. return new BABYLON.Vector3(1, 0, 0);
  9188. case 1:
  9189. return new BABYLON.Vector3(-1, 0, 0);
  9190. case 2:
  9191. return new BABYLON.Vector3(0, -1, 0);
  9192. case 3:
  9193. return new BABYLON.Vector3(0, 1, 0);
  9194. case 4:
  9195. return new BABYLON.Vector3(0, 0, 1);
  9196. case 5:
  9197. return new BABYLON.Vector3(0, 0, -1);
  9198. }
  9199. return BABYLON.Vector3.Zero();
  9200. };
  9201. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9202. var activeCamera = this.getScene().activeCamera;
  9203. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9204. };
  9205. PointLight.prototype._getWorldMatrix = function () {
  9206. if (!this._worldMatrix) {
  9207. this._worldMatrix = BABYLON.Matrix.Identity();
  9208. }
  9209. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9210. return this._worldMatrix;
  9211. };
  9212. PointLight.prototype.getTypeID = function () {
  9213. return 0;
  9214. };
  9215. __decorate([
  9216. BABYLON.serializeAsVector3()
  9217. ], PointLight.prototype, "position", void 0);
  9218. return PointLight;
  9219. })(BABYLON.Light);
  9220. BABYLON.PointLight = PointLight;
  9221. })(BABYLON || (BABYLON = {}));
  9222. var BABYLON;
  9223. (function (BABYLON) {
  9224. var SpotLight = (function (_super) {
  9225. __extends(SpotLight, _super);
  9226. function SpotLight(name, position, direction, angle, exponent, scene) {
  9227. _super.call(this, name, scene);
  9228. this.position = position;
  9229. this.direction = direction;
  9230. this.angle = angle;
  9231. this.exponent = exponent;
  9232. }
  9233. SpotLight.prototype.getAbsolutePosition = function () {
  9234. return this.transformedPosition ? this.transformedPosition : this.position;
  9235. };
  9236. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9237. var activeCamera = this.getScene().activeCamera;
  9238. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9239. };
  9240. SpotLight.prototype.needCube = function () {
  9241. return false;
  9242. };
  9243. SpotLight.prototype.supportsVSM = function () {
  9244. return true;
  9245. };
  9246. SpotLight.prototype.needRefreshPerFrame = function () {
  9247. return false;
  9248. };
  9249. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9250. return this.direction;
  9251. };
  9252. SpotLight.prototype.setDirectionToTarget = function (target) {
  9253. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9254. return this.direction;
  9255. };
  9256. SpotLight.prototype.computeTransformedPosition = function () {
  9257. if (this.parent && this.parent.getWorldMatrix) {
  9258. if (!this.transformedPosition) {
  9259. this.transformedPosition = BABYLON.Vector3.Zero();
  9260. }
  9261. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9262. return true;
  9263. }
  9264. return false;
  9265. };
  9266. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9267. var normalizeDirection;
  9268. if (this.parent && this.parent.getWorldMatrix) {
  9269. if (!this._transformedDirection) {
  9270. this._transformedDirection = BABYLON.Vector3.Zero();
  9271. }
  9272. this.computeTransformedPosition();
  9273. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9274. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9275. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9276. }
  9277. else {
  9278. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9279. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9280. }
  9281. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9282. };
  9283. SpotLight.prototype._getWorldMatrix = function () {
  9284. if (!this._worldMatrix) {
  9285. this._worldMatrix = BABYLON.Matrix.Identity();
  9286. }
  9287. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9288. return this._worldMatrix;
  9289. };
  9290. SpotLight.prototype.getTypeID = function () {
  9291. return 2;
  9292. };
  9293. __decorate([
  9294. BABYLON.serializeAsVector3()
  9295. ], SpotLight.prototype, "position", void 0);
  9296. __decorate([
  9297. BABYLON.serializeAsVector3()
  9298. ], SpotLight.prototype, "direction", void 0);
  9299. __decorate([
  9300. BABYLON.serialize()
  9301. ], SpotLight.prototype, "angle", void 0);
  9302. __decorate([
  9303. BABYLON.serialize()
  9304. ], SpotLight.prototype, "exponent", void 0);
  9305. return SpotLight;
  9306. })(BABYLON.Light);
  9307. BABYLON.SpotLight = SpotLight;
  9308. })(BABYLON || (BABYLON = {}));
  9309. var BABYLON;
  9310. (function (BABYLON) {
  9311. var HemisphericLight = (function (_super) {
  9312. __extends(HemisphericLight, _super);
  9313. function HemisphericLight(name, direction, scene) {
  9314. _super.call(this, name, scene);
  9315. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9316. this.direction = direction;
  9317. }
  9318. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9319. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9320. return this.direction;
  9321. };
  9322. HemisphericLight.prototype.getShadowGenerator = function () {
  9323. return null;
  9324. };
  9325. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9326. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9327. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9328. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9329. };
  9330. HemisphericLight.prototype._getWorldMatrix = function () {
  9331. if (!this._worldMatrix) {
  9332. this._worldMatrix = BABYLON.Matrix.Identity();
  9333. }
  9334. return this._worldMatrix;
  9335. };
  9336. HemisphericLight.prototype.getTypeID = function () {
  9337. return 3;
  9338. };
  9339. __decorate([
  9340. BABYLON.serializeAsColor3()
  9341. ], HemisphericLight.prototype, "groundColor", void 0);
  9342. __decorate([
  9343. BABYLON.serializeAsVector3()
  9344. ], HemisphericLight.prototype, "direction", void 0);
  9345. return HemisphericLight;
  9346. })(BABYLON.Light);
  9347. BABYLON.HemisphericLight = HemisphericLight;
  9348. })(BABYLON || (BABYLON = {}));
  9349. var BABYLON;
  9350. (function (BABYLON) {
  9351. var DirectionalLight = (function (_super) {
  9352. __extends(DirectionalLight, _super);
  9353. function DirectionalLight(name, direction, scene) {
  9354. _super.call(this, name, scene);
  9355. this.shadowOrthoScale = 0.5;
  9356. this.autoUpdateExtends = true;
  9357. // Cache
  9358. this._orthoLeft = Number.MAX_VALUE;
  9359. this._orthoRight = Number.MIN_VALUE;
  9360. this._orthoTop = Number.MIN_VALUE;
  9361. this._orthoBottom = Number.MAX_VALUE;
  9362. this.position = direction.scale(-1);
  9363. this.direction = direction;
  9364. }
  9365. DirectionalLight.prototype.getAbsolutePosition = function () {
  9366. return this.transformedPosition ? this.transformedPosition : this.position;
  9367. };
  9368. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9369. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9370. return this.direction;
  9371. };
  9372. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9373. var activeCamera = this.getScene().activeCamera;
  9374. // Check extends
  9375. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9376. var tempVector3 = BABYLON.Vector3.Zero();
  9377. this._orthoLeft = Number.MAX_VALUE;
  9378. this._orthoRight = Number.MIN_VALUE;
  9379. this._orthoTop = Number.MIN_VALUE;
  9380. this._orthoBottom = Number.MAX_VALUE;
  9381. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9382. var mesh = renderList[meshIndex];
  9383. if (!mesh) {
  9384. continue;
  9385. }
  9386. var boundingInfo = mesh.getBoundingInfo();
  9387. if (!boundingInfo) {
  9388. continue;
  9389. }
  9390. var boundingBox = boundingInfo.boundingBox;
  9391. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9392. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9393. if (tempVector3.x < this._orthoLeft)
  9394. this._orthoLeft = tempVector3.x;
  9395. if (tempVector3.y < this._orthoBottom)
  9396. this._orthoBottom = tempVector3.y;
  9397. if (tempVector3.x > this._orthoRight)
  9398. this._orthoRight = tempVector3.x;
  9399. if (tempVector3.y > this._orthoTop)
  9400. this._orthoTop = tempVector3.y;
  9401. }
  9402. }
  9403. }
  9404. var xOffset = this._orthoRight - this._orthoLeft;
  9405. var yOffset = this._orthoTop - this._orthoBottom;
  9406. 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);
  9407. };
  9408. DirectionalLight.prototype.supportsVSM = function () {
  9409. return true;
  9410. };
  9411. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9412. return true;
  9413. };
  9414. DirectionalLight.prototype.needCube = function () {
  9415. return false;
  9416. };
  9417. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9418. return this.direction;
  9419. };
  9420. DirectionalLight.prototype.computeTransformedPosition = function () {
  9421. if (this.parent && this.parent.getWorldMatrix) {
  9422. if (!this.transformedPosition) {
  9423. this.transformedPosition = BABYLON.Vector3.Zero();
  9424. }
  9425. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9426. return true;
  9427. }
  9428. return false;
  9429. };
  9430. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9431. if (this.parent && this.parent.getWorldMatrix) {
  9432. if (!this._transformedDirection) {
  9433. this._transformedDirection = BABYLON.Vector3.Zero();
  9434. }
  9435. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9436. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9437. return;
  9438. }
  9439. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9440. };
  9441. DirectionalLight.prototype._getWorldMatrix = function () {
  9442. if (!this._worldMatrix) {
  9443. this._worldMatrix = BABYLON.Matrix.Identity();
  9444. }
  9445. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9446. return this._worldMatrix;
  9447. };
  9448. DirectionalLight.prototype.getTypeID = function () {
  9449. return 1;
  9450. };
  9451. __decorate([
  9452. BABYLON.serializeAsVector3()
  9453. ], DirectionalLight.prototype, "position", void 0);
  9454. __decorate([
  9455. BABYLON.serializeAsVector3()
  9456. ], DirectionalLight.prototype, "direction", void 0);
  9457. __decorate([
  9458. BABYLON.serialize()
  9459. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9460. __decorate([
  9461. BABYLON.serialize()
  9462. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9463. return DirectionalLight;
  9464. })(BABYLON.Light);
  9465. BABYLON.DirectionalLight = DirectionalLight;
  9466. })(BABYLON || (BABYLON = {}));
  9467. var BABYLON;
  9468. (function (BABYLON) {
  9469. var ShadowGenerator = (function () {
  9470. function ShadowGenerator(mapSize, light) {
  9471. var _this = this;
  9472. // Members
  9473. this._filter = ShadowGenerator.FILTER_NONE;
  9474. this.blurScale = 2;
  9475. this._blurBoxOffset = 0;
  9476. this._bias = 0.00005;
  9477. this._lightDirection = BABYLON.Vector3.Zero();
  9478. this.forceBackFacesOnly = false;
  9479. this._darkness = 0;
  9480. this._transparencyShadow = false;
  9481. this._viewMatrix = BABYLON.Matrix.Zero();
  9482. this._projectionMatrix = BABYLON.Matrix.Zero();
  9483. this._transformMatrix = BABYLON.Matrix.Zero();
  9484. this._worldViewProjection = BABYLON.Matrix.Zero();
  9485. this._currentFaceIndex = 0;
  9486. this._currentFaceIndexCache = 0;
  9487. this._light = light;
  9488. this._scene = light.getScene();
  9489. this._mapSize = mapSize;
  9490. light._shadowGenerator = this;
  9491. // Render target
  9492. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9493. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9494. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9495. this._shadowMap.anisotropicFilteringLevel = 1;
  9496. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9497. this._shadowMap.renderParticles = false;
  9498. this._shadowMap.onBeforeRender = function (faceIndex) {
  9499. _this._currentFaceIndex = faceIndex;
  9500. };
  9501. this._shadowMap.onAfterUnbind = function () {
  9502. if (!_this.useBlurVarianceShadowMap) {
  9503. return;
  9504. }
  9505. if (!_this._shadowMap2) {
  9506. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9507. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9508. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9509. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9510. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9511. _this._downSamplePostprocess.onApply = function (effect) {
  9512. effect.setTexture("textureSampler", _this._shadowMap);
  9513. };
  9514. _this.blurBoxOffset = 1;
  9515. }
  9516. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9517. };
  9518. // Custom render function
  9519. var renderSubMesh = function (subMesh) {
  9520. var mesh = subMesh.getRenderingMesh();
  9521. var scene = _this._scene;
  9522. var engine = scene.getEngine();
  9523. // Culling
  9524. engine.setState(subMesh.getMaterial().backFaceCulling);
  9525. // Managing instances
  9526. var batch = mesh._getInstancesRenderList(subMesh._id);
  9527. if (batch.mustReturn) {
  9528. return;
  9529. }
  9530. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9531. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9532. engine.enableEffect(_this._effect);
  9533. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9534. var material = subMesh.getMaterial();
  9535. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9536. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9537. if (_this.getLight().needCube()) {
  9538. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9539. }
  9540. // Alpha test
  9541. if (material && material.needAlphaTesting()) {
  9542. var alphaTexture = material.getAlphaTestTexture();
  9543. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9544. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9545. }
  9546. // Bones
  9547. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9548. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9549. }
  9550. if (_this.forceBackFacesOnly) {
  9551. engine.setState(true, 0, false, true);
  9552. }
  9553. // Draw
  9554. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9555. if (_this.forceBackFacesOnly) {
  9556. engine.setState(true, 0, false, false);
  9557. }
  9558. }
  9559. else {
  9560. // Need to reset refresh rate of the shadowMap
  9561. _this._shadowMap.resetRefreshCounter();
  9562. }
  9563. };
  9564. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9565. var index;
  9566. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9567. renderSubMesh(opaqueSubMeshes.data[index]);
  9568. }
  9569. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9570. renderSubMesh(alphaTestSubMeshes.data[index]);
  9571. }
  9572. if (_this._transparencyShadow) {
  9573. for (index = 0; index < transparentSubMeshes.length; index++) {
  9574. renderSubMesh(transparentSubMeshes.data[index]);
  9575. }
  9576. }
  9577. };
  9578. this._shadowMap.onClear = function (engine) {
  9579. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9580. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9581. }
  9582. else {
  9583. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9584. }
  9585. };
  9586. }
  9587. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9588. // Static
  9589. get: function () {
  9590. return ShadowGenerator._FILTER_NONE;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9596. get: function () {
  9597. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9603. get: function () {
  9604. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9610. get: function () {
  9611. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9617. get: function () {
  9618. return this._bias;
  9619. },
  9620. set: function (bias) {
  9621. this._bias = bias;
  9622. },
  9623. enumerable: true,
  9624. configurable: true
  9625. });
  9626. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9627. get: function () {
  9628. return this._blurBoxOffset;
  9629. },
  9630. set: function (value) {
  9631. var _this = this;
  9632. if (this._blurBoxOffset === value) {
  9633. return;
  9634. }
  9635. this._blurBoxOffset = value;
  9636. if (this._boxBlurPostprocess) {
  9637. this._boxBlurPostprocess.dispose();
  9638. }
  9639. 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);
  9640. this._boxBlurPostprocess.onApply = function (effect) {
  9641. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9642. };
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9648. get: function () {
  9649. return this._filter;
  9650. },
  9651. set: function (value) {
  9652. if (this._filter === value) {
  9653. return;
  9654. }
  9655. this._filter = value;
  9656. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9657. this._shadowMap.anisotropicFilteringLevel = 16;
  9658. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9659. }
  9660. else {
  9661. this._shadowMap.anisotropicFilteringLevel = 1;
  9662. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9663. }
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9669. get: function () {
  9670. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9671. },
  9672. set: function (value) {
  9673. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9679. get: function () {
  9680. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9681. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9682. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9683. },
  9684. set: function (value) {
  9685. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9691. get: function () {
  9692. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9693. },
  9694. set: function (value) {
  9695. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9701. var defines = [];
  9702. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9703. defines.push("#define VSM");
  9704. }
  9705. if (this.getLight().needCube()) {
  9706. defines.push("#define CUBEMAP");
  9707. }
  9708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9709. var mesh = subMesh.getMesh();
  9710. var material = subMesh.getMaterial();
  9711. // Alpha test
  9712. if (material && material.needAlphaTesting()) {
  9713. defines.push("#define ALPHATEST");
  9714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9715. attribs.push(BABYLON.VertexBuffer.UVKind);
  9716. defines.push("#define UV1");
  9717. }
  9718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9720. defines.push("#define UV2");
  9721. }
  9722. }
  9723. // Bones
  9724. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9727. if (mesh.numBoneInfluencers > 4) {
  9728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9730. }
  9731. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9732. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9733. }
  9734. else {
  9735. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9736. }
  9737. // Instances
  9738. if (useInstances) {
  9739. defines.push("#define INSTANCES");
  9740. attribs.push("world0");
  9741. attribs.push("world1");
  9742. attribs.push("world2");
  9743. attribs.push("world3");
  9744. }
  9745. // Get correct effect
  9746. var join = defines.join("\n");
  9747. if (this._cachedDefines !== join) {
  9748. this._cachedDefines = join;
  9749. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9750. }
  9751. return this._effect.isReady();
  9752. };
  9753. ShadowGenerator.prototype.getShadowMap = function () {
  9754. return this._shadowMap;
  9755. };
  9756. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9757. if (this._shadowMap2) {
  9758. return this._shadowMap2;
  9759. }
  9760. return this._shadowMap;
  9761. };
  9762. ShadowGenerator.prototype.getLight = function () {
  9763. return this._light;
  9764. };
  9765. // Methods
  9766. ShadowGenerator.prototype.getTransformMatrix = function () {
  9767. var scene = this._scene;
  9768. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9769. return this._transformMatrix;
  9770. }
  9771. this._currentRenderID = scene.getRenderId();
  9772. this._currentFaceIndexCache = this._currentFaceIndex;
  9773. var lightPosition = this._light.position;
  9774. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9775. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9776. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9777. }
  9778. if (this._light.computeTransformedPosition()) {
  9779. lightPosition = this._light.transformedPosition;
  9780. }
  9781. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9782. this._cachedPosition = lightPosition.clone();
  9783. this._cachedDirection = this._lightDirection.clone();
  9784. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9785. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9786. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9787. }
  9788. return this._transformMatrix;
  9789. };
  9790. ShadowGenerator.prototype.getDarkness = function () {
  9791. return this._darkness;
  9792. };
  9793. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9794. if (darkness >= 1.0)
  9795. this._darkness = 1.0;
  9796. else if (darkness <= 0.0)
  9797. this._darkness = 0.0;
  9798. else
  9799. this._darkness = darkness;
  9800. };
  9801. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9802. this._transparencyShadow = hasShadow;
  9803. };
  9804. ShadowGenerator.prototype._packHalf = function (depth) {
  9805. var scale = depth * 255.0;
  9806. var fract = scale - Math.floor(scale);
  9807. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9808. };
  9809. ShadowGenerator.prototype.dispose = function () {
  9810. this._shadowMap.dispose();
  9811. if (this._shadowMap2) {
  9812. this._shadowMap2.dispose();
  9813. }
  9814. if (this._downSamplePostprocess) {
  9815. this._downSamplePostprocess.dispose();
  9816. }
  9817. if (this._boxBlurPostprocess) {
  9818. this._boxBlurPostprocess.dispose();
  9819. }
  9820. };
  9821. ShadowGenerator.prototype.serialize = function () {
  9822. var serializationObject = {};
  9823. serializationObject.lightId = this._light.id;
  9824. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9825. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9826. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9827. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9828. serializationObject.renderList = [];
  9829. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9830. var mesh = this.getShadowMap().renderList[meshIndex];
  9831. serializationObject.renderList.push(mesh.id);
  9832. }
  9833. return serializationObject;
  9834. };
  9835. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9836. //casting to point light, as light is missing the position attr and typescript complains.
  9837. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9838. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9839. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9840. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9841. shadowGenerator.getShadowMap().renderList.push(mesh);
  9842. }
  9843. if (parsedShadowGenerator.usePoissonSampling) {
  9844. shadowGenerator.usePoissonSampling = true;
  9845. }
  9846. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9847. shadowGenerator.useVarianceShadowMap = true;
  9848. }
  9849. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9850. shadowGenerator.useBlurVarianceShadowMap = true;
  9851. if (parsedShadowGenerator.blurScale) {
  9852. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9853. }
  9854. if (parsedShadowGenerator.blurBoxOffset) {
  9855. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9856. }
  9857. }
  9858. if (parsedShadowGenerator.bias !== undefined) {
  9859. shadowGenerator.bias = parsedShadowGenerator.bias;
  9860. }
  9861. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9862. return shadowGenerator;
  9863. };
  9864. ShadowGenerator._FILTER_NONE = 0;
  9865. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9866. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9867. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9868. return ShadowGenerator;
  9869. })();
  9870. BABYLON.ShadowGenerator = ShadowGenerator;
  9871. })(BABYLON || (BABYLON = {}));
  9872. var BABYLON;
  9873. (function (BABYLON) {
  9874. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9875. if (boxMin.x > sphereCenter.x + sphereRadius)
  9876. return false;
  9877. if (sphereCenter.x - sphereRadius > boxMax.x)
  9878. return false;
  9879. if (boxMin.y > sphereCenter.y + sphereRadius)
  9880. return false;
  9881. if (sphereCenter.y - sphereRadius > boxMax.y)
  9882. return false;
  9883. if (boxMin.z > sphereCenter.z + sphereRadius)
  9884. return false;
  9885. if (sphereCenter.z - sphereRadius > boxMax.z)
  9886. return false;
  9887. return true;
  9888. };
  9889. var getLowestRoot = function (a, b, c, maxR) {
  9890. var determinant = b * b - 4.0 * a * c;
  9891. var result = { root: 0, found: false };
  9892. if (determinant < 0)
  9893. return result;
  9894. var sqrtD = Math.sqrt(determinant);
  9895. var r1 = (-b - sqrtD) / (2.0 * a);
  9896. var r2 = (-b + sqrtD) / (2.0 * a);
  9897. if (r1 > r2) {
  9898. var temp = r2;
  9899. r2 = r1;
  9900. r1 = temp;
  9901. }
  9902. if (r1 > 0 && r1 < maxR) {
  9903. result.root = r1;
  9904. result.found = true;
  9905. return result;
  9906. }
  9907. if (r2 > 0 && r2 < maxR) {
  9908. result.root = r2;
  9909. result.found = true;
  9910. return result;
  9911. }
  9912. return result;
  9913. };
  9914. var Collider = (function () {
  9915. function Collider() {
  9916. this.radius = new BABYLON.Vector3(1, 1, 1);
  9917. this.retry = 0;
  9918. this.basePointWorld = BABYLON.Vector3.Zero();
  9919. this.velocityWorld = BABYLON.Vector3.Zero();
  9920. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9921. this._collisionPoint = BABYLON.Vector3.Zero();
  9922. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9923. this._tempVector = BABYLON.Vector3.Zero();
  9924. this._tempVector2 = BABYLON.Vector3.Zero();
  9925. this._tempVector3 = BABYLON.Vector3.Zero();
  9926. this._tempVector4 = BABYLON.Vector3.Zero();
  9927. this._edge = BABYLON.Vector3.Zero();
  9928. this._baseToVertex = BABYLON.Vector3.Zero();
  9929. this._destinationPoint = BABYLON.Vector3.Zero();
  9930. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9931. this._displacementVector = BABYLON.Vector3.Zero();
  9932. }
  9933. // Methods
  9934. Collider.prototype._initialize = function (source, dir, e) {
  9935. this.velocity = dir;
  9936. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9937. this.basePoint = source;
  9938. source.multiplyToRef(this.radius, this.basePointWorld);
  9939. dir.multiplyToRef(this.radius, this.velocityWorld);
  9940. this.velocityWorldLength = this.velocityWorld.length();
  9941. this.epsilon = e;
  9942. this.collisionFound = false;
  9943. };
  9944. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9945. pa.subtractToRef(point, this._tempVector);
  9946. pb.subtractToRef(point, this._tempVector2);
  9947. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9948. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9949. if (d < 0)
  9950. return false;
  9951. pc.subtractToRef(point, this._tempVector3);
  9952. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9953. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9954. if (d < 0)
  9955. return false;
  9956. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9957. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9958. return d >= 0;
  9959. };
  9960. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9961. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9962. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9963. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9964. return false;
  9965. }
  9966. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9967. return false;
  9968. return true;
  9969. };
  9970. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9971. var t0;
  9972. var embeddedInPlane = false;
  9973. //defensive programming, actually not needed.
  9974. if (!trianglePlaneArray) {
  9975. trianglePlaneArray = [];
  9976. }
  9977. if (!trianglePlaneArray[faceIndex]) {
  9978. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9979. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9980. }
  9981. var trianglePlane = trianglePlaneArray[faceIndex];
  9982. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9983. return;
  9984. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9985. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9986. if (normalDotVelocity == 0) {
  9987. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9988. return;
  9989. embeddedInPlane = true;
  9990. t0 = 0;
  9991. }
  9992. else {
  9993. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9994. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9995. if (t0 > t1) {
  9996. var temp = t1;
  9997. t1 = t0;
  9998. t0 = temp;
  9999. }
  10000. if (t0 > 1.0 || t1 < 0.0)
  10001. return;
  10002. if (t0 < 0)
  10003. t0 = 0;
  10004. if (t0 > 1.0)
  10005. t0 = 1.0;
  10006. }
  10007. this._collisionPoint.copyFromFloats(0, 0, 0);
  10008. var found = false;
  10009. var t = 1.0;
  10010. if (!embeddedInPlane) {
  10011. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10012. this.velocity.scaleToRef(t0, this._tempVector);
  10013. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10014. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10015. found = true;
  10016. t = t0;
  10017. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10018. }
  10019. }
  10020. if (!found) {
  10021. var velocitySquaredLength = this.velocity.lengthSquared();
  10022. var a = velocitySquaredLength;
  10023. this.basePoint.subtractToRef(p1, this._tempVector);
  10024. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10025. var c = this._tempVector.lengthSquared() - 1.0;
  10026. var lowestRoot = getLowestRoot(a, b, c, t);
  10027. if (lowestRoot.found) {
  10028. t = lowestRoot.root;
  10029. found = true;
  10030. this._collisionPoint.copyFrom(p1);
  10031. }
  10032. this.basePoint.subtractToRef(p2, this._tempVector);
  10033. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10034. c = this._tempVector.lengthSquared() - 1.0;
  10035. lowestRoot = getLowestRoot(a, b, c, t);
  10036. if (lowestRoot.found) {
  10037. t = lowestRoot.root;
  10038. found = true;
  10039. this._collisionPoint.copyFrom(p2);
  10040. }
  10041. this.basePoint.subtractToRef(p3, this._tempVector);
  10042. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10043. c = this._tempVector.lengthSquared() - 1.0;
  10044. lowestRoot = getLowestRoot(a, b, c, t);
  10045. if (lowestRoot.found) {
  10046. t = lowestRoot.root;
  10047. found = true;
  10048. this._collisionPoint.copyFrom(p3);
  10049. }
  10050. p2.subtractToRef(p1, this._edge);
  10051. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10052. var edgeSquaredLength = this._edge.lengthSquared();
  10053. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10054. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10055. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10056. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10057. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10058. lowestRoot = getLowestRoot(a, b, c, t);
  10059. if (lowestRoot.found) {
  10060. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10061. if (f >= 0.0 && f <= 1.0) {
  10062. t = lowestRoot.root;
  10063. found = true;
  10064. this._edge.scaleInPlace(f);
  10065. p1.addToRef(this._edge, this._collisionPoint);
  10066. }
  10067. }
  10068. p3.subtractToRef(p2, this._edge);
  10069. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10070. edgeSquaredLength = this._edge.lengthSquared();
  10071. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10072. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10073. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10074. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10075. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10076. lowestRoot = getLowestRoot(a, b, c, t);
  10077. if (lowestRoot.found) {
  10078. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10079. if (f >= 0.0 && f <= 1.0) {
  10080. t = lowestRoot.root;
  10081. found = true;
  10082. this._edge.scaleInPlace(f);
  10083. p2.addToRef(this._edge, this._collisionPoint);
  10084. }
  10085. }
  10086. p1.subtractToRef(p3, this._edge);
  10087. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10088. edgeSquaredLength = this._edge.lengthSquared();
  10089. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10090. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10091. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10092. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10093. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10094. lowestRoot = getLowestRoot(a, b, c, t);
  10095. if (lowestRoot.found) {
  10096. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10097. if (f >= 0.0 && f <= 1.0) {
  10098. t = lowestRoot.root;
  10099. found = true;
  10100. this._edge.scaleInPlace(f);
  10101. p3.addToRef(this._edge, this._collisionPoint);
  10102. }
  10103. }
  10104. }
  10105. if (found) {
  10106. var distToCollision = t * this.velocity.length();
  10107. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10108. if (!this.intersectionPoint) {
  10109. this.intersectionPoint = this._collisionPoint.clone();
  10110. }
  10111. else {
  10112. this.intersectionPoint.copyFrom(this._collisionPoint);
  10113. }
  10114. this.nearestDistance = distToCollision;
  10115. this.collisionFound = true;
  10116. }
  10117. }
  10118. };
  10119. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10120. for (var i = indexStart; i < indexEnd; i += 3) {
  10121. var p1 = pts[indices[i] - decal];
  10122. var p2 = pts[indices[i + 1] - decal];
  10123. var p3 = pts[indices[i + 2] - decal];
  10124. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10125. }
  10126. };
  10127. Collider.prototype._getResponse = function (pos, vel) {
  10128. pos.addToRef(vel, this._destinationPoint);
  10129. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10130. this.basePoint.addToRef(vel, pos);
  10131. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10132. this._slidePlaneNormal.normalize();
  10133. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10134. pos.addInPlace(this._displacementVector);
  10135. this.intersectionPoint.addInPlace(this._displacementVector);
  10136. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10137. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10138. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10139. };
  10140. return Collider;
  10141. })();
  10142. BABYLON.Collider = Collider;
  10143. })(BABYLON || (BABYLON = {}));
  10144. var BABYLON;
  10145. (function (BABYLON) {
  10146. //WebWorker code will be inserted to this variable.
  10147. BABYLON.CollisionWorker = "";
  10148. (function (WorkerTaskType) {
  10149. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10150. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10151. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10152. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10153. var WorkerTaskType = BABYLON.WorkerTaskType;
  10154. (function (WorkerReplyType) {
  10155. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10156. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10157. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10158. var WorkerReplyType = BABYLON.WorkerReplyType;
  10159. var CollisionCoordinatorWorker = (function () {
  10160. function CollisionCoordinatorWorker() {
  10161. var _this = this;
  10162. this._scaledPosition = BABYLON.Vector3.Zero();
  10163. this._scaledVelocity = BABYLON.Vector3.Zero();
  10164. this.onMeshUpdated = function (mesh) {
  10165. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10166. };
  10167. this.onGeometryUpdated = function (geometry) {
  10168. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10169. };
  10170. this._afterRender = function () {
  10171. if (!_this._init)
  10172. return;
  10173. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10174. return;
  10175. }
  10176. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10177. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10178. if (_this._runningUpdated > 4) {
  10179. return;
  10180. }
  10181. ++_this._runningUpdated;
  10182. var payload = {
  10183. updatedMeshes: _this._addUpdateMeshesList,
  10184. updatedGeometries: _this._addUpdateGeometriesList,
  10185. removedGeometries: _this._toRemoveGeometryArray,
  10186. removedMeshes: _this._toRemoveMeshesArray
  10187. };
  10188. var message = {
  10189. payload: payload,
  10190. taskType: WorkerTaskType.UPDATE
  10191. };
  10192. var serializable = [];
  10193. for (var id in payload.updatedGeometries) {
  10194. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10195. //prepare transferables
  10196. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10197. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10198. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10199. }
  10200. }
  10201. _this._worker.postMessage(message, serializable);
  10202. _this._addUpdateMeshesList = {};
  10203. _this._addUpdateGeometriesList = {};
  10204. _this._toRemoveGeometryArray = [];
  10205. _this._toRemoveMeshesArray = [];
  10206. };
  10207. this._onMessageFromWorker = function (e) {
  10208. var returnData = e.data;
  10209. if (returnData.error != WorkerReplyType.SUCCESS) {
  10210. //TODO what errors can be returned from the worker?
  10211. BABYLON.Tools.Warn("error returned from worker!");
  10212. return;
  10213. }
  10214. switch (returnData.taskType) {
  10215. case WorkerTaskType.INIT:
  10216. _this._init = true;
  10217. //Update the worked with ALL of the scene's current state
  10218. _this._scene.meshes.forEach(function (mesh) {
  10219. _this.onMeshAdded(mesh);
  10220. });
  10221. _this._scene.getGeometries().forEach(function (geometry) {
  10222. _this.onGeometryAdded(geometry);
  10223. });
  10224. break;
  10225. case WorkerTaskType.UPDATE:
  10226. _this._runningUpdated--;
  10227. break;
  10228. case WorkerTaskType.COLLIDE:
  10229. _this._runningCollisionTask = false;
  10230. var returnPayload = returnData.payload;
  10231. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10232. return;
  10233. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10234. //cleanup
  10235. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10236. break;
  10237. }
  10238. };
  10239. this._collisionsCallbackArray = [];
  10240. this._init = false;
  10241. this._runningUpdated = 0;
  10242. this._runningCollisionTask = false;
  10243. this._addUpdateMeshesList = {};
  10244. this._addUpdateGeometriesList = {};
  10245. this._toRemoveGeometryArray = [];
  10246. this._toRemoveMeshesArray = [];
  10247. }
  10248. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10249. if (!this._init)
  10250. return;
  10251. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10252. return;
  10253. position.divideToRef(collider.radius, this._scaledPosition);
  10254. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10255. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10256. var payload = {
  10257. collider: {
  10258. position: this._scaledPosition.asArray(),
  10259. velocity: this._scaledVelocity.asArray(),
  10260. radius: collider.radius.asArray()
  10261. },
  10262. collisionId: collisionIndex,
  10263. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10264. maximumRetry: maximumRetry
  10265. };
  10266. var message = {
  10267. payload: payload,
  10268. taskType: WorkerTaskType.COLLIDE
  10269. };
  10270. this._worker.postMessage(message);
  10271. };
  10272. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10273. this._scene = scene;
  10274. this._scene.registerAfterRender(this._afterRender);
  10275. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10276. this._worker = new Worker(workerUrl);
  10277. this._worker.onmessage = this._onMessageFromWorker;
  10278. var message = {
  10279. payload: {},
  10280. taskType: WorkerTaskType.INIT
  10281. };
  10282. this._worker.postMessage(message);
  10283. };
  10284. CollisionCoordinatorWorker.prototype.destroy = function () {
  10285. this._scene.unregisterAfterRender(this._afterRender);
  10286. this._worker.terminate();
  10287. };
  10288. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10289. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10290. this.onMeshUpdated(mesh);
  10291. };
  10292. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10293. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10294. };
  10295. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10296. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10297. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10298. this.onGeometryUpdated(geometry);
  10299. };
  10300. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10301. this._toRemoveGeometryArray.push(geometry.id);
  10302. };
  10303. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10304. var submeshes = [];
  10305. if (mesh.subMeshes) {
  10306. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10307. return {
  10308. position: idx,
  10309. verticesStart: sm.verticesStart,
  10310. verticesCount: sm.verticesCount,
  10311. indexStart: sm.indexStart,
  10312. indexCount: sm.indexCount,
  10313. hasMaterial: !!sm.getMaterial(),
  10314. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10315. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10316. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10317. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10318. };
  10319. });
  10320. }
  10321. var geometryId = null;
  10322. if (mesh instanceof BABYLON.Mesh) {
  10323. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10324. }
  10325. else if (mesh instanceof BABYLON.InstancedMesh) {
  10326. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10327. }
  10328. return {
  10329. uniqueId: mesh.uniqueId,
  10330. id: mesh.id,
  10331. name: mesh.name,
  10332. geometryId: geometryId,
  10333. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10334. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10335. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10336. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10337. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10338. subMeshes: submeshes,
  10339. checkCollisions: mesh.checkCollisions
  10340. };
  10341. };
  10342. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10343. return {
  10344. id: geometry.id,
  10345. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10346. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10347. indices: new Int32Array(geometry.getIndices() || []),
  10348. };
  10349. };
  10350. return CollisionCoordinatorWorker;
  10351. })();
  10352. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10353. var CollisionCoordinatorLegacy = (function () {
  10354. function CollisionCoordinatorLegacy() {
  10355. this._scaledPosition = BABYLON.Vector3.Zero();
  10356. this._scaledVelocity = BABYLON.Vector3.Zero();
  10357. this._finalPosition = BABYLON.Vector3.Zero();
  10358. }
  10359. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10360. position.divideToRef(collider.radius, this._scaledPosition);
  10361. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10362. collider.collidedMesh = null;
  10363. collider.retry = 0;
  10364. collider.initialVelocity = this._scaledVelocity;
  10365. collider.initialPosition = this._scaledPosition;
  10366. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10367. this._finalPosition.multiplyInPlace(collider.radius);
  10368. //run the callback
  10369. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10370. };
  10371. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10372. this._scene = scene;
  10373. };
  10374. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10375. //Legacy need no destruction method.
  10376. };
  10377. //No update in legacy mode
  10378. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10379. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10380. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10381. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10382. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10383. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10384. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10385. if (excludedMesh === void 0) { excludedMesh = null; }
  10386. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10387. if (collider.retry >= maximumRetry) {
  10388. finalPosition.copyFrom(position);
  10389. return;
  10390. }
  10391. collider._initialize(position, velocity, closeDistance);
  10392. // Check all meshes
  10393. for (var index = 0; index < this._scene.meshes.length; index++) {
  10394. var mesh = this._scene.meshes[index];
  10395. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10396. mesh._checkCollision(collider);
  10397. }
  10398. }
  10399. if (!collider.collisionFound) {
  10400. position.addToRef(velocity, finalPosition);
  10401. return;
  10402. }
  10403. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10404. collider._getResponse(position, velocity);
  10405. }
  10406. if (velocity.length() <= closeDistance) {
  10407. finalPosition.copyFrom(position);
  10408. return;
  10409. }
  10410. collider.retry++;
  10411. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10412. };
  10413. return CollisionCoordinatorLegacy;
  10414. })();
  10415. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10416. })(BABYLON || (BABYLON = {}));
  10417. var BABYLON;
  10418. (function (BABYLON) {
  10419. var Camera = (function (_super) {
  10420. __extends(Camera, _super);
  10421. function Camera(name, position, scene) {
  10422. _super.call(this, name, scene);
  10423. this.upVector = BABYLON.Vector3.Up();
  10424. this.orthoLeft = null;
  10425. this.orthoRight = null;
  10426. this.orthoBottom = null;
  10427. this.orthoTop = null;
  10428. this.fov = 0.8;
  10429. this.minZ = 1.0;
  10430. this.maxZ = 10000.0;
  10431. this.inertia = 0.9;
  10432. this.mode = Camera.PERSPECTIVE_CAMERA;
  10433. this.isIntermediate = false;
  10434. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10435. this.layerMask = 0x0FFFFFFF;
  10436. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10437. // Camera rig members
  10438. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10439. this._rigCameras = new Array();
  10440. // Cache
  10441. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10442. this._projectionMatrix = new BABYLON.Matrix();
  10443. this._postProcesses = new Array();
  10444. this._postProcessesTakenIndices = [];
  10445. this._activeMeshes = new BABYLON.SmartArray(256);
  10446. this._globalPosition = BABYLON.Vector3.Zero();
  10447. scene.addCamera(this);
  10448. if (!scene.activeCamera) {
  10449. scene.activeCamera = this;
  10450. }
  10451. this.position = position;
  10452. }
  10453. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10454. get: function () {
  10455. return Camera._PERSPECTIVE_CAMERA;
  10456. },
  10457. enumerable: true,
  10458. configurable: true
  10459. });
  10460. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10461. get: function () {
  10462. return Camera._ORTHOGRAPHIC_CAMERA;
  10463. },
  10464. enumerable: true,
  10465. configurable: true
  10466. });
  10467. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10468. get: function () {
  10469. return Camera._FOVMODE_VERTICAL_FIXED;
  10470. },
  10471. enumerable: true,
  10472. configurable: true
  10473. });
  10474. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10475. get: function () {
  10476. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10477. },
  10478. enumerable: true,
  10479. configurable: true
  10480. });
  10481. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10482. get: function () {
  10483. return Camera._RIG_MODE_NONE;
  10484. },
  10485. enumerable: true,
  10486. configurable: true
  10487. });
  10488. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10489. get: function () {
  10490. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10491. },
  10492. enumerable: true,
  10493. configurable: true
  10494. });
  10495. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10496. get: function () {
  10497. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10498. },
  10499. enumerable: true,
  10500. configurable: true
  10501. });
  10502. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10503. get: function () {
  10504. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10505. },
  10506. enumerable: true,
  10507. configurable: true
  10508. });
  10509. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10510. get: function () {
  10511. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10512. },
  10513. enumerable: true,
  10514. configurable: true
  10515. });
  10516. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10517. get: function () {
  10518. return Camera._RIG_MODE_VR;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(Camera.prototype, "globalPosition", {
  10524. get: function () {
  10525. return this._globalPosition;
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. Camera.prototype.getActiveMeshes = function () {
  10531. return this._activeMeshes;
  10532. };
  10533. Camera.prototype.isActiveMesh = function (mesh) {
  10534. return (this._activeMeshes.indexOf(mesh) !== -1);
  10535. };
  10536. //Cache
  10537. Camera.prototype._initCache = function () {
  10538. _super.prototype._initCache.call(this);
  10539. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10540. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10541. this._cache.mode = undefined;
  10542. this._cache.minZ = undefined;
  10543. this._cache.maxZ = undefined;
  10544. this._cache.fov = undefined;
  10545. this._cache.aspectRatio = undefined;
  10546. this._cache.orthoLeft = undefined;
  10547. this._cache.orthoRight = undefined;
  10548. this._cache.orthoBottom = undefined;
  10549. this._cache.orthoTop = undefined;
  10550. this._cache.renderWidth = undefined;
  10551. this._cache.renderHeight = undefined;
  10552. };
  10553. Camera.prototype._updateCache = function (ignoreParentClass) {
  10554. if (!ignoreParentClass) {
  10555. _super.prototype._updateCache.call(this);
  10556. }
  10557. var engine = this.getEngine();
  10558. this._cache.position.copyFrom(this.position);
  10559. this._cache.upVector.copyFrom(this.upVector);
  10560. this._cache.mode = this.mode;
  10561. this._cache.minZ = this.minZ;
  10562. this._cache.maxZ = this.maxZ;
  10563. this._cache.fov = this.fov;
  10564. this._cache.aspectRatio = engine.getAspectRatio(this);
  10565. this._cache.orthoLeft = this.orthoLeft;
  10566. this._cache.orthoRight = this.orthoRight;
  10567. this._cache.orthoBottom = this.orthoBottom;
  10568. this._cache.orthoTop = this.orthoTop;
  10569. this._cache.renderWidth = engine.getRenderWidth();
  10570. this._cache.renderHeight = engine.getRenderHeight();
  10571. };
  10572. Camera.prototype._updateFromScene = function () {
  10573. this.updateCache();
  10574. this._update();
  10575. };
  10576. // Synchronized
  10577. Camera.prototype._isSynchronized = function () {
  10578. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10579. };
  10580. Camera.prototype._isSynchronizedViewMatrix = function () {
  10581. if (!_super.prototype._isSynchronized.call(this))
  10582. return false;
  10583. return this._cache.position.equals(this.position)
  10584. && this._cache.upVector.equals(this.upVector)
  10585. && this.isSynchronizedWithParent();
  10586. };
  10587. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10588. var check = this._cache.mode === this.mode
  10589. && this._cache.minZ === this.minZ
  10590. && this._cache.maxZ === this.maxZ;
  10591. if (!check) {
  10592. return false;
  10593. }
  10594. var engine = this.getEngine();
  10595. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10596. check = this._cache.fov === this.fov
  10597. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10598. }
  10599. else {
  10600. check = this._cache.orthoLeft === this.orthoLeft
  10601. && this._cache.orthoRight === this.orthoRight
  10602. && this._cache.orthoBottom === this.orthoBottom
  10603. && this._cache.orthoTop === this.orthoTop
  10604. && this._cache.renderWidth === engine.getRenderWidth()
  10605. && this._cache.renderHeight === engine.getRenderHeight();
  10606. }
  10607. return check;
  10608. };
  10609. // Controls
  10610. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10611. };
  10612. Camera.prototype.detachControl = function (element) {
  10613. };
  10614. Camera.prototype._update = function () {
  10615. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10616. this._updateRigCameras();
  10617. }
  10618. this._checkInputs();
  10619. };
  10620. Camera.prototype._checkInputs = function () {
  10621. };
  10622. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10623. if (insertAt === void 0) { insertAt = null; }
  10624. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10625. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10626. return 0;
  10627. }
  10628. if (insertAt == null || insertAt < 0) {
  10629. this._postProcesses.push(postProcess);
  10630. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10631. return this._postProcesses.length - 1;
  10632. }
  10633. var add = 0;
  10634. var i;
  10635. var start;
  10636. if (this._postProcesses[insertAt]) {
  10637. start = this._postProcesses.length - 1;
  10638. for (i = start; i >= insertAt + 1; --i) {
  10639. this._postProcesses[i + 1] = this._postProcesses[i];
  10640. }
  10641. add = 1;
  10642. }
  10643. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10644. if (this._postProcessesTakenIndices[i] < insertAt) {
  10645. continue;
  10646. }
  10647. start = this._postProcessesTakenIndices.length - 1;
  10648. for (var j = start; j >= i; --j) {
  10649. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10650. }
  10651. this._postProcessesTakenIndices[i] = insertAt;
  10652. break;
  10653. }
  10654. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10655. this._postProcessesTakenIndices.push(insertAt);
  10656. }
  10657. var result = insertAt + add;
  10658. this._postProcesses[result] = postProcess;
  10659. return result;
  10660. };
  10661. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10662. if (atIndices === void 0) { atIndices = null; }
  10663. var result = [];
  10664. var i;
  10665. var index;
  10666. if (!atIndices) {
  10667. var length = this._postProcesses.length;
  10668. for (i = 0; i < length; i++) {
  10669. if (this._postProcesses[i] !== postProcess) {
  10670. continue;
  10671. }
  10672. delete this._postProcesses[i];
  10673. index = this._postProcessesTakenIndices.indexOf(i);
  10674. this._postProcessesTakenIndices.splice(index, 1);
  10675. }
  10676. }
  10677. else {
  10678. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10679. for (i = 0; i < atIndices.length; i++) {
  10680. var foundPostProcess = this._postProcesses[atIndices[i]];
  10681. if (foundPostProcess !== postProcess) {
  10682. result.push(i);
  10683. continue;
  10684. }
  10685. delete this._postProcesses[atIndices[i]];
  10686. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10687. this._postProcessesTakenIndices.splice(index, 1);
  10688. }
  10689. }
  10690. return result;
  10691. };
  10692. Camera.prototype.getWorldMatrix = function () {
  10693. if (!this._worldMatrix) {
  10694. this._worldMatrix = BABYLON.Matrix.Identity();
  10695. }
  10696. var viewMatrix = this.getViewMatrix();
  10697. viewMatrix.invertToRef(this._worldMatrix);
  10698. return this._worldMatrix;
  10699. };
  10700. Camera.prototype._getViewMatrix = function () {
  10701. return BABYLON.Matrix.Identity();
  10702. };
  10703. Camera.prototype.getViewMatrix = function (force) {
  10704. this._computedViewMatrix = this._computeViewMatrix(force);
  10705. if (!force && this._isSynchronizedViewMatrix()) {
  10706. return this._computedViewMatrix;
  10707. }
  10708. if (!this.parent || !this.parent.getWorldMatrix) {
  10709. this._globalPosition.copyFrom(this.position);
  10710. }
  10711. else {
  10712. if (!this._worldMatrix) {
  10713. this._worldMatrix = BABYLON.Matrix.Identity();
  10714. }
  10715. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10716. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10717. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10718. this._computedViewMatrix.invert();
  10719. this._markSyncedWithParent();
  10720. }
  10721. this._currentRenderId = this.getScene().getRenderId();
  10722. return this._computedViewMatrix;
  10723. };
  10724. Camera.prototype._computeViewMatrix = function (force) {
  10725. if (!force && this._isSynchronizedViewMatrix()) {
  10726. return this._computedViewMatrix;
  10727. }
  10728. this._computedViewMatrix = this._getViewMatrix();
  10729. this._currentRenderId = this.getScene().getRenderId();
  10730. return this._computedViewMatrix;
  10731. };
  10732. Camera.prototype.getProjectionMatrix = function (force) {
  10733. if (!force && this._isSynchronizedProjectionMatrix()) {
  10734. return this._projectionMatrix;
  10735. }
  10736. var engine = this.getEngine();
  10737. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10738. if (this.minZ <= 0) {
  10739. this.minZ = 0.1;
  10740. }
  10741. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10742. return this._projectionMatrix;
  10743. }
  10744. var halfWidth = engine.getRenderWidth() / 2.0;
  10745. var halfHeight = engine.getRenderHeight() / 2.0;
  10746. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10747. return this._projectionMatrix;
  10748. };
  10749. Camera.prototype.dispose = function () {
  10750. // Animations
  10751. this.getScene().stopAnimation(this);
  10752. // Remove from scene
  10753. this.getScene().removeCamera(this);
  10754. while (this._rigCameras.length > 0) {
  10755. this._rigCameras.pop().dispose();
  10756. }
  10757. // Postprocesses
  10758. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10759. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10760. }
  10761. };
  10762. // ---- Camera rigs section ----
  10763. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10764. while (this._rigCameras.length > 0) {
  10765. this._rigCameras.pop().dispose();
  10766. }
  10767. this.cameraRigMode = mode;
  10768. this._cameraRigParams = {};
  10769. switch (this.cameraRigMode) {
  10770. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10771. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10772. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10773. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10774. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10775. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10776. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10777. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10778. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10779. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10780. break;
  10781. }
  10782. var postProcesses = new Array();
  10783. switch (this.cameraRigMode) {
  10784. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10785. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10786. this._rigCameras[0].isIntermediate = true;
  10787. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10788. postProcesses[1].onApply = function (effect) {
  10789. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10790. };
  10791. break;
  10792. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10793. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10794. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10795. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10796. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10797. var secondCamIndex = 1 - firstCamIndex;
  10798. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10799. this._rigCameras[firstCamIndex].isIntermediate = true;
  10800. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10801. break;
  10802. case Camera.RIG_MODE_VR:
  10803. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10804. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10805. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10806. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10807. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10808. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10809. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10810. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10811. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10812. if (metrics.compensateDistortion) {
  10813. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10814. }
  10815. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10816. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10817. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10818. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10819. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10820. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10821. if (metrics.compensateDistortion) {
  10822. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10823. }
  10824. break;
  10825. }
  10826. this._update();
  10827. };
  10828. Camera.prototype._getVRProjectionMatrix = function () {
  10829. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10830. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10831. return this._projectionMatrix;
  10832. };
  10833. Camera.prototype.setCameraRigParameter = function (name, value) {
  10834. this._cameraRigParams[name] = value;
  10835. //provisionnally:
  10836. if (name === "interaxialDistance") {
  10837. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10838. }
  10839. };
  10840. /**
  10841. * May needs to be overridden by children so sub has required properties to be copied
  10842. */
  10843. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10844. return null;
  10845. };
  10846. /**
  10847. * May needs to be overridden by children
  10848. */
  10849. Camera.prototype._updateRigCameras = function () {
  10850. for (var i = 0; i < this._rigCameras.length; i++) {
  10851. this._rigCameras[i].minZ = this.minZ;
  10852. this._rigCameras[i].maxZ = this.maxZ;
  10853. this._rigCameras[i].fov = this.fov;
  10854. }
  10855. // only update viewport when ANAGLYPH
  10856. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10857. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10858. }
  10859. };
  10860. Camera.prototype.serialize = function () {
  10861. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10862. // Type
  10863. serializationObject.type = this.getTypeName();
  10864. // Parent
  10865. if (this.parent) {
  10866. serializationObject.parentId = this.parent.id;
  10867. }
  10868. // Animations
  10869. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10870. serializationObject.ranges = this.serializeAnimationRanges();
  10871. return serializationObject;
  10872. };
  10873. Camera.prototype.getTypeName = function () {
  10874. return "Camera";
  10875. };
  10876. Camera.prototype.clone = function (name) {
  10877. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10878. };
  10879. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10880. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10881. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10882. switch (type) {
  10883. case "ArcRotateCamera":
  10884. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10885. case "DeviceOrientationCamera":
  10886. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10887. case "FollowCamera":
  10888. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10889. case "ArcFollowCamera":
  10890. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10891. case "GamepadCamera":
  10892. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10893. case "TouchCamera":
  10894. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10895. case "VirtualJoysticksCamera":
  10896. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10897. case "WebVRFreeCamera":
  10898. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10899. case "VRDeviceOrientationFreeCamera":
  10900. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10901. case "AnaglyphArcRotateCamera":
  10902. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10903. case "AnaglyphFreeCamera":
  10904. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10905. case "AnaglyphGamepadCamera":
  10906. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10907. case "AnaglyphUniversalCamera":
  10908. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10909. case "StereoscopicArcRotateCamera":
  10910. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10911. case "StereoscopicFreeCamera":
  10912. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10913. case "StereoscopicGamepadCamera":
  10914. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10915. case "StereoscopicUniversalCamera":
  10916. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10917. case "FreeCamera":
  10918. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10919. default:
  10920. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10921. }
  10922. };
  10923. Camera.Parse = function (parsedCamera, scene) {
  10924. var type = parsedCamera.type;
  10925. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10926. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10927. // Parent
  10928. if (parsedCamera.parentId) {
  10929. camera._waitingParentId = parsedCamera.parentId;
  10930. }
  10931. // Target
  10932. if (parsedCamera.target) {
  10933. if (camera.setTarget) {
  10934. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10935. }
  10936. }
  10937. // Apply 3d rig, when found
  10938. if (parsedCamera.cameraRigMode) {
  10939. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10940. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10941. }
  10942. // Animations
  10943. if (parsedCamera.animations) {
  10944. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10945. var parsedAnimation = parsedCamera.animations[animationIndex];
  10946. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10947. }
  10948. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10949. }
  10950. if (parsedCamera.autoAnimate) {
  10951. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10952. }
  10953. return camera;
  10954. };
  10955. // Statics
  10956. Camera._PERSPECTIVE_CAMERA = 0;
  10957. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10958. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10959. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10960. Camera._RIG_MODE_NONE = 0;
  10961. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10962. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10963. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10964. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10965. Camera._RIG_MODE_VR = 20;
  10966. __decorate([
  10967. BABYLON.serializeAsVector3()
  10968. ], Camera.prototype, "position", void 0);
  10969. __decorate([
  10970. BABYLON.serialize()
  10971. ], Camera.prototype, "upVector", void 0);
  10972. __decorate([
  10973. BABYLON.serialize()
  10974. ], Camera.prototype, "orthoLeft", void 0);
  10975. __decorate([
  10976. BABYLON.serialize()
  10977. ], Camera.prototype, "orthoRight", void 0);
  10978. __decorate([
  10979. BABYLON.serialize()
  10980. ], Camera.prototype, "orthoBottom", void 0);
  10981. __decorate([
  10982. BABYLON.serialize()
  10983. ], Camera.prototype, "orthoTop", void 0);
  10984. __decorate([
  10985. BABYLON.serialize()
  10986. ], Camera.prototype, "fov", void 0);
  10987. __decorate([
  10988. BABYLON.serialize()
  10989. ], Camera.prototype, "minZ", void 0);
  10990. __decorate([
  10991. BABYLON.serialize()
  10992. ], Camera.prototype, "maxZ", void 0);
  10993. __decorate([
  10994. BABYLON.serialize()
  10995. ], Camera.prototype, "inertia", void 0);
  10996. __decorate([
  10997. BABYLON.serialize()
  10998. ], Camera.prototype, "mode", void 0);
  10999. __decorate([
  11000. BABYLON.serialize()
  11001. ], Camera.prototype, "layerMask", void 0);
  11002. __decorate([
  11003. BABYLON.serialize()
  11004. ], Camera.prototype, "fovMode", void 0);
  11005. __decorate([
  11006. BABYLON.serialize()
  11007. ], Camera.prototype, "cameraRigMode", void 0);
  11008. __decorate([
  11009. BABYLON.serialize()
  11010. ], Camera.prototype, "interaxialDistance", void 0);
  11011. __decorate([
  11012. BABYLON.serialize()
  11013. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11014. return Camera;
  11015. })(BABYLON.Node);
  11016. BABYLON.Camera = Camera;
  11017. })(BABYLON || (BABYLON = {}));
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. var TargetCamera = (function (_super) {
  11021. __extends(TargetCamera, _super);
  11022. function TargetCamera(name, position, scene) {
  11023. _super.call(this, name, position, scene);
  11024. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11025. this.cameraRotation = new BABYLON.Vector2(0, 0);
  11026. this.rotation = new BABYLON.Vector3(0, 0, 0);
  11027. this.speed = 2.0;
  11028. this.noRotationConstraint = false;
  11029. this.lockedTarget = null;
  11030. this._currentTarget = BABYLON.Vector3.Zero();
  11031. this._viewMatrix = BABYLON.Matrix.Zero();
  11032. this._camMatrix = BABYLON.Matrix.Zero();
  11033. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  11034. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  11035. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  11036. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  11037. this._lookAtTemp = BABYLON.Matrix.Zero();
  11038. this._tempMatrix = BABYLON.Matrix.Zero();
  11039. }
  11040. TargetCamera.prototype.getFrontPosition = function (distance) {
  11041. var direction = this.getTarget().subtract(this.position);
  11042. direction.normalize();
  11043. direction.scaleInPlace(distance);
  11044. return this.globalPosition.add(direction);
  11045. };
  11046. TargetCamera.prototype._getLockedTargetPosition = function () {
  11047. if (!this.lockedTarget) {
  11048. return null;
  11049. }
  11050. return this.lockedTarget.position || this.lockedTarget;
  11051. };
  11052. // Cache
  11053. TargetCamera.prototype._initCache = function () {
  11054. _super.prototype._initCache.call(this);
  11055. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11056. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11057. };
  11058. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11059. if (!ignoreParentClass) {
  11060. _super.prototype._updateCache.call(this);
  11061. }
  11062. var lockedTargetPosition = this._getLockedTargetPosition();
  11063. if (!lockedTargetPosition) {
  11064. this._cache.lockedTarget = null;
  11065. }
  11066. else {
  11067. if (!this._cache.lockedTarget) {
  11068. this._cache.lockedTarget = lockedTargetPosition.clone();
  11069. }
  11070. else {
  11071. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11072. }
  11073. }
  11074. this._cache.rotation.copyFrom(this.rotation);
  11075. };
  11076. // Synchronized
  11077. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11078. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11079. return false;
  11080. }
  11081. var lockedTargetPosition = this._getLockedTargetPosition();
  11082. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11083. && this._cache.rotation.equals(this.rotation);
  11084. };
  11085. // Methods
  11086. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11087. var engine = this.getEngine();
  11088. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11089. };
  11090. // Target
  11091. TargetCamera.prototype.setTarget = function (target) {
  11092. this.upVector.normalize();
  11093. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11094. this._camMatrix.invert();
  11095. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11096. var vDir = target.subtract(this.position);
  11097. if (vDir.x >= 0.0) {
  11098. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11099. }
  11100. else {
  11101. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11102. }
  11103. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11104. if (isNaN(this.rotation.x)) {
  11105. this.rotation.x = 0;
  11106. }
  11107. if (isNaN(this.rotation.y)) {
  11108. this.rotation.y = 0;
  11109. }
  11110. if (isNaN(this.rotation.z)) {
  11111. this.rotation.z = 0;
  11112. }
  11113. };
  11114. TargetCamera.prototype.getTarget = function () {
  11115. return this._currentTarget;
  11116. };
  11117. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11118. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11119. };
  11120. TargetCamera.prototype._updatePosition = function () {
  11121. this.position.addInPlace(this.cameraDirection);
  11122. };
  11123. TargetCamera.prototype._checkInputs = function () {
  11124. var needToMove = this._decideIfNeedsToMove();
  11125. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11126. // Move
  11127. if (needToMove) {
  11128. this._updatePosition();
  11129. }
  11130. // Rotate
  11131. if (needToRotate) {
  11132. this.rotation.x += this.cameraRotation.x;
  11133. this.rotation.y += this.cameraRotation.y;
  11134. if (!this.noRotationConstraint) {
  11135. var limit = (Math.PI / 2) * 0.95;
  11136. if (this.rotation.x > limit)
  11137. this.rotation.x = limit;
  11138. if (this.rotation.x < -limit)
  11139. this.rotation.x = -limit;
  11140. }
  11141. }
  11142. // Inertia
  11143. if (needToMove) {
  11144. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11145. this.cameraDirection.x = 0;
  11146. }
  11147. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11148. this.cameraDirection.y = 0;
  11149. }
  11150. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11151. this.cameraDirection.z = 0;
  11152. }
  11153. this.cameraDirection.scaleInPlace(this.inertia);
  11154. }
  11155. if (needToRotate) {
  11156. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11157. this.cameraRotation.x = 0;
  11158. }
  11159. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11160. this.cameraRotation.y = 0;
  11161. }
  11162. this.cameraRotation.scaleInPlace(this.inertia);
  11163. }
  11164. _super.prototype._checkInputs.call(this);
  11165. };
  11166. TargetCamera.prototype._getViewMatrix = function () {
  11167. if (!this.lockedTarget) {
  11168. // Compute
  11169. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11170. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11171. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11172. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11173. this._lookAtTemp.invert();
  11174. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11175. }
  11176. else {
  11177. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11178. }
  11179. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11180. // Computing target and final matrix
  11181. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11182. }
  11183. else {
  11184. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11185. }
  11186. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11187. return this._viewMatrix;
  11188. };
  11189. TargetCamera.prototype._getVRViewMatrix = function () {
  11190. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11191. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11192. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11193. // Computing target and final matrix
  11194. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11195. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11196. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11197. return this._viewMatrix;
  11198. };
  11199. /**
  11200. * @override
  11201. * Override Camera.createRigCamera
  11202. */
  11203. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11204. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11205. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11206. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11207. rigCamera._cameraRigParams = {};
  11208. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11209. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11210. }
  11211. return rigCamera;
  11212. }
  11213. return null;
  11214. };
  11215. /**
  11216. * @override
  11217. * Override Camera._updateRigCameras
  11218. */
  11219. TargetCamera.prototype._updateRigCameras = function () {
  11220. switch (this.cameraRigMode) {
  11221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11222. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11224. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11225. case BABYLON.Camera.RIG_MODE_VR:
  11226. var camLeft = this._rigCameras[0];
  11227. var camRight = this._rigCameras[1];
  11228. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11229. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11230. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11231. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11232. camLeft.position.copyFrom(this.position);
  11233. camRight.position.copyFrom(this.position);
  11234. }
  11235. else {
  11236. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11237. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11238. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11239. camLeft.setTarget(this.getTarget());
  11240. camRight.setTarget(this.getTarget());
  11241. }
  11242. break;
  11243. }
  11244. _super.prototype._updateRigCameras.call(this);
  11245. };
  11246. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11247. if (!this._rigCamTransformMatrix) {
  11248. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11249. }
  11250. var target = this.getTarget();
  11251. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11252. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11254. };
  11255. TargetCamera.prototype.getTypeName = function () {
  11256. return "TargetCamera";
  11257. };
  11258. __decorate([
  11259. BABYLON.serializeAsVector3()
  11260. ], TargetCamera.prototype, "rotation", void 0);
  11261. __decorate([
  11262. BABYLON.serialize()
  11263. ], TargetCamera.prototype, "speed", void 0);
  11264. __decorate([
  11265. BABYLON.serializeAsMeshReference("lockedTargetId")
  11266. ], TargetCamera.prototype, "lockedTarget", void 0);
  11267. return TargetCamera;
  11268. })(BABYLON.Camera);
  11269. BABYLON.TargetCamera = TargetCamera;
  11270. })(BABYLON || (BABYLON = {}));
  11271. var BABYLON;
  11272. (function (BABYLON) {
  11273. var FreeCamera = (function (_super) {
  11274. __extends(FreeCamera, _super);
  11275. function FreeCamera(name, position, scene) {
  11276. var _this = this;
  11277. _super.call(this, name, position, scene);
  11278. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11279. this.keysUp = [38];
  11280. this.keysDown = [40];
  11281. this.keysLeft = [37];
  11282. this.keysRight = [39];
  11283. this.checkCollisions = false;
  11284. this.applyGravity = false;
  11285. this.angularSensibility = 2000.0;
  11286. this._keys = [];
  11287. this._collider = new BABYLON.Collider();
  11288. this._needMoveForGravity = false;
  11289. this._oldPosition = BABYLON.Vector3.Zero();
  11290. this._diffPosition = BABYLON.Vector3.Zero();
  11291. this._newPosition = BABYLON.Vector3.Zero();
  11292. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11293. if (collidedMesh === void 0) { collidedMesh = null; }
  11294. //TODO move this to the collision coordinator!
  11295. if (_this.getScene().workerCollisions)
  11296. newPosition.multiplyInPlace(_this._collider.radius);
  11297. var updatePosition = function (newPos) {
  11298. _this._newPosition.copyFrom(newPos);
  11299. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11300. var oldPosition = _this.position.clone();
  11301. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11302. _this.position.addInPlace(_this._diffPosition);
  11303. if (_this.onCollide && collidedMesh) {
  11304. _this.onCollide(collidedMesh);
  11305. }
  11306. }
  11307. };
  11308. updatePosition(newPosition);
  11309. };
  11310. }
  11311. FreeCamera.prototype._onLostFocus = function (e) {
  11312. this._keys = [];
  11313. };
  11314. // Controls
  11315. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11316. var _this = this;
  11317. var previousPosition;
  11318. var engine = this.getEngine();
  11319. if (this._attachedElement) {
  11320. return;
  11321. }
  11322. this._attachedElement = element;
  11323. if (this._onMouseDown === undefined) {
  11324. this._onMouseDown = function (evt) {
  11325. previousPosition = {
  11326. x: evt.clientX,
  11327. y: evt.clientY
  11328. };
  11329. if (!noPreventDefault) {
  11330. evt.preventDefault();
  11331. }
  11332. };
  11333. this._onMouseUp = function (evt) {
  11334. previousPosition = null;
  11335. if (!noPreventDefault) {
  11336. evt.preventDefault();
  11337. }
  11338. };
  11339. this._onMouseOut = function (evt) {
  11340. previousPosition = null;
  11341. _this._keys = [];
  11342. if (!noPreventDefault) {
  11343. evt.preventDefault();
  11344. }
  11345. };
  11346. this._onMouseMove = function (evt) {
  11347. if (!previousPosition && !engine.isPointerLock) {
  11348. return;
  11349. }
  11350. var offsetX;
  11351. var offsetY;
  11352. if (!engine.isPointerLock) {
  11353. offsetX = evt.clientX - previousPosition.x;
  11354. offsetY = evt.clientY - previousPosition.y;
  11355. }
  11356. else {
  11357. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11358. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11359. }
  11360. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11361. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11362. previousPosition = {
  11363. x: evt.clientX,
  11364. y: evt.clientY
  11365. };
  11366. if (!noPreventDefault) {
  11367. evt.preventDefault();
  11368. }
  11369. };
  11370. this._onKeyDown = function (evt) {
  11371. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11372. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11373. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11374. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11375. var index = _this._keys.indexOf(evt.keyCode);
  11376. if (index === -1) {
  11377. _this._keys.push(evt.keyCode);
  11378. }
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. }
  11383. };
  11384. this._onKeyUp = function (evt) {
  11385. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11386. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11387. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11388. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11389. var index = _this._keys.indexOf(evt.keyCode);
  11390. if (index >= 0) {
  11391. _this._keys.splice(index, 1);
  11392. }
  11393. if (!noPreventDefault) {
  11394. evt.preventDefault();
  11395. }
  11396. }
  11397. };
  11398. this._reset = function () {
  11399. _this._keys = [];
  11400. previousPosition = null;
  11401. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11402. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11403. };
  11404. }
  11405. element.addEventListener("mousedown", this._onMouseDown, false);
  11406. element.addEventListener("mouseup", this._onMouseUp, false);
  11407. element.addEventListener("mouseout", this._onMouseOut, false);
  11408. element.addEventListener("mousemove", this._onMouseMove, false);
  11409. BABYLON.Tools.RegisterTopRootEvents([
  11410. { name: "keydown", handler: this._onKeyDown },
  11411. { name: "keyup", handler: this._onKeyUp },
  11412. { name: "blur", handler: this._onLostFocus }
  11413. ]);
  11414. };
  11415. FreeCamera.prototype.detachControl = function (element) {
  11416. if (this._attachedElement !== element) {
  11417. return;
  11418. }
  11419. element.removeEventListener("mousedown", this._onMouseDown);
  11420. element.removeEventListener("mouseup", this._onMouseUp);
  11421. element.removeEventListener("mouseout", this._onMouseOut);
  11422. element.removeEventListener("mousemove", this._onMouseMove);
  11423. BABYLON.Tools.UnregisterTopRootEvents([
  11424. { name: "keydown", handler: this._onKeyDown },
  11425. { name: "keyup", handler: this._onKeyUp },
  11426. { name: "blur", handler: this._onLostFocus }
  11427. ]);
  11428. this._attachedElement = null;
  11429. if (this._reset) {
  11430. this._reset();
  11431. }
  11432. };
  11433. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11434. var globalPosition;
  11435. if (this.parent) {
  11436. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11437. }
  11438. else {
  11439. globalPosition = this.position;
  11440. }
  11441. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11442. this._collider.radius = this.ellipsoid;
  11443. //no need for clone, as long as gravity is not on.
  11444. var actualVelocity = velocity;
  11445. //add gravity to the velocity to prevent the dual-collision checking
  11446. if (this.applyGravity) {
  11447. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11448. actualVelocity = velocity.add(this.getScene().gravity);
  11449. }
  11450. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11451. };
  11452. FreeCamera.prototype._checkInputs = function () {
  11453. if (!this._localDirection) {
  11454. this._localDirection = BABYLON.Vector3.Zero();
  11455. this._transformedDirection = BABYLON.Vector3.Zero();
  11456. }
  11457. // Keyboard
  11458. for (var index = 0; index < this._keys.length; index++) {
  11459. var keyCode = this._keys[index];
  11460. var speed = this._computeLocalCameraSpeed();
  11461. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11462. this._localDirection.copyFromFloats(-speed, 0, 0);
  11463. }
  11464. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11465. this._localDirection.copyFromFloats(0, 0, speed);
  11466. }
  11467. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11468. this._localDirection.copyFromFloats(speed, 0, 0);
  11469. }
  11470. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11471. this._localDirection.copyFromFloats(0, 0, -speed);
  11472. }
  11473. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11474. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11475. this.cameraDirection.addInPlace(this._transformedDirection);
  11476. }
  11477. _super.prototype._checkInputs.call(this);
  11478. };
  11479. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11480. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11481. };
  11482. FreeCamera.prototype._updatePosition = function () {
  11483. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11484. this._collideWithWorld(this.cameraDirection);
  11485. }
  11486. else {
  11487. this.position.addInPlace(this.cameraDirection);
  11488. }
  11489. };
  11490. FreeCamera.prototype.getTypeName = function () {
  11491. return "FreeCamera";
  11492. };
  11493. __decorate([
  11494. BABYLON.serializeAsVector3()
  11495. ], FreeCamera.prototype, "ellipsoid", void 0);
  11496. __decorate([
  11497. BABYLON.serialize()
  11498. ], FreeCamera.prototype, "keysUp", void 0);
  11499. __decorate([
  11500. BABYLON.serialize()
  11501. ], FreeCamera.prototype, "keysDown", void 0);
  11502. __decorate([
  11503. BABYLON.serialize()
  11504. ], FreeCamera.prototype, "keysLeft", void 0);
  11505. __decorate([
  11506. BABYLON.serialize()
  11507. ], FreeCamera.prototype, "keysRight", void 0);
  11508. __decorate([
  11509. BABYLON.serialize()
  11510. ], FreeCamera.prototype, "checkCollisions", void 0);
  11511. __decorate([
  11512. BABYLON.serialize()
  11513. ], FreeCamera.prototype, "applyGravity", void 0);
  11514. __decorate([
  11515. BABYLON.serialize()
  11516. ], FreeCamera.prototype, "angularSensibility", void 0);
  11517. return FreeCamera;
  11518. })(BABYLON.TargetCamera);
  11519. BABYLON.FreeCamera = FreeCamera;
  11520. })(BABYLON || (BABYLON = {}));
  11521. var BABYLON;
  11522. (function (BABYLON) {
  11523. var FollowCamera = (function (_super) {
  11524. __extends(FollowCamera, _super);
  11525. function FollowCamera(name, position, scene, target) {
  11526. _super.call(this, name, position, scene);
  11527. this.radius = 12;
  11528. this.rotationOffset = 0;
  11529. this.heightOffset = 4;
  11530. this.cameraAcceleration = 0.05;
  11531. this.maxCameraSpeed = 20;
  11532. this.target = target;
  11533. }
  11534. FollowCamera.prototype.getRadians = function (degrees) {
  11535. return degrees * Math.PI / 180;
  11536. };
  11537. FollowCamera.prototype.follow = function (cameraTarget) {
  11538. if (!cameraTarget)
  11539. return;
  11540. var yRotation;
  11541. if (cameraTarget.rotationQuaternion) {
  11542. var rotMatrix = new BABYLON.Matrix();
  11543. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11544. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11545. }
  11546. else {
  11547. yRotation = cameraTarget.rotation.y;
  11548. }
  11549. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11550. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11551. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11552. var dx = targetX - this.position.x;
  11553. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11554. var dz = (targetZ) - this.position.z;
  11555. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11556. var vy = dy * this.cameraAcceleration;
  11557. var vz = dz * this.cameraAcceleration * 2;
  11558. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11559. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11560. }
  11561. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11562. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11563. }
  11564. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11565. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11566. }
  11567. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11568. this.setTarget(cameraTarget.position);
  11569. };
  11570. FollowCamera.prototype._checkInputs = function () {
  11571. _super.prototype._checkInputs.call(this);
  11572. this.follow(this.target);
  11573. };
  11574. FollowCamera.prototype.getTypeName = function () {
  11575. return "FollowCamera";
  11576. };
  11577. __decorate([
  11578. BABYLON.serialize()
  11579. ], FollowCamera.prototype, "radius", void 0);
  11580. __decorate([
  11581. BABYLON.serialize()
  11582. ], FollowCamera.prototype, "rotationOffset", void 0);
  11583. __decorate([
  11584. BABYLON.serialize()
  11585. ], FollowCamera.prototype, "heightOffset", void 0);
  11586. __decorate([
  11587. BABYLON.serialize()
  11588. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11589. __decorate([
  11590. BABYLON.serialize()
  11591. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11592. __decorate([
  11593. BABYLON.serializeAsMeshReference("lockedTargetId")
  11594. ], FollowCamera.prototype, "target", void 0);
  11595. return FollowCamera;
  11596. })(BABYLON.TargetCamera);
  11597. BABYLON.FollowCamera = FollowCamera;
  11598. var ArcFollowCamera = (function (_super) {
  11599. __extends(ArcFollowCamera, _super);
  11600. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11601. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11602. this.alpha = alpha;
  11603. this.beta = beta;
  11604. this.radius = radius;
  11605. this.target = target;
  11606. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11607. this.follow();
  11608. }
  11609. ArcFollowCamera.prototype.follow = function () {
  11610. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11611. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11612. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11613. this.position = this.target.position.add(this._cartesianCoordinates);
  11614. this.setTarget(this.target.position);
  11615. };
  11616. ArcFollowCamera.prototype._checkInputs = function () {
  11617. _super.prototype._checkInputs.call(this);
  11618. this.follow();
  11619. };
  11620. ArcFollowCamera.prototype.getTypeName = function () {
  11621. return "ArcFollowCamera";
  11622. };
  11623. return ArcFollowCamera;
  11624. })(BABYLON.TargetCamera);
  11625. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11626. })(BABYLON || (BABYLON = {}));
  11627. var BABYLON;
  11628. (function (BABYLON) {
  11629. // We're mainly based on the logic defined into the FreeCamera code
  11630. var TouchCamera = (function (_super) {
  11631. __extends(TouchCamera, _super);
  11632. function TouchCamera(name, position, scene) {
  11633. _super.call(this, name, position, scene);
  11634. this._offsetX = null;
  11635. this._offsetY = null;
  11636. this._pointerCount = 0;
  11637. this._pointerPressed = [];
  11638. this.touchAngularSensibility = 200000.0;
  11639. this.touchMoveSensibility = 250.0;
  11640. }
  11641. TouchCamera.prototype._onLostFocus = function (e) {
  11642. this._offsetX = null;
  11643. this._offsetY = null;
  11644. _super.prototype._onLostFocus.call(this, e);
  11645. };
  11646. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11647. var _this = this;
  11648. var previousPosition;
  11649. if (this._attachedCanvas) {
  11650. return;
  11651. }
  11652. if (this._onPointerDown === undefined) {
  11653. this._onPointerDown = function (evt) {
  11654. if (evt.pointerType === "mouse") {
  11655. return;
  11656. }
  11657. if (!noPreventDefault) {
  11658. evt.preventDefault();
  11659. }
  11660. _this._pointerPressed.push(evt.pointerId);
  11661. if (_this._pointerPressed.length !== 1) {
  11662. return;
  11663. }
  11664. previousPosition = {
  11665. x: evt.clientX,
  11666. y: evt.clientY
  11667. };
  11668. };
  11669. this._onPointerUp = function (evt) {
  11670. if (evt.pointerType === "mouse") {
  11671. return;
  11672. }
  11673. if (!noPreventDefault) {
  11674. evt.preventDefault();
  11675. }
  11676. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11677. if (index === -1) {
  11678. return;
  11679. }
  11680. _this._pointerPressed.splice(index, 1);
  11681. if (index != 0) {
  11682. return;
  11683. }
  11684. previousPosition = null;
  11685. _this._offsetX = null;
  11686. _this._offsetY = null;
  11687. };
  11688. this._onPointerMove = function (evt) {
  11689. if (evt.pointerType === "mouse") {
  11690. return;
  11691. }
  11692. if (!noPreventDefault) {
  11693. evt.preventDefault();
  11694. }
  11695. if (!previousPosition) {
  11696. return;
  11697. }
  11698. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11699. if (index != 0) {
  11700. return;
  11701. }
  11702. _this._offsetX = evt.clientX - previousPosition.x;
  11703. _this._offsetY = -(evt.clientY - previousPosition.y);
  11704. };
  11705. }
  11706. canvas.addEventListener("pointerdown", this._onPointerDown);
  11707. canvas.addEventListener("pointerup", this._onPointerUp);
  11708. canvas.addEventListener("pointerout", this._onPointerUp);
  11709. canvas.addEventListener("pointermove", this._onPointerMove);
  11710. _super.prototype.attachControl.call(this, canvas);
  11711. };
  11712. TouchCamera.prototype.detachControl = function (canvas) {
  11713. if (this._attachedCanvas !== canvas) {
  11714. return;
  11715. }
  11716. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11717. canvas.removeEventListener("pointerup", this._onPointerUp);
  11718. canvas.removeEventListener("pointerout", this._onPointerUp);
  11719. canvas.removeEventListener("pointermove", this._onPointerMove);
  11720. _super.prototype.detachControl.call(this, canvas);
  11721. };
  11722. TouchCamera.prototype._checkInputs = function () {
  11723. if (this._offsetX) {
  11724. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11725. if (this._pointerPressed.length > 1) {
  11726. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11727. }
  11728. else {
  11729. var speed = this._computeLocalCameraSpeed();
  11730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11732. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11733. }
  11734. }
  11735. _super.prototype._checkInputs.call(this);
  11736. };
  11737. TouchCamera.prototype.getTypeName = function () {
  11738. return "TouchCamera";
  11739. };
  11740. __decorate([
  11741. BABYLON.serialize()
  11742. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11743. __decorate([
  11744. BABYLON.serialize()
  11745. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11746. return TouchCamera;
  11747. })(BABYLON.FreeCamera);
  11748. BABYLON.TouchCamera = TouchCamera;
  11749. })(BABYLON || (BABYLON = {}));
  11750. var BABYLON;
  11751. (function (BABYLON) {
  11752. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11753. var ArcRotateCamera = (function (_super) {
  11754. __extends(ArcRotateCamera, _super);
  11755. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11756. var _this = this;
  11757. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11758. this.inertialAlphaOffset = 0;
  11759. this.inertialBetaOffset = 0;
  11760. this.inertialRadiusOffset = 0;
  11761. this.lowerAlphaLimit = null;
  11762. this.upperAlphaLimit = null;
  11763. this.lowerBetaLimit = 0.01;
  11764. this.upperBetaLimit = Math.PI;
  11765. this.lowerRadiusLimit = null;
  11766. this.upperRadiusLimit = null;
  11767. this.angularSensibilityX = 1000.0;
  11768. this.angularSensibilityY = 1000.0;
  11769. this.wheelPrecision = 3.0;
  11770. this.pinchPrecision = 2.0;
  11771. this.panningSensibility = 50.0;
  11772. this.inertialPanningX = 0;
  11773. this.inertialPanningY = 0;
  11774. this.keysUp = [38];
  11775. this.keysDown = [40];
  11776. this.keysLeft = [37];
  11777. this.keysRight = [39];
  11778. this.zoomOnFactor = 1;
  11779. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11780. this.pinchInwards = true;
  11781. this.allowUpsideDown = true;
  11782. this._keys = [];
  11783. this._viewMatrix = new BABYLON.Matrix();
  11784. // Panning
  11785. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11786. this._isRightClick = false;
  11787. this._isCtrlPushed = false;
  11788. this.checkCollisions = false;
  11789. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11790. this._collider = new BABYLON.Collider();
  11791. this._previousPosition = BABYLON.Vector3.Zero();
  11792. this._collisionVelocity = BABYLON.Vector3.Zero();
  11793. this._newPosition = BABYLON.Vector3.Zero();
  11794. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11795. if (collidedMesh === void 0) { collidedMesh = null; }
  11796. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11797. newPosition.multiplyInPlace(_this._collider.radius);
  11798. }
  11799. if (!collidedMesh) {
  11800. _this._previousPosition.copyFrom(_this.position);
  11801. }
  11802. else {
  11803. _this.setPosition(newPosition);
  11804. if (_this.onCollide) {
  11805. _this.onCollide(collidedMesh);
  11806. }
  11807. }
  11808. // Recompute because of constraints
  11809. var cosa = Math.cos(_this.alpha);
  11810. var sina = Math.sin(_this.alpha);
  11811. var cosb = Math.cos(_this.beta);
  11812. var sinb = Math.sin(_this.beta);
  11813. if (sinb === 0) {
  11814. sinb = 0.0001;
  11815. }
  11816. var target = _this._getTargetPosition();
  11817. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11818. _this.position.copyFrom(_this._newPosition);
  11819. var up = _this.upVector;
  11820. if (_this.allowUpsideDown && _this.beta < 0) {
  11821. up = up.clone();
  11822. up = up.negate();
  11823. }
  11824. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11825. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11826. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11827. _this._collisionTriggered = false;
  11828. };
  11829. if (!target) {
  11830. this.target = BABYLON.Vector3.Zero();
  11831. }
  11832. else {
  11833. this.target = target;
  11834. }
  11835. this.alpha = alpha;
  11836. this.beta = beta;
  11837. this.radius = radius;
  11838. this.getViewMatrix();
  11839. }
  11840. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11841. //deprecated angularSensibility support
  11842. get: function () {
  11843. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11844. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11845. },
  11846. //deprecated angularSensibility support
  11847. set: function (value) {
  11848. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11849. this.angularSensibilityX = value;
  11850. this.angularSensibilityY = value;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. // Cache
  11856. ArcRotateCamera.prototype._initCache = function () {
  11857. _super.prototype._initCache.call(this);
  11858. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11859. this._cache.alpha = undefined;
  11860. this._cache.beta = undefined;
  11861. this._cache.radius = undefined;
  11862. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11863. };
  11864. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11865. if (!ignoreParentClass) {
  11866. _super.prototype._updateCache.call(this);
  11867. }
  11868. this._cache.target.copyFrom(this._getTargetPosition());
  11869. this._cache.alpha = this.alpha;
  11870. this._cache.beta = this.beta;
  11871. this._cache.radius = this.radius;
  11872. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11873. };
  11874. ArcRotateCamera.prototype._getTargetPosition = function () {
  11875. if (this.target.getAbsolutePosition) {
  11876. return this.target.getAbsolutePosition();
  11877. }
  11878. return this.target;
  11879. };
  11880. // Synchronized
  11881. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11882. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11883. return false;
  11884. return this._cache.target.equals(this.target)
  11885. && this._cache.alpha === this.alpha
  11886. && this._cache.beta === this.beta
  11887. && this._cache.radius === this.radius
  11888. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11889. };
  11890. // Methods
  11891. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11892. var _this = this;
  11893. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11894. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11895. var previousPinchDistance = 0;
  11896. var pointers = new BABYLON.SmartCollection();
  11897. if (this._attachedElement) {
  11898. return;
  11899. }
  11900. this._attachedElement = element;
  11901. var engine = this.getEngine();
  11902. if (this._onPointerDown === undefined) {
  11903. this._onPointerDown = function (evt) {
  11904. // Manage panning with right click
  11905. _this._isRightClick = evt.button === 2;
  11906. // manage pointers
  11907. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11908. cacheSoloPointer = pointers.item(evt.pointerId);
  11909. if (!noPreventDefault) {
  11910. evt.preventDefault();
  11911. }
  11912. };
  11913. this._onPointerUp = function (evt) {
  11914. cacheSoloPointer = null;
  11915. previousPinchDistance = 0;
  11916. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11917. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11918. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11919. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11920. pointers.empty();
  11921. if (!noPreventDefault) {
  11922. evt.preventDefault();
  11923. }
  11924. };
  11925. this._onContextMenu = function (evt) {
  11926. evt.preventDefault();
  11927. };
  11928. this._onPointerMove = function (evt) {
  11929. if (!noPreventDefault) {
  11930. evt.preventDefault();
  11931. }
  11932. switch (pointers.count) {
  11933. case 1:
  11934. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11935. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11936. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11937. }
  11938. else {
  11939. var offsetX = evt.clientX - cacheSoloPointer.x;
  11940. var offsetY = evt.clientY - cacheSoloPointer.y;
  11941. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11942. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11943. }
  11944. cacheSoloPointer.x = evt.clientX;
  11945. cacheSoloPointer.y = evt.clientY;
  11946. break;
  11947. case 2:
  11948. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11949. pointers.item(evt.pointerId).x = evt.clientX;
  11950. pointers.item(evt.pointerId).y = evt.clientY;
  11951. var direction = _this.pinchInwards ? 1 : -1;
  11952. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11953. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11954. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11955. if (previousPinchDistance === 0) {
  11956. previousPinchDistance = pinchSquaredDistance;
  11957. return;
  11958. }
  11959. if (pinchSquaredDistance !== previousPinchDistance) {
  11960. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11961. previousPinchDistance = pinchSquaredDistance;
  11962. }
  11963. break;
  11964. default:
  11965. if (pointers.item(evt.pointerId)) {
  11966. pointers.item(evt.pointerId).x = evt.clientX;
  11967. pointers.item(evt.pointerId).y = evt.clientY;
  11968. }
  11969. }
  11970. };
  11971. this._onMouseMove = function (evt) {
  11972. if (!engine.isPointerLock) {
  11973. return;
  11974. }
  11975. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11976. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11977. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11978. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11979. if (!noPreventDefault) {
  11980. evt.preventDefault();
  11981. }
  11982. };
  11983. this._wheel = function (event) {
  11984. var delta = 0;
  11985. if (event.wheelDelta) {
  11986. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11987. }
  11988. else if (event.detail) {
  11989. delta = -event.detail / _this.wheelPrecision;
  11990. }
  11991. if (delta)
  11992. _this.inertialRadiusOffset += delta;
  11993. if (event.preventDefault) {
  11994. if (!noPreventDefault) {
  11995. event.preventDefault();
  11996. }
  11997. }
  11998. };
  11999. this._onKeyDown = function (evt) {
  12000. _this._isCtrlPushed = evt.ctrlKey;
  12001. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12002. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12003. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12004. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12005. var index = _this._keys.indexOf(evt.keyCode);
  12006. if (index === -1) {
  12007. _this._keys.push(evt.keyCode);
  12008. }
  12009. if (evt.preventDefault) {
  12010. if (!noPreventDefault) {
  12011. evt.preventDefault();
  12012. }
  12013. }
  12014. }
  12015. };
  12016. this._onKeyUp = function (evt) {
  12017. _this._isCtrlPushed = evt.ctrlKey;
  12018. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12019. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12020. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12021. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12022. var index = _this._keys.indexOf(evt.keyCode);
  12023. if (index >= 0) {
  12024. _this._keys.splice(index, 1);
  12025. }
  12026. if (evt.preventDefault) {
  12027. if (!noPreventDefault) {
  12028. evt.preventDefault();
  12029. }
  12030. }
  12031. }
  12032. };
  12033. this._onLostFocus = function () {
  12034. _this._keys = [];
  12035. pointers.empty();
  12036. previousPinchDistance = 0;
  12037. cacheSoloPointer = null;
  12038. };
  12039. this._onGestureStart = function (e) {
  12040. if (window.MSGesture === undefined) {
  12041. return;
  12042. }
  12043. if (!_this._MSGestureHandler) {
  12044. _this._MSGestureHandler = new MSGesture();
  12045. _this._MSGestureHandler.target = element;
  12046. }
  12047. _this._MSGestureHandler.addPointer(e.pointerId);
  12048. };
  12049. this._onGesture = function (e) {
  12050. _this.radius *= e.scale;
  12051. if (e.preventDefault) {
  12052. if (!noPreventDefault) {
  12053. e.stopPropagation();
  12054. e.preventDefault();
  12055. }
  12056. }
  12057. };
  12058. this._reset = function () {
  12059. _this._keys = [];
  12060. _this.inertialAlphaOffset = 0;
  12061. _this.inertialBetaOffset = 0;
  12062. _this.inertialRadiusOffset = 0;
  12063. pointers.empty();
  12064. previousPinchDistance = 0;
  12065. cacheSoloPointer = null;
  12066. };
  12067. }
  12068. if (!useCtrlForPanning) {
  12069. element.addEventListener("contextmenu", this._onContextMenu, false);
  12070. }
  12071. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12072. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12073. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12074. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12075. element.addEventListener("mousemove", this._onMouseMove, false);
  12076. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12077. element.addEventListener("MSGestureChange", this._onGesture, false);
  12078. element.addEventListener('mousewheel', this._wheel, false);
  12079. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12080. BABYLON.Tools.RegisterTopRootEvents([
  12081. { name: "keydown", handler: this._onKeyDown },
  12082. { name: "keyup", handler: this._onKeyUp },
  12083. { name: "blur", handler: this._onLostFocus }
  12084. ]);
  12085. };
  12086. ArcRotateCamera.prototype.detachControl = function (element) {
  12087. if (this._attachedElement !== element) {
  12088. return;
  12089. }
  12090. element.removeEventListener("contextmenu", this._onContextMenu);
  12091. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12092. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12093. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12094. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12095. element.removeEventListener("mousemove", this._onMouseMove);
  12096. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12097. element.removeEventListener("MSGestureChange", this._onGesture);
  12098. element.removeEventListener('mousewheel', this._wheel);
  12099. element.removeEventListener('DOMMouseScroll', this._wheel);
  12100. BABYLON.Tools.UnregisterTopRootEvents([
  12101. { name: "keydown", handler: this._onKeyDown },
  12102. { name: "keyup", handler: this._onKeyUp },
  12103. { name: "blur", handler: this._onLostFocus }
  12104. ]);
  12105. this._MSGestureHandler = null;
  12106. this._attachedElement = null;
  12107. if (this._reset) {
  12108. this._reset();
  12109. }
  12110. };
  12111. ArcRotateCamera.prototype._checkInputs = function () {
  12112. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12113. if (this._collisionTriggered) {
  12114. return;
  12115. }
  12116. // Keyboard
  12117. for (var index = 0; index < this._keys.length; index++) {
  12118. var keyCode = this._keys[index];
  12119. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12120. this.inertialAlphaOffset -= 0.01;
  12121. }
  12122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12123. this.inertialBetaOffset -= 0.01;
  12124. }
  12125. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12126. this.inertialAlphaOffset += 0.01;
  12127. }
  12128. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12129. this.inertialBetaOffset += 0.01;
  12130. }
  12131. }
  12132. // Inertia
  12133. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12134. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12135. this.beta += this.inertialBetaOffset;
  12136. this.radius -= this.inertialRadiusOffset;
  12137. this.inertialAlphaOffset *= this.inertia;
  12138. this.inertialBetaOffset *= this.inertia;
  12139. this.inertialRadiusOffset *= this.inertia;
  12140. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12141. this.inertialAlphaOffset = 0;
  12142. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12143. this.inertialBetaOffset = 0;
  12144. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12145. this.inertialRadiusOffset = 0;
  12146. }
  12147. // Panning inertia
  12148. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12149. if (!this._localDirection) {
  12150. this._localDirection = BABYLON.Vector3.Zero();
  12151. this._transformedDirection = BABYLON.Vector3.Zero();
  12152. }
  12153. this.inertialPanningX *= this.inertia;
  12154. this.inertialPanningY *= this.inertia;
  12155. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12156. this.inertialPanningX = 0;
  12157. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12158. this.inertialPanningY = 0;
  12159. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12160. this._localDirection.multiplyInPlace(this.panningAxis);
  12161. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12162. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12163. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12164. if (!this.panningAxis.y) {
  12165. this._transformedDirection.y = 0;
  12166. }
  12167. this.target.addInPlace(this._transformedDirection);
  12168. }
  12169. // Limits
  12170. this._checkLimits();
  12171. _super.prototype._checkInputs.call(this);
  12172. };
  12173. ArcRotateCamera.prototype._checkLimits = function () {
  12174. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12175. if (this.allowUpsideDown && this.beta > Math.PI) {
  12176. this.beta = this.beta - (2 * Math.PI);
  12177. }
  12178. }
  12179. else {
  12180. if (this.beta < this.lowerBetaLimit) {
  12181. this.beta = this.lowerBetaLimit;
  12182. }
  12183. }
  12184. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12185. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12186. this.beta = this.beta + (2 * Math.PI);
  12187. }
  12188. }
  12189. else {
  12190. if (this.beta > this.upperBetaLimit) {
  12191. this.beta = this.upperBetaLimit;
  12192. }
  12193. }
  12194. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12195. this.alpha = this.lowerAlphaLimit;
  12196. }
  12197. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12198. this.alpha = this.upperAlphaLimit;
  12199. }
  12200. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12201. this.radius = this.lowerRadiusLimit;
  12202. }
  12203. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12204. this.radius = this.upperRadiusLimit;
  12205. }
  12206. };
  12207. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12208. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12209. this.radius = radiusv3.length();
  12210. // Alpha
  12211. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12212. if (radiusv3.z < 0) {
  12213. this.alpha = 2 * Math.PI - this.alpha;
  12214. }
  12215. // Beta
  12216. this.beta = Math.acos(radiusv3.y / this.radius);
  12217. this._checkLimits();
  12218. };
  12219. ArcRotateCamera.prototype.setPosition = function (position) {
  12220. if (this.position.equals(position)) {
  12221. return;
  12222. }
  12223. this.position = position;
  12224. this.rebuildAnglesAndRadius();
  12225. };
  12226. ArcRotateCamera.prototype.setTarget = function (target) {
  12227. if (this._getTargetPosition().equals(target)) {
  12228. return;
  12229. }
  12230. this.target = target;
  12231. this.rebuildAnglesAndRadius();
  12232. };
  12233. ArcRotateCamera.prototype._getViewMatrix = function () {
  12234. // Compute
  12235. var cosa = Math.cos(this.alpha);
  12236. var sina = Math.sin(this.alpha);
  12237. var cosb = Math.cos(this.beta);
  12238. var sinb = Math.sin(this.beta);
  12239. if (sinb === 0) {
  12240. sinb = 0.0001;
  12241. }
  12242. var target = this._getTargetPosition();
  12243. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12244. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12245. this._collider.radius = this.collisionRadius;
  12246. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12247. this._collisionTriggered = true;
  12248. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12249. }
  12250. else {
  12251. this.position.copyFrom(this._newPosition);
  12252. var up = this.upVector;
  12253. if (this.allowUpsideDown && this.beta < 0) {
  12254. up = up.clone();
  12255. up = up.negate();
  12256. }
  12257. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12258. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12259. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12260. }
  12261. return this._viewMatrix;
  12262. };
  12263. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12264. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12265. meshes = meshes || this.getScene().meshes;
  12266. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12267. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12268. this.radius = distance * this.zoomOnFactor;
  12269. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12270. };
  12271. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12272. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12273. var meshesOrMinMaxVector;
  12274. var distance;
  12275. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12276. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12277. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12278. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12279. }
  12280. else {
  12281. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12282. distance = meshesOrMinMaxVectorAndDistance.distance;
  12283. }
  12284. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12285. if (!doNotUpdateMaxZ) {
  12286. this.maxZ = distance * 2;
  12287. }
  12288. };
  12289. /**
  12290. * @override
  12291. * Override Camera.createRigCamera
  12292. */
  12293. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12294. switch (this.cameraRigMode) {
  12295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12298. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12299. case BABYLON.Camera.RIG_MODE_VR:
  12300. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12301. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12302. }
  12303. return null;
  12304. };
  12305. /**
  12306. * @override
  12307. * Override Camera._updateRigCameras
  12308. */
  12309. ArcRotateCamera.prototype._updateRigCameras = function () {
  12310. switch (this.cameraRigMode) {
  12311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12315. case BABYLON.Camera.RIG_MODE_VR:
  12316. var camLeft = this._rigCameras[0];
  12317. var camRight = this._rigCameras[1];
  12318. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12319. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12320. camLeft.beta = camRight.beta = this.beta;
  12321. camLeft.radius = camRight.radius = this.radius;
  12322. break;
  12323. }
  12324. _super.prototype._updateRigCameras.call(this);
  12325. };
  12326. ArcRotateCamera.prototype.getTypeName = function () {
  12327. return "ArcRotateCamera";
  12328. };
  12329. __decorate([
  12330. BABYLON.serialize()
  12331. ], ArcRotateCamera.prototype, "alpha", void 0);
  12332. __decorate([
  12333. BABYLON.serialize()
  12334. ], ArcRotateCamera.prototype, "beta", void 0);
  12335. __decorate([
  12336. BABYLON.serialize()
  12337. ], ArcRotateCamera.prototype, "radius", void 0);
  12338. __decorate([
  12339. BABYLON.serializeAsVector3()
  12340. ], ArcRotateCamera.prototype, "target", void 0);
  12341. __decorate([
  12342. BABYLON.serialize()
  12343. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12356. __decorate([
  12357. BABYLON.serialize()
  12358. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12359. __decorate([
  12360. BABYLON.serialize()
  12361. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12362. __decorate([
  12363. BABYLON.serialize()
  12364. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12368. __decorate([
  12369. BABYLON.serialize()
  12370. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12371. __decorate([
  12372. BABYLON.serialize()
  12373. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12374. __decorate([
  12375. BABYLON.serialize()
  12376. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12377. __decorate([
  12378. BABYLON.serialize()
  12379. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12380. __decorate([
  12381. BABYLON.serialize()
  12382. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12383. __decorate([
  12384. BABYLON.serialize()
  12385. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12386. __decorate([
  12387. BABYLON.serialize()
  12388. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12389. __decorate([
  12390. BABYLON.serialize()
  12391. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12392. __decorate([
  12393. BABYLON.serialize()
  12394. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12395. __decorate([
  12396. BABYLON.serialize()
  12397. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12398. __decorate([
  12399. BABYLON.serialize()
  12400. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12401. __decorate([
  12402. BABYLON.serialize()
  12403. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12404. __decorate([
  12405. BABYLON.serialize()
  12406. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12407. return ArcRotateCamera;
  12408. })(BABYLON.TargetCamera);
  12409. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12410. })(BABYLON || (BABYLON = {}));
  12411. var BABYLON;
  12412. (function (BABYLON) {
  12413. var RenderingManager = (function () {
  12414. function RenderingManager(scene) {
  12415. this._renderingGroups = new Array();
  12416. this._scene = scene;
  12417. }
  12418. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12419. if (this._scene._activeParticleSystems.length === 0) {
  12420. return;
  12421. }
  12422. // Particles
  12423. var activeCamera = this._scene.activeCamera;
  12424. var beforeParticlesDate = BABYLON.Tools.Now;
  12425. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12426. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12427. if (particleSystem.renderingGroupId !== index) {
  12428. continue;
  12429. }
  12430. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12431. continue;
  12432. }
  12433. this._clearDepthBuffer();
  12434. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12435. this._scene._activeParticles += particleSystem.render();
  12436. }
  12437. }
  12438. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12439. };
  12440. RenderingManager.prototype._renderSprites = function (index) {
  12441. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12442. return;
  12443. }
  12444. // Sprites
  12445. var activeCamera = this._scene.activeCamera;
  12446. var beforeSpritessDate = BABYLON.Tools.Now;
  12447. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12448. var spriteManager = this._scene.spriteManagers[id];
  12449. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12450. this._clearDepthBuffer();
  12451. spriteManager.render();
  12452. }
  12453. }
  12454. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12455. };
  12456. RenderingManager.prototype._clearDepthBuffer = function () {
  12457. if (this._depthBufferAlreadyCleaned) {
  12458. return;
  12459. }
  12460. this._scene.getEngine().clear(0, false, true);
  12461. this._depthBufferAlreadyCleaned = true;
  12462. };
  12463. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12464. if (this._currentRenderSprites) {
  12465. this._renderSprites(this._currentIndex);
  12466. }
  12467. if (this._currentRenderParticles) {
  12468. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12469. }
  12470. };
  12471. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12472. this._currentActiveMeshes = activeMeshes;
  12473. this._currentRenderParticles = renderParticles;
  12474. this._currentRenderSprites = renderSprites;
  12475. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12476. this._depthBufferAlreadyCleaned = index == 0;
  12477. var renderingGroup = this._renderingGroups[index];
  12478. var needToStepBack = false;
  12479. this._currentIndex = index;
  12480. if (renderingGroup) {
  12481. this._clearDepthBuffer();
  12482. if (!renderingGroup.onBeforeTransparentRendering) {
  12483. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12484. }
  12485. if (!renderingGroup.render(customRenderFunction)) {
  12486. this._renderingGroups.splice(index, 1);
  12487. needToStepBack = true;
  12488. this._renderSpritesAndParticles();
  12489. }
  12490. }
  12491. else {
  12492. this._renderSpritesAndParticles();
  12493. }
  12494. if (needToStepBack) {
  12495. index--;
  12496. }
  12497. }
  12498. };
  12499. RenderingManager.prototype.reset = function () {
  12500. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12501. if (renderingGroup) {
  12502. renderingGroup.prepare();
  12503. }
  12504. });
  12505. };
  12506. RenderingManager.prototype.dispatch = function (subMesh) {
  12507. var mesh = subMesh.getMesh();
  12508. var renderingGroupId = mesh.renderingGroupId || 0;
  12509. if (!this._renderingGroups[renderingGroupId]) {
  12510. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12511. }
  12512. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12513. };
  12514. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12515. return RenderingManager;
  12516. })();
  12517. BABYLON.RenderingManager = RenderingManager;
  12518. })(BABYLON || (BABYLON = {}));
  12519. var BABYLON;
  12520. (function (BABYLON) {
  12521. var RenderingGroup = (function () {
  12522. function RenderingGroup(index, scene) {
  12523. this.index = index;
  12524. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12525. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12526. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12527. this._scene = scene;
  12528. }
  12529. RenderingGroup.prototype.render = function (customRenderFunction) {
  12530. if (customRenderFunction) {
  12531. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12532. return true;
  12533. }
  12534. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12535. if (this.onBeforeTransparentRendering) {
  12536. this.onBeforeTransparentRendering();
  12537. }
  12538. return false;
  12539. }
  12540. var engine = this._scene.getEngine();
  12541. // Opaque
  12542. var subIndex;
  12543. var submesh;
  12544. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12545. submesh = this._opaqueSubMeshes.data[subIndex];
  12546. submesh.render(false);
  12547. }
  12548. // Alpha test
  12549. engine.setAlphaTesting(true);
  12550. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12551. submesh = this._alphaTestSubMeshes.data[subIndex];
  12552. submesh.render(false);
  12553. }
  12554. engine.setAlphaTesting(false);
  12555. if (this.onBeforeTransparentRendering) {
  12556. this.onBeforeTransparentRendering();
  12557. }
  12558. // Transparent
  12559. if (this._transparentSubMeshes.length) {
  12560. // Sorting
  12561. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12562. submesh = this._transparentSubMeshes.data[subIndex];
  12563. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12564. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12565. }
  12566. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12567. sortedArray.sort(function (a, b) {
  12568. // Alpha index first
  12569. if (a._alphaIndex > b._alphaIndex) {
  12570. return 1;
  12571. }
  12572. if (a._alphaIndex < b._alphaIndex) {
  12573. return -1;
  12574. }
  12575. // Then distance to camera
  12576. if (a._distanceToCamera < b._distanceToCamera) {
  12577. return 1;
  12578. }
  12579. if (a._distanceToCamera > b._distanceToCamera) {
  12580. return -1;
  12581. }
  12582. return 0;
  12583. });
  12584. // Rendering
  12585. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12586. submesh = sortedArray[subIndex];
  12587. submesh.render(true);
  12588. }
  12589. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12590. }
  12591. return true;
  12592. };
  12593. RenderingGroup.prototype.prepare = function () {
  12594. this._opaqueSubMeshes.reset();
  12595. this._transparentSubMeshes.reset();
  12596. this._alphaTestSubMeshes.reset();
  12597. };
  12598. RenderingGroup.prototype.dispatch = function (subMesh) {
  12599. var material = subMesh.getMaterial();
  12600. var mesh = subMesh.getMesh();
  12601. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12602. this._transparentSubMeshes.push(subMesh);
  12603. }
  12604. else if (material.needAlphaTesting()) {
  12605. this._alphaTestSubMeshes.push(subMesh);
  12606. }
  12607. else {
  12608. this._opaqueSubMeshes.push(subMesh); // Opaque
  12609. }
  12610. };
  12611. return RenderingGroup;
  12612. })();
  12613. BABYLON.RenderingGroup = RenderingGroup;
  12614. })(BABYLON || (BABYLON = {}));
  12615. var BABYLON;
  12616. (function (BABYLON) {
  12617. /**
  12618. * Represents a scene to be rendered by the engine.
  12619. * @see http://doc.babylonjs.com/page.php?p=21911
  12620. */
  12621. var Scene = (function () {
  12622. /**
  12623. * @constructor
  12624. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12625. */
  12626. function Scene(engine) {
  12627. // Members
  12628. this.autoClear = true;
  12629. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12630. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12631. this.forceWireframe = false;
  12632. this.forcePointsCloud = false;
  12633. this.forceShowBoundingBoxes = false;
  12634. this.animationsEnabled = true;
  12635. this.constantlyUpdateMeshUnderPointer = false;
  12636. // Animations
  12637. this.animations = [];
  12638. 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
  12639. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12640. this._startingPointerTime = 0;
  12641. // Fog
  12642. /**
  12643. * is fog enabled on this scene.
  12644. * @type {boolean}
  12645. */
  12646. this.fogEnabled = true;
  12647. this.fogMode = Scene.FOGMODE_NONE;
  12648. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12649. this.fogDensity = 0.1;
  12650. this.fogStart = 0;
  12651. this.fogEnd = 1000.0;
  12652. // Lights
  12653. /**
  12654. * is shadow enabled on this scene.
  12655. * @type {boolean}
  12656. */
  12657. this.shadowsEnabled = true;
  12658. /**
  12659. * is light enabled on this scene.
  12660. * @type {boolean}
  12661. */
  12662. this.lightsEnabled = true;
  12663. /**
  12664. * All of the lights added to this scene.
  12665. * @see BABYLON.Light
  12666. * @type {BABYLON.Light[]}
  12667. */
  12668. this.lights = new Array();
  12669. // Cameras
  12670. /**
  12671. * All of the cameras added to this scene.
  12672. * @see BABYLON.Camera
  12673. * @type {BABYLON.Camera[]}
  12674. */
  12675. this.cameras = new Array();
  12676. this.activeCameras = new Array();
  12677. // Meshes
  12678. /**
  12679. * All of the (abstract) meshes added to this scene.
  12680. * @see BABYLON.AbstractMesh
  12681. * @type {BABYLON.AbstractMesh[]}
  12682. */
  12683. this.meshes = new Array();
  12684. // Geometries
  12685. this._geometries = new Array();
  12686. this.materials = new Array();
  12687. this.multiMaterials = new Array();
  12688. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12689. // Textures
  12690. this.texturesEnabled = true;
  12691. this.textures = new Array();
  12692. // Particles
  12693. this.particlesEnabled = true;
  12694. this.particleSystems = new Array();
  12695. // Sprites
  12696. this.spritesEnabled = true;
  12697. this.spriteManagers = new Array();
  12698. // Layers
  12699. this.layers = new Array();
  12700. // Skeletons
  12701. this.skeletonsEnabled = true;
  12702. this.skeletons = new Array();
  12703. // Lens flares
  12704. this.lensFlaresEnabled = true;
  12705. this.lensFlareSystems = new Array();
  12706. // Collisions
  12707. this.collisionsEnabled = true;
  12708. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12709. // Postprocesses
  12710. this.postProcessesEnabled = true;
  12711. // Customs render targets
  12712. this.renderTargetsEnabled = true;
  12713. this.dumpNextRenderTargets = false;
  12714. this.customRenderTargets = new Array();
  12715. // Imported meshes
  12716. this.importedMeshesFiles = new Array();
  12717. // Probes
  12718. this.probesEnabled = true;
  12719. this.reflectionProbes = new Array();
  12720. this._actionManagers = new Array();
  12721. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12722. // Procedural textures
  12723. this.proceduralTexturesEnabled = true;
  12724. this._proceduralTextures = new Array();
  12725. this.soundTracks = new Array();
  12726. this._audioEnabled = true;
  12727. this._headphone = false;
  12728. this._totalVertices = 0;
  12729. this._activeIndices = 0;
  12730. this._activeParticles = 0;
  12731. this._lastFrameDuration = 0;
  12732. this._evaluateActiveMeshesDuration = 0;
  12733. this._renderTargetsDuration = 0;
  12734. this._particlesDuration = 0;
  12735. this._renderDuration = 0;
  12736. this._spritesDuration = 0;
  12737. this._animationRatio = 0;
  12738. this._renderId = 0;
  12739. this._executeWhenReadyTimeoutId = -1;
  12740. this._toBeDisposed = new BABYLON.SmartArray(256);
  12741. this._onReadyCallbacks = new Array();
  12742. this._pendingData = []; //ANY
  12743. this._onBeforeRenderCallbacks = new Array();
  12744. this._onAfterRenderCallbacks = new Array();
  12745. this._activeMeshes = new BABYLON.SmartArray(256);
  12746. this._processedMaterials = new BABYLON.SmartArray(256);
  12747. this._renderTargets = new BABYLON.SmartArray(256);
  12748. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12749. this._activeSkeletons = new BABYLON.SmartArray(32);
  12750. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12751. this._activeBones = 0;
  12752. this._activeAnimatables = new Array();
  12753. this._transformMatrix = BABYLON.Matrix.Zero();
  12754. this._edgesRenderers = new BABYLON.SmartArray(16);
  12755. this._uniqueIdCounter = 0;
  12756. this._engine = engine;
  12757. engine.scenes.push(this);
  12758. this._renderingManager = new BABYLON.RenderingManager(this);
  12759. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12760. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12761. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12762. if (BABYLON.OutlineRenderer) {
  12763. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12764. }
  12765. this.attachControl();
  12766. this._debugLayer = new BABYLON.DebugLayer(this);
  12767. if (BABYLON.SoundTrack) {
  12768. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12769. }
  12770. //simplification queue
  12771. if (BABYLON.SimplificationQueue) {
  12772. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12773. }
  12774. //collision coordinator initialization. For now legacy per default.
  12775. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12776. }
  12777. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12778. get: function () {
  12779. return Scene._FOGMODE_NONE;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12785. get: function () {
  12786. return Scene._FOGMODE_EXP;
  12787. },
  12788. enumerable: true,
  12789. configurable: true
  12790. });
  12791. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12792. get: function () {
  12793. return Scene._FOGMODE_EXP2;
  12794. },
  12795. enumerable: true,
  12796. configurable: true
  12797. });
  12798. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12799. get: function () {
  12800. return Scene._FOGMODE_LINEAR;
  12801. },
  12802. enumerable: true,
  12803. configurable: true
  12804. });
  12805. Object.defineProperty(Scene.prototype, "debugLayer", {
  12806. // Properties
  12807. get: function () {
  12808. return this._debugLayer;
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12814. get: function () {
  12815. return this._workerCollisions;
  12816. },
  12817. set: function (enabled) {
  12818. enabled = (enabled && !!Worker);
  12819. this._workerCollisions = enabled;
  12820. if (this.collisionCoordinator) {
  12821. this.collisionCoordinator.destroy();
  12822. }
  12823. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12824. this.collisionCoordinator.init(this);
  12825. },
  12826. enumerable: true,
  12827. configurable: true
  12828. });
  12829. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12830. get: function () {
  12831. return this._selectionOctree;
  12832. },
  12833. enumerable: true,
  12834. configurable: true
  12835. });
  12836. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12837. /**
  12838. * The mesh that is currently under the pointer.
  12839. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12840. */
  12841. get: function () {
  12842. return this._pointerOverMesh;
  12843. },
  12844. enumerable: true,
  12845. configurable: true
  12846. });
  12847. Object.defineProperty(Scene.prototype, "pointerX", {
  12848. /**
  12849. * Current on-screen X position of the pointer
  12850. * @return {number} X position of the pointer
  12851. */
  12852. get: function () {
  12853. return this._pointerX;
  12854. },
  12855. enumerable: true,
  12856. configurable: true
  12857. });
  12858. Object.defineProperty(Scene.prototype, "pointerY", {
  12859. /**
  12860. * Current on-screen Y position of the pointer
  12861. * @return {number} Y position of the pointer
  12862. */
  12863. get: function () {
  12864. return this._pointerY;
  12865. },
  12866. enumerable: true,
  12867. configurable: true
  12868. });
  12869. Scene.prototype.getCachedMaterial = function () {
  12870. return this._cachedMaterial;
  12871. };
  12872. Scene.prototype.getBoundingBoxRenderer = function () {
  12873. return this._boundingBoxRenderer;
  12874. };
  12875. Scene.prototype.getOutlineRenderer = function () {
  12876. return this._outlineRenderer;
  12877. };
  12878. Scene.prototype.getEngine = function () {
  12879. return this._engine;
  12880. };
  12881. Scene.prototype.getTotalVertices = function () {
  12882. return this._totalVertices;
  12883. };
  12884. Scene.prototype.getActiveIndices = function () {
  12885. return this._activeIndices;
  12886. };
  12887. Scene.prototype.getActiveParticles = function () {
  12888. return this._activeParticles;
  12889. };
  12890. Scene.prototype.getActiveBones = function () {
  12891. return this._activeBones;
  12892. };
  12893. // Stats
  12894. Scene.prototype.getLastFrameDuration = function () {
  12895. return this._lastFrameDuration;
  12896. };
  12897. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12898. return this._evaluateActiveMeshesDuration;
  12899. };
  12900. Scene.prototype.getActiveMeshes = function () {
  12901. return this._activeMeshes;
  12902. };
  12903. Scene.prototype.getRenderTargetsDuration = function () {
  12904. return this._renderTargetsDuration;
  12905. };
  12906. Scene.prototype.getRenderDuration = function () {
  12907. return this._renderDuration;
  12908. };
  12909. Scene.prototype.getParticlesDuration = function () {
  12910. return this._particlesDuration;
  12911. };
  12912. Scene.prototype.getSpritesDuration = function () {
  12913. return this._spritesDuration;
  12914. };
  12915. Scene.prototype.getAnimationRatio = function () {
  12916. return this._animationRatio;
  12917. };
  12918. Scene.prototype.getRenderId = function () {
  12919. return this._renderId;
  12920. };
  12921. Scene.prototype.incrementRenderId = function () {
  12922. this._renderId++;
  12923. };
  12924. Scene.prototype._updatePointerPosition = function (evt) {
  12925. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12926. this._pointerX = evt.clientX - canvasRect.left;
  12927. this._pointerY = evt.clientY - canvasRect.top;
  12928. this._unTranslatedPointerX = this._pointerX;
  12929. this._unTranslatedPointerY = this._pointerY;
  12930. if (this.cameraToUseForPointers) {
  12931. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12932. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12933. }
  12934. };
  12935. // Pointers handling
  12936. Scene.prototype.attachControl = function () {
  12937. var _this = this;
  12938. var spritePredicate = function (sprite) {
  12939. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12940. };
  12941. this._onPointerMove = function (evt) {
  12942. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12943. return;
  12944. }
  12945. var canvas = _this._engine.getRenderingCanvas();
  12946. _this._updatePointerPosition(evt);
  12947. if (!_this.pointerMovePredicate) {
  12948. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  12949. }
  12950. // Meshes
  12951. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  12952. if (pickResult.hit && pickResult.pickedMesh) {
  12953. _this.setPointerOverSprite(null);
  12954. _this.setPointerOverMesh(pickResult.pickedMesh);
  12955. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12956. canvas.style.cursor = "pointer";
  12957. }
  12958. else {
  12959. canvas.style.cursor = "";
  12960. }
  12961. }
  12962. else {
  12963. _this.setPointerOverMesh(null);
  12964. // Sprites
  12965. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12966. if (pickResult.hit && pickResult.pickedSprite) {
  12967. canvas.style.cursor = "pointer";
  12968. _this.setPointerOverSprite(pickResult.pickedSprite);
  12969. }
  12970. else {
  12971. _this.setPointerOverSprite(null);
  12972. // Restore pointer
  12973. canvas.style.cursor = "";
  12974. }
  12975. }
  12976. if (_this.onPointerMove) {
  12977. _this.onPointerMove(evt, pickResult);
  12978. }
  12979. };
  12980. this._onPointerDown = function (evt) {
  12981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12982. return;
  12983. }
  12984. _this._updatePointerPosition(evt);
  12985. _this._startingPointerPosition.x = _this._pointerX;
  12986. _this._startingPointerPosition.y = _this._pointerY;
  12987. _this._startingPointerTime = new Date().getTime();
  12988. if (!_this.pointerDownPredicate) {
  12989. _this.pointerDownPredicate = function (mesh) {
  12990. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12991. };
  12992. }
  12993. // Meshes
  12994. _this._pickedDownMesh = null;
  12995. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  12996. if (pickResult.hit && pickResult.pickedMesh) {
  12997. if (pickResult.pickedMesh.actionManager) {
  12998. _this._pickedDownMesh = pickResult.pickedMesh;
  12999. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13000. switch (evt.button) {
  13001. case 0:
  13002. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13003. break;
  13004. case 1:
  13005. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13006. break;
  13007. case 2:
  13008. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13009. break;
  13010. }
  13011. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13012. }
  13013. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13014. var that = _this;
  13015. window.setTimeout(function () {
  13016. 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);
  13017. if (pickResult.hit && pickResult.pickedMesh) {
  13018. if (pickResult.pickedMesh.actionManager) {
  13019. 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)) {
  13020. that._startingPointerTime = 0;
  13021. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13022. }
  13023. }
  13024. }
  13025. }, BABYLON.ActionManager.LongPressDelay);
  13026. }
  13027. }
  13028. }
  13029. if (_this.onPointerDown) {
  13030. _this.onPointerDown(evt, pickResult);
  13031. }
  13032. // Sprites
  13033. _this._pickedDownSprite = null;
  13034. if (_this.spriteManagers.length > 0) {
  13035. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13036. if (pickResult.hit && pickResult.pickedSprite) {
  13037. if (pickResult.pickedSprite.actionManager) {
  13038. _this._pickedDownSprite = pickResult.pickedSprite;
  13039. switch (evt.button) {
  13040. case 0:
  13041. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13042. break;
  13043. case 1:
  13044. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13045. break;
  13046. case 2:
  13047. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13048. break;
  13049. }
  13050. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13051. }
  13052. }
  13053. }
  13054. };
  13055. this._onPointerUp = function (evt) {
  13056. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13057. return;
  13058. }
  13059. _this._updatePointerPosition(evt);
  13060. if (!_this.pointerUpPredicate) {
  13061. _this.pointerUpPredicate = function (mesh) {
  13062. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  13063. };
  13064. }
  13065. // Meshes
  13066. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13067. if (pickResult.hit && pickResult.pickedMesh) {
  13068. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13069. _this.onPointerPick(evt, pickResult);
  13070. }
  13071. if (pickResult.pickedMesh.actionManager) {
  13072. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13073. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13074. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13075. }
  13076. }
  13077. }
  13078. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13079. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13080. }
  13081. if (_this.onPointerUp) {
  13082. _this.onPointerUp(evt, pickResult);
  13083. }
  13084. _this._startingPointerTime = 0;
  13085. // Sprites
  13086. if (_this.spriteManagers.length > 0) {
  13087. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13088. if (pickResult.hit && pickResult.pickedSprite) {
  13089. if (pickResult.pickedSprite.actionManager) {
  13090. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13091. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13092. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13093. }
  13094. }
  13095. }
  13096. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13097. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13098. }
  13099. }
  13100. };
  13101. this._onKeyDown = function (evt) {
  13102. if (_this.actionManager) {
  13103. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13104. }
  13105. };
  13106. this._onKeyUp = function (evt) {
  13107. if (_this.actionManager) {
  13108. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13109. }
  13110. };
  13111. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13112. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13113. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13114. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13115. // Wheel
  13116. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13117. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13118. BABYLON.Tools.RegisterTopRootEvents([
  13119. { name: "keydown", handler: this._onKeyDown },
  13120. { name: "keyup", handler: this._onKeyUp }
  13121. ]);
  13122. };
  13123. Scene.prototype.detachControl = function () {
  13124. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13125. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13126. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13127. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13128. // Wheel
  13129. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13130. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13131. BABYLON.Tools.UnregisterTopRootEvents([
  13132. { name: "keydown", handler: this._onKeyDown },
  13133. { name: "keyup", handler: this._onKeyUp }
  13134. ]);
  13135. };
  13136. // Ready
  13137. Scene.prototype.isReady = function () {
  13138. if (this._pendingData.length > 0) {
  13139. return false;
  13140. }
  13141. var index;
  13142. for (index = 0; index < this._geometries.length; index++) {
  13143. var geometry = this._geometries[index];
  13144. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13145. return false;
  13146. }
  13147. }
  13148. for (index = 0; index < this.meshes.length; index++) {
  13149. var mesh = this.meshes[index];
  13150. if (!mesh.isReady()) {
  13151. return false;
  13152. }
  13153. var mat = mesh.material;
  13154. if (mat) {
  13155. if (!mat.isReady(mesh)) {
  13156. return false;
  13157. }
  13158. }
  13159. }
  13160. return true;
  13161. };
  13162. Scene.prototype.resetCachedMaterial = function () {
  13163. this._cachedMaterial = null;
  13164. };
  13165. Scene.prototype.registerBeforeRender = function (func) {
  13166. this._onBeforeRenderCallbacks.push(func);
  13167. };
  13168. Scene.prototype.unregisterBeforeRender = function (func) {
  13169. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13170. if (index > -1) {
  13171. this._onBeforeRenderCallbacks.splice(index, 1);
  13172. }
  13173. };
  13174. Scene.prototype.registerAfterRender = function (func) {
  13175. this._onAfterRenderCallbacks.push(func);
  13176. };
  13177. Scene.prototype.unregisterAfterRender = function (func) {
  13178. var index = this._onAfterRenderCallbacks.indexOf(func);
  13179. if (index > -1) {
  13180. this._onAfterRenderCallbacks.splice(index, 1);
  13181. }
  13182. };
  13183. Scene.prototype._addPendingData = function (data) {
  13184. this._pendingData.push(data);
  13185. };
  13186. Scene.prototype._removePendingData = function (data) {
  13187. var index = this._pendingData.indexOf(data);
  13188. if (index !== -1) {
  13189. this._pendingData.splice(index, 1);
  13190. }
  13191. };
  13192. Scene.prototype.getWaitingItemsCount = function () {
  13193. return this._pendingData.length;
  13194. };
  13195. /**
  13196. * Registers a function to be executed when the scene is ready.
  13197. * @param {Function} func - the function to be executed.
  13198. */
  13199. Scene.prototype.executeWhenReady = function (func) {
  13200. var _this = this;
  13201. this._onReadyCallbacks.push(func);
  13202. if (this._executeWhenReadyTimeoutId !== -1) {
  13203. return;
  13204. }
  13205. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13206. _this._checkIsReady();
  13207. }, 150);
  13208. };
  13209. Scene.prototype._checkIsReady = function () {
  13210. var _this = this;
  13211. if (this.isReady()) {
  13212. this._onReadyCallbacks.forEach(function (func) {
  13213. func();
  13214. });
  13215. this._onReadyCallbacks = [];
  13216. this._executeWhenReadyTimeoutId = -1;
  13217. return;
  13218. }
  13219. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13220. _this._checkIsReady();
  13221. }, 150);
  13222. };
  13223. // Animations
  13224. /**
  13225. * Will start the animation sequence of a given target
  13226. * @param target - the target
  13227. * @param {number} from - from which frame should animation start
  13228. * @param {number} to - till which frame should animation run.
  13229. * @param {boolean} [loop] - should the animation loop
  13230. * @param {number} [speedRatio] - the speed in which to run the animation
  13231. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13232. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13233. * @return {BABYLON.Animatable} the animatable object created for this animation
  13234. * @see BABYLON.Animatable
  13235. * @see http://doc.babylonjs.com/page.php?p=22081
  13236. */
  13237. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13238. if (speedRatio === void 0) { speedRatio = 1.0; }
  13239. this.stopAnimation(target);
  13240. if (!animatable) {
  13241. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13242. }
  13243. // Local animations
  13244. if (target.animations) {
  13245. animatable.appendAnimations(target, target.animations);
  13246. }
  13247. // Children animations
  13248. if (target.getAnimatables) {
  13249. var animatables = target.getAnimatables();
  13250. for (var index = 0; index < animatables.length; index++) {
  13251. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13252. }
  13253. }
  13254. animatable.reset();
  13255. return animatable;
  13256. };
  13257. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13258. if (speedRatio === undefined) {
  13259. speedRatio = 1.0;
  13260. }
  13261. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13262. return animatable;
  13263. };
  13264. Scene.prototype.getAnimatableByTarget = function (target) {
  13265. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13266. if (this._activeAnimatables[index].target === target) {
  13267. return this._activeAnimatables[index];
  13268. }
  13269. }
  13270. return null;
  13271. };
  13272. Object.defineProperty(Scene.prototype, "Animatables", {
  13273. get: function () {
  13274. return this._activeAnimatables;
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. /**
  13280. * Will stop the animation of the given target
  13281. * @param target - the target
  13282. * @see beginAnimation
  13283. */
  13284. Scene.prototype.stopAnimation = function (target) {
  13285. var animatable = this.getAnimatableByTarget(target);
  13286. if (animatable) {
  13287. animatable.stop();
  13288. }
  13289. };
  13290. Scene.prototype._animate = function () {
  13291. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13292. return;
  13293. }
  13294. if (!this._animationStartDate) {
  13295. if (this._pendingData.length > 0) {
  13296. return;
  13297. }
  13298. this._animationStartDate = BABYLON.Tools.Now;
  13299. }
  13300. // Getting time
  13301. var now = BABYLON.Tools.Now;
  13302. var delay = now - this._animationStartDate;
  13303. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13304. this._activeAnimatables[index]._animate(delay);
  13305. }
  13306. };
  13307. // Matrix
  13308. Scene.prototype.getViewMatrix = function () {
  13309. return this._viewMatrix;
  13310. };
  13311. Scene.prototype.getProjectionMatrix = function () {
  13312. return this._projectionMatrix;
  13313. };
  13314. Scene.prototype.getTransformMatrix = function () {
  13315. return this._transformMatrix;
  13316. };
  13317. Scene.prototype.setTransformMatrix = function (view, projection) {
  13318. this._viewMatrix = view;
  13319. this._projectionMatrix = projection;
  13320. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13321. };
  13322. // Methods
  13323. Scene.prototype.addMesh = function (newMesh) {
  13324. newMesh.uniqueId = this._uniqueIdCounter++;
  13325. var position = this.meshes.push(newMesh);
  13326. //notify the collision coordinator
  13327. this.collisionCoordinator.onMeshAdded(newMesh);
  13328. if (this.onNewMeshAdded) {
  13329. this.onNewMeshAdded(newMesh, position, this);
  13330. }
  13331. };
  13332. Scene.prototype.removeMesh = function (toRemove) {
  13333. var index = this.meshes.indexOf(toRemove);
  13334. if (index !== -1) {
  13335. // Remove from the scene if mesh found
  13336. this.meshes.splice(index, 1);
  13337. }
  13338. //notify the collision coordinator
  13339. this.collisionCoordinator.onMeshRemoved(toRemove);
  13340. if (this.onMeshRemoved) {
  13341. this.onMeshRemoved(toRemove);
  13342. }
  13343. return index;
  13344. };
  13345. Scene.prototype.removeSkeleton = function (toRemove) {
  13346. var index = this.skeletons.indexOf(toRemove);
  13347. if (index !== -1) {
  13348. // Remove from the scene if mesh found
  13349. this.skeletons.splice(index, 1);
  13350. }
  13351. return index;
  13352. };
  13353. Scene.prototype.removeLight = function (toRemove) {
  13354. var index = this.lights.indexOf(toRemove);
  13355. if (index !== -1) {
  13356. // Remove from the scene if mesh found
  13357. this.lights.splice(index, 1);
  13358. }
  13359. if (this.onLightRemoved) {
  13360. this.onLightRemoved(toRemove);
  13361. }
  13362. return index;
  13363. };
  13364. Scene.prototype.removeCamera = function (toRemove) {
  13365. var index = this.cameras.indexOf(toRemove);
  13366. if (index !== -1) {
  13367. // Remove from the scene if mesh found
  13368. this.cameras.splice(index, 1);
  13369. }
  13370. // Remove from activeCameras
  13371. var index2 = this.activeCameras.indexOf(toRemove);
  13372. if (index2 !== -1) {
  13373. // Remove from the scene if mesh found
  13374. this.activeCameras.splice(index2, 1);
  13375. }
  13376. // Reset the activeCamera
  13377. if (this.activeCamera === toRemove) {
  13378. if (this.cameras.length > 0) {
  13379. this.activeCamera = this.cameras[0];
  13380. }
  13381. else {
  13382. this.activeCamera = null;
  13383. }
  13384. }
  13385. if (this.onCameraRemoved) {
  13386. this.onCameraRemoved(toRemove);
  13387. }
  13388. return index;
  13389. };
  13390. Scene.prototype.addLight = function (newLight) {
  13391. newLight.uniqueId = this._uniqueIdCounter++;
  13392. var position = this.lights.push(newLight);
  13393. if (this.onNewLightAdded) {
  13394. this.onNewLightAdded(newLight, position, this);
  13395. }
  13396. };
  13397. Scene.prototype.addCamera = function (newCamera) {
  13398. newCamera.uniqueId = this._uniqueIdCounter++;
  13399. var position = this.cameras.push(newCamera);
  13400. if (this.onNewCameraAdded) {
  13401. this.onNewCameraAdded(newCamera, position, this);
  13402. }
  13403. };
  13404. /**
  13405. * Switch active camera
  13406. * @param {Camera} newCamera - new active camera
  13407. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13408. */
  13409. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13410. if (attachControl === void 0) { attachControl = true; }
  13411. var canvas = this._engine.getRenderingCanvas();
  13412. this.activeCamera.detachControl(canvas);
  13413. this.activeCamera = newCamera;
  13414. if (attachControl) {
  13415. newCamera.attachControl(canvas);
  13416. }
  13417. };
  13418. /**
  13419. * sets the active camera of the scene using its ID
  13420. * @param {string} id - the camera's ID
  13421. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13422. * @see activeCamera
  13423. */
  13424. Scene.prototype.setActiveCameraByID = function (id) {
  13425. var camera = this.getCameraByID(id);
  13426. if (camera) {
  13427. this.activeCamera = camera;
  13428. return camera;
  13429. }
  13430. return null;
  13431. };
  13432. /**
  13433. * sets the active camera of the scene using its name
  13434. * @param {string} name - the camera's name
  13435. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13436. * @see activeCamera
  13437. */
  13438. Scene.prototype.setActiveCameraByName = function (name) {
  13439. var camera = this.getCameraByName(name);
  13440. if (camera) {
  13441. this.activeCamera = camera;
  13442. return camera;
  13443. }
  13444. return null;
  13445. };
  13446. /**
  13447. * get a material using its id
  13448. * @param {string} the material's ID
  13449. * @return {BABYLON.Material|null} the material or null if none found.
  13450. */
  13451. Scene.prototype.getMaterialByID = function (id) {
  13452. for (var index = 0; index < this.materials.length; index++) {
  13453. if (this.materials[index].id === id) {
  13454. return this.materials[index];
  13455. }
  13456. }
  13457. return null;
  13458. };
  13459. /**
  13460. * get a material using its name
  13461. * @param {string} the material's name
  13462. * @return {BABYLON.Material|null} the material or null if none found.
  13463. */
  13464. Scene.prototype.getMaterialByName = function (name) {
  13465. for (var index = 0; index < this.materials.length; index++) {
  13466. if (this.materials[index].name === name) {
  13467. return this.materials[index];
  13468. }
  13469. }
  13470. return null;
  13471. };
  13472. Scene.prototype.getLensFlareSystemByName = function (name) {
  13473. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13474. if (this.lensFlareSystems[index].name === name) {
  13475. return this.lensFlareSystems[index];
  13476. }
  13477. }
  13478. return null;
  13479. };
  13480. Scene.prototype.getCameraByID = function (id) {
  13481. for (var index = 0; index < this.cameras.length; index++) {
  13482. if (this.cameras[index].id === id) {
  13483. return this.cameras[index];
  13484. }
  13485. }
  13486. return null;
  13487. };
  13488. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13489. for (var index = 0; index < this.cameras.length; index++) {
  13490. if (this.cameras[index].uniqueId === uniqueId) {
  13491. return this.cameras[index];
  13492. }
  13493. }
  13494. return null;
  13495. };
  13496. /**
  13497. * get a camera using its name
  13498. * @param {string} the camera's name
  13499. * @return {BABYLON.Camera|null} the camera or null if none found.
  13500. */
  13501. Scene.prototype.getCameraByName = function (name) {
  13502. for (var index = 0; index < this.cameras.length; index++) {
  13503. if (this.cameras[index].name === name) {
  13504. return this.cameras[index];
  13505. }
  13506. }
  13507. return null;
  13508. };
  13509. /**
  13510. * get a bone using its id
  13511. * @param {string} the bone's id
  13512. * @return {BABYLON.Bone|null} the bone or null if not found
  13513. */
  13514. Scene.prototype.getBoneByID = function (id) {
  13515. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13516. var skeleton = this.skeletons[skeletonIndex];
  13517. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13518. if (skeleton.bones[boneIndex].id === id) {
  13519. return skeleton.bones[boneIndex];
  13520. }
  13521. }
  13522. }
  13523. return null;
  13524. };
  13525. /**
  13526. * get a bone using its id
  13527. * @param {string} the bone's name
  13528. * @return {BABYLON.Bone|null} the bone or null if not found
  13529. */
  13530. Scene.prototype.getBoneByName = function (name) {
  13531. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13532. var skeleton = this.skeletons[skeletonIndex];
  13533. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13534. if (skeleton.bones[boneIndex].name === name) {
  13535. return skeleton.bones[boneIndex];
  13536. }
  13537. }
  13538. }
  13539. return null;
  13540. };
  13541. /**
  13542. * get a light node using its name
  13543. * @param {string} the light's name
  13544. * @return {BABYLON.Light|null} the light or null if none found.
  13545. */
  13546. Scene.prototype.getLightByName = function (name) {
  13547. for (var index = 0; index < this.lights.length; index++) {
  13548. if (this.lights[index].name === name) {
  13549. return this.lights[index];
  13550. }
  13551. }
  13552. return null;
  13553. };
  13554. /**
  13555. * get a light node using its ID
  13556. * @param {string} the light's id
  13557. * @return {BABYLON.Light|null} the light or null if none found.
  13558. */
  13559. Scene.prototype.getLightByID = function (id) {
  13560. for (var index = 0; index < this.lights.length; index++) {
  13561. if (this.lights[index].id === id) {
  13562. return this.lights[index];
  13563. }
  13564. }
  13565. return null;
  13566. };
  13567. /**
  13568. * get a light node using its scene-generated unique ID
  13569. * @param {number} the light's unique id
  13570. * @return {BABYLON.Light|null} the light or null if none found.
  13571. */
  13572. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13573. for (var index = 0; index < this.lights.length; index++) {
  13574. if (this.lights[index].uniqueId === uniqueId) {
  13575. return this.lights[index];
  13576. }
  13577. }
  13578. return null;
  13579. };
  13580. /**
  13581. * get a particle system by id
  13582. * @param id {number} the particle system id
  13583. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13584. */
  13585. Scene.prototype.getParticleSystemByID = function (id) {
  13586. for (var index = 0; index < this.particleSystems.length; index++) {
  13587. if (this.particleSystems[index].id === id) {
  13588. return this.particleSystems[index];
  13589. }
  13590. }
  13591. return null;
  13592. };
  13593. /**
  13594. * get a geometry using its ID
  13595. * @param {string} the geometry's id
  13596. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13597. */
  13598. Scene.prototype.getGeometryByID = function (id) {
  13599. for (var index = 0; index < this._geometries.length; index++) {
  13600. if (this._geometries[index].id === id) {
  13601. return this._geometries[index];
  13602. }
  13603. }
  13604. return null;
  13605. };
  13606. /**
  13607. * add a new geometry to this scene.
  13608. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13609. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13610. * @return {boolean} was the geometry added or not
  13611. */
  13612. Scene.prototype.pushGeometry = function (geometry, force) {
  13613. if (!force && this.getGeometryByID(geometry.id)) {
  13614. return false;
  13615. }
  13616. this._geometries.push(geometry);
  13617. //notify the collision coordinator
  13618. this.collisionCoordinator.onGeometryAdded(geometry);
  13619. if (this.onGeometryAdded) {
  13620. this.onGeometryAdded(geometry);
  13621. }
  13622. return true;
  13623. };
  13624. /**
  13625. * Removes an existing geometry
  13626. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13627. * @return {boolean} was the geometry removed or not
  13628. */
  13629. Scene.prototype.removeGeometry = function (geometry) {
  13630. var index = this._geometries.indexOf(geometry);
  13631. if (index > -1) {
  13632. this._geometries.splice(index, 1);
  13633. //notify the collision coordinator
  13634. this.collisionCoordinator.onGeometryDeleted(geometry);
  13635. if (this.onGeometryRemoved) {
  13636. this.onGeometryRemoved(geometry);
  13637. }
  13638. return true;
  13639. }
  13640. return false;
  13641. };
  13642. Scene.prototype.getGeometries = function () {
  13643. return this._geometries;
  13644. };
  13645. /**
  13646. * Get the first added mesh found of a given ID
  13647. * @param {string} id - the id to search for
  13648. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13649. */
  13650. Scene.prototype.getMeshByID = function (id) {
  13651. for (var index = 0; index < this.meshes.length; index++) {
  13652. if (this.meshes[index].id === id) {
  13653. return this.meshes[index];
  13654. }
  13655. }
  13656. return null;
  13657. };
  13658. /**
  13659. * Get a mesh with its auto-generated unique id
  13660. * @param {number} uniqueId - the unique id to search for
  13661. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13662. */
  13663. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13664. for (var index = 0; index < this.meshes.length; index++) {
  13665. if (this.meshes[index].uniqueId === uniqueId) {
  13666. return this.meshes[index];
  13667. }
  13668. }
  13669. return null;
  13670. };
  13671. /**
  13672. * Get a the last added mesh found of a given ID
  13673. * @param {string} id - the id to search for
  13674. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13675. */
  13676. Scene.prototype.getLastMeshByID = function (id) {
  13677. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13678. if (this.meshes[index].id === id) {
  13679. return this.meshes[index];
  13680. }
  13681. }
  13682. return null;
  13683. };
  13684. /**
  13685. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13686. * @param {string} id - the id to search for
  13687. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13688. */
  13689. Scene.prototype.getLastEntryByID = function (id) {
  13690. var index;
  13691. for (index = this.meshes.length - 1; index >= 0; index--) {
  13692. if (this.meshes[index].id === id) {
  13693. return this.meshes[index];
  13694. }
  13695. }
  13696. for (index = this.cameras.length - 1; index >= 0; index--) {
  13697. if (this.cameras[index].id === id) {
  13698. return this.cameras[index];
  13699. }
  13700. }
  13701. for (index = this.lights.length - 1; index >= 0; index--) {
  13702. if (this.lights[index].id === id) {
  13703. return this.lights[index];
  13704. }
  13705. }
  13706. return null;
  13707. };
  13708. Scene.prototype.getNodeByID = function (id) {
  13709. var mesh = this.getMeshByID(id);
  13710. if (mesh) {
  13711. return mesh;
  13712. }
  13713. var light = this.getLightByID(id);
  13714. if (light) {
  13715. return light;
  13716. }
  13717. var camera = this.getCameraByID(id);
  13718. if (camera) {
  13719. return camera;
  13720. }
  13721. var bone = this.getBoneByID(id);
  13722. return bone;
  13723. };
  13724. Scene.prototype.getNodeByName = function (name) {
  13725. var mesh = this.getMeshByName(name);
  13726. if (mesh) {
  13727. return mesh;
  13728. }
  13729. var light = this.getLightByName(name);
  13730. if (light) {
  13731. return light;
  13732. }
  13733. var camera = this.getCameraByName(name);
  13734. if (camera) {
  13735. return camera;
  13736. }
  13737. var bone = this.getBoneByName(name);
  13738. return bone;
  13739. };
  13740. Scene.prototype.getMeshByName = function (name) {
  13741. for (var index = 0; index < this.meshes.length; index++) {
  13742. if (this.meshes[index].name === name) {
  13743. return this.meshes[index];
  13744. }
  13745. }
  13746. return null;
  13747. };
  13748. Scene.prototype.getSoundByName = function (name) {
  13749. var index;
  13750. if (BABYLON.AudioEngine) {
  13751. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13752. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13753. return this.mainSoundTrack.soundCollection[index];
  13754. }
  13755. }
  13756. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13757. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13758. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13759. return this.soundTracks[sdIndex].soundCollection[index];
  13760. }
  13761. }
  13762. }
  13763. }
  13764. return null;
  13765. };
  13766. Scene.prototype.getLastSkeletonByID = function (id) {
  13767. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13768. if (this.skeletons[index].id === id) {
  13769. return this.skeletons[index];
  13770. }
  13771. }
  13772. return null;
  13773. };
  13774. Scene.prototype.getSkeletonById = function (id) {
  13775. for (var index = 0; index < this.skeletons.length; index++) {
  13776. if (this.skeletons[index].id === id) {
  13777. return this.skeletons[index];
  13778. }
  13779. }
  13780. return null;
  13781. };
  13782. Scene.prototype.getSkeletonByName = function (name) {
  13783. for (var index = 0; index < this.skeletons.length; index++) {
  13784. if (this.skeletons[index].name === name) {
  13785. return this.skeletons[index];
  13786. }
  13787. }
  13788. return null;
  13789. };
  13790. Scene.prototype.isActiveMesh = function (mesh) {
  13791. return (this._activeMeshes.indexOf(mesh) !== -1);
  13792. };
  13793. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13794. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13795. var material = subMesh.getMaterial();
  13796. if (mesh.showSubMeshesBoundingBox) {
  13797. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13798. }
  13799. if (material) {
  13800. // Render targets
  13801. if (material.getRenderTargetTextures) {
  13802. if (this._processedMaterials.indexOf(material) === -1) {
  13803. this._processedMaterials.push(material);
  13804. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13805. }
  13806. }
  13807. // Dispatch
  13808. this._activeIndices += subMesh.indexCount;
  13809. this._renderingManager.dispatch(subMesh);
  13810. }
  13811. }
  13812. };
  13813. Scene.prototype._evaluateActiveMeshes = function () {
  13814. this.activeCamera._activeMeshes.reset();
  13815. this._activeMeshes.reset();
  13816. this._renderingManager.reset();
  13817. this._processedMaterials.reset();
  13818. this._activeParticleSystems.reset();
  13819. this._activeSkeletons.reset();
  13820. this._softwareSkinnedMeshes.reset();
  13821. this._boundingBoxRenderer.reset();
  13822. this._edgesRenderers.reset();
  13823. if (!this._frustumPlanes) {
  13824. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13825. }
  13826. else {
  13827. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13828. }
  13829. // Meshes
  13830. var meshes;
  13831. var len;
  13832. if (this._selectionOctree) {
  13833. var selection = this._selectionOctree.select(this._frustumPlanes);
  13834. meshes = selection.data;
  13835. len = selection.length;
  13836. }
  13837. else {
  13838. len = this.meshes.length;
  13839. meshes = this.meshes;
  13840. }
  13841. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13842. var mesh = meshes[meshIndex];
  13843. if (mesh.isBlocked) {
  13844. continue;
  13845. }
  13846. this._totalVertices += mesh.getTotalVertices();
  13847. if (!mesh.isReady() || !mesh.isEnabled()) {
  13848. continue;
  13849. }
  13850. mesh.computeWorldMatrix();
  13851. // Intersections
  13852. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13853. this._meshesForIntersections.pushNoDuplicate(mesh);
  13854. }
  13855. // Switch to current LOD
  13856. var meshLOD = mesh.getLOD(this.activeCamera);
  13857. if (!meshLOD) {
  13858. continue;
  13859. }
  13860. mesh._preActivate();
  13861. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13862. this._activeMeshes.push(mesh);
  13863. this.activeCamera._activeMeshes.push(mesh);
  13864. mesh._activate(this._renderId);
  13865. this._activeMesh(meshLOD);
  13866. }
  13867. }
  13868. // Particle systems
  13869. var beforeParticlesDate = BABYLON.Tools.Now;
  13870. if (this.particlesEnabled) {
  13871. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13872. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13873. var particleSystem = this.particleSystems[particleIndex];
  13874. if (!particleSystem.isStarted()) {
  13875. continue;
  13876. }
  13877. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13878. this._activeParticleSystems.push(particleSystem);
  13879. particleSystem.animate();
  13880. }
  13881. }
  13882. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13883. }
  13884. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13885. };
  13886. Scene.prototype._activeMesh = function (mesh) {
  13887. if (mesh.skeleton && this.skeletonsEnabled) {
  13888. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13889. if (!mesh.computeBonesUsingShaders) {
  13890. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13891. }
  13892. }
  13893. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13894. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13895. }
  13896. if (mesh._edgesRenderer) {
  13897. this._edgesRenderers.push(mesh._edgesRenderer);
  13898. }
  13899. if (mesh && mesh.subMeshes) {
  13900. // Submeshes Octrees
  13901. var len;
  13902. var subMeshes;
  13903. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13904. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13905. len = intersections.length;
  13906. subMeshes = intersections.data;
  13907. }
  13908. else {
  13909. subMeshes = mesh.subMeshes;
  13910. len = subMeshes.length;
  13911. }
  13912. for (var subIndex = 0; subIndex < len; subIndex++) {
  13913. var subMesh = subMeshes[subIndex];
  13914. this._evaluateSubMesh(subMesh, mesh);
  13915. }
  13916. }
  13917. };
  13918. Scene.prototype.updateTransformMatrix = function (force) {
  13919. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13920. };
  13921. Scene.prototype._renderForCamera = function (camera) {
  13922. var engine = this._engine;
  13923. this.activeCamera = camera;
  13924. if (!this.activeCamera)
  13925. throw new Error("Active camera not set");
  13926. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13927. // Viewport
  13928. engine.setViewport(this.activeCamera.viewport);
  13929. // Camera
  13930. this.resetCachedMaterial();
  13931. this._renderId++;
  13932. this.updateTransformMatrix();
  13933. if (this.beforeCameraRender) {
  13934. this.beforeCameraRender(this.activeCamera);
  13935. }
  13936. // Meshes
  13937. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13938. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13939. this._evaluateActiveMeshes();
  13940. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13941. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13942. // Skeletons
  13943. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13944. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13945. skeleton.prepare();
  13946. }
  13947. // Software skinning
  13948. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13949. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13950. mesh.applySkeleton(mesh.skeleton);
  13951. }
  13952. // Render targets
  13953. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13954. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13955. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13956. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13957. var renderTarget = this._renderTargets.data[renderIndex];
  13958. if (renderTarget._shouldRender()) {
  13959. this._renderId++;
  13960. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13961. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13962. }
  13963. }
  13964. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13965. this._renderId++;
  13966. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13967. }
  13968. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13969. // Prepare Frame
  13970. this.postProcessManager._prepareFrame();
  13971. var beforeRenderDate = BABYLON.Tools.Now;
  13972. // Backgrounds
  13973. var layerIndex;
  13974. var layer;
  13975. if (this.layers.length) {
  13976. engine.setDepthBuffer(false);
  13977. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13978. layer = this.layers[layerIndex];
  13979. if (layer.isBackground) {
  13980. layer.render();
  13981. }
  13982. }
  13983. engine.setDepthBuffer(true);
  13984. }
  13985. // Render
  13986. BABYLON.Tools.StartPerformanceCounter("Main render");
  13987. this._renderingManager.render(null, null, true, true);
  13988. BABYLON.Tools.EndPerformanceCounter("Main render");
  13989. // Bounding boxes
  13990. this._boundingBoxRenderer.render();
  13991. // Edges
  13992. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13993. this._edgesRenderers.data[edgesRendererIndex].render();
  13994. }
  13995. // Lens flares
  13996. if (this.lensFlaresEnabled) {
  13997. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13998. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13999. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  14000. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14001. lensFlareSystem.render();
  14002. }
  14003. }
  14004. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14005. }
  14006. // Foregrounds
  14007. if (this.layers.length) {
  14008. engine.setDepthBuffer(false);
  14009. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14010. layer = this.layers[layerIndex];
  14011. if (!layer.isBackground) {
  14012. layer.render();
  14013. }
  14014. }
  14015. engine.setDepthBuffer(true);
  14016. }
  14017. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14018. // Finalize frame
  14019. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14020. // Update camera
  14021. this.activeCamera._updateFromScene();
  14022. // Reset some special arrays
  14023. this._renderTargets.reset();
  14024. if (this.afterCameraRender) {
  14025. this.afterCameraRender(this.activeCamera);
  14026. }
  14027. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14028. };
  14029. Scene.prototype._processSubCameras = function (camera) {
  14030. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14031. this._renderForCamera(camera);
  14032. return;
  14033. }
  14034. // rig cameras
  14035. for (var index = 0; index < camera._rigCameras.length; index++) {
  14036. this._renderForCamera(camera._rigCameras[index]);
  14037. }
  14038. this.activeCamera = camera;
  14039. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14040. // Update camera
  14041. this.activeCamera._updateFromScene();
  14042. };
  14043. Scene.prototype._checkIntersections = function () {
  14044. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14045. var sourceMesh = this._meshesForIntersections.data[index];
  14046. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14047. var action = sourceMesh.actionManager.actions[actionIndex];
  14048. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14049. var parameters = action.getTriggerParameter();
  14050. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14051. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14052. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14053. if (areIntersecting && currentIntersectionInProgress === -1) {
  14054. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14055. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14056. sourceMesh._intersectionsInProgress.push(otherMesh);
  14057. }
  14058. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14059. sourceMesh._intersectionsInProgress.push(otherMesh);
  14060. }
  14061. }
  14062. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14063. //They intersected, and now they don't.
  14064. //is this trigger an exit trigger? execute an event.
  14065. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14066. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14067. }
  14068. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14069. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14070. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14071. }
  14072. }
  14073. }
  14074. }
  14075. }
  14076. };
  14077. Scene.prototype.render = function () {
  14078. var startDate = BABYLON.Tools.Now;
  14079. this._particlesDuration = 0;
  14080. this._spritesDuration = 0;
  14081. this._activeParticles = 0;
  14082. this._renderDuration = 0;
  14083. this._renderTargetsDuration = 0;
  14084. this._evaluateActiveMeshesDuration = 0;
  14085. this._totalVertices = 0;
  14086. this._activeIndices = 0;
  14087. this._activeBones = 0;
  14088. this.getEngine().resetDrawCalls();
  14089. this._meshesForIntersections.reset();
  14090. this.resetCachedMaterial();
  14091. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14092. // Actions
  14093. if (this.actionManager) {
  14094. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14095. }
  14096. //Simplification Queue
  14097. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14098. this.simplificationQueue.executeNext();
  14099. }
  14100. // Animations
  14101. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14102. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14103. this._animate();
  14104. // Physics
  14105. if (this._physicsEngine) {
  14106. BABYLON.Tools.StartPerformanceCounter("Physics");
  14107. this._physicsEngine._step(deltaTime / 1000.0);
  14108. BABYLON.Tools.EndPerformanceCounter("Physics");
  14109. }
  14110. // Before render
  14111. if (this.beforeRender) {
  14112. this.beforeRender();
  14113. }
  14114. var callbackIndex;
  14115. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14116. this._onBeforeRenderCallbacks[callbackIndex]();
  14117. }
  14118. // Customs render targets
  14119. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14120. var engine = this.getEngine();
  14121. var currentActiveCamera = this.activeCamera;
  14122. if (this.renderTargetsEnabled) {
  14123. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14124. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14125. var renderTarget = this.customRenderTargets[customIndex];
  14126. if (renderTarget._shouldRender()) {
  14127. this._renderId++;
  14128. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14129. if (!this.activeCamera)
  14130. throw new Error("Active camera not set");
  14131. // Viewport
  14132. engine.setViewport(this.activeCamera.viewport);
  14133. // Camera
  14134. this.updateTransformMatrix();
  14135. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14136. }
  14137. }
  14138. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14139. this._renderId++;
  14140. }
  14141. if (this.customRenderTargets.length > 0) {
  14142. engine.restoreDefaultFramebuffer();
  14143. }
  14144. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14145. this.activeCamera = currentActiveCamera;
  14146. // Procedural textures
  14147. if (this.proceduralTexturesEnabled) {
  14148. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14149. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14150. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14151. if (proceduralTexture._shouldRender()) {
  14152. proceduralTexture.render();
  14153. }
  14154. }
  14155. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14156. }
  14157. // Clear
  14158. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14159. // Shadows
  14160. if (this.shadowsEnabled) {
  14161. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14162. var light = this.lights[lightIndex];
  14163. var shadowGenerator = light.getShadowGenerator();
  14164. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14165. this._renderTargets.push(shadowGenerator.getShadowMap());
  14166. }
  14167. }
  14168. }
  14169. // Depth renderer
  14170. if (this._depthRenderer) {
  14171. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14172. }
  14173. // RenderPipeline
  14174. this.postProcessRenderPipelineManager.update();
  14175. // Multi-cameras?
  14176. if (this.activeCameras.length > 0) {
  14177. var currentRenderId = this._renderId;
  14178. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14179. this._renderId = currentRenderId;
  14180. if (cameraIndex > 0) {
  14181. this._engine.clear(0, false, true);
  14182. }
  14183. this._processSubCameras(this.activeCameras[cameraIndex]);
  14184. }
  14185. }
  14186. else {
  14187. if (!this.activeCamera) {
  14188. throw new Error("No camera defined");
  14189. }
  14190. this._processSubCameras(this.activeCamera);
  14191. }
  14192. // Intersection checks
  14193. this._checkIntersections();
  14194. // Update the audio listener attached to the camera
  14195. if (BABYLON.AudioEngine) {
  14196. this._updateAudioParameters();
  14197. }
  14198. // After render
  14199. if (this.afterRender) {
  14200. this.afterRender();
  14201. }
  14202. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14203. this._onAfterRenderCallbacks[callbackIndex]();
  14204. }
  14205. // Cleaning
  14206. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14207. this._toBeDisposed.data[index].dispose();
  14208. this._toBeDisposed[index] = null;
  14209. }
  14210. this._toBeDisposed.reset();
  14211. if (this.dumpNextRenderTargets) {
  14212. this.dumpNextRenderTargets = false;
  14213. }
  14214. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14215. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14216. };
  14217. Scene.prototype._updateAudioParameters = function () {
  14218. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14219. return;
  14220. }
  14221. var listeningCamera;
  14222. var audioEngine = BABYLON.Engine.audioEngine;
  14223. if (this.activeCameras.length > 0) {
  14224. listeningCamera = this.activeCameras[0];
  14225. }
  14226. else {
  14227. listeningCamera = this.activeCamera;
  14228. }
  14229. if (listeningCamera && audioEngine.canUseWebAudio) {
  14230. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14231. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14232. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14233. cameraDirection.normalize();
  14234. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14235. var i;
  14236. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14237. var sound = this.mainSoundTrack.soundCollection[i];
  14238. if (sound.useCustomAttenuation) {
  14239. sound.updateDistanceFromListener();
  14240. }
  14241. }
  14242. for (i = 0; i < this.soundTracks.length; i++) {
  14243. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14244. sound = this.soundTracks[i].soundCollection[j];
  14245. if (sound.useCustomAttenuation) {
  14246. sound.updateDistanceFromListener();
  14247. }
  14248. }
  14249. }
  14250. }
  14251. };
  14252. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14253. // Audio
  14254. get: function () {
  14255. return this._audioEnabled;
  14256. },
  14257. set: function (value) {
  14258. this._audioEnabled = value;
  14259. if (BABYLON.AudioEngine) {
  14260. if (this._audioEnabled) {
  14261. this._enableAudio();
  14262. }
  14263. else {
  14264. this._disableAudio();
  14265. }
  14266. }
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Scene.prototype._disableAudio = function () {
  14272. var i;
  14273. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14274. this.mainSoundTrack.soundCollection[i].pause();
  14275. }
  14276. for (i = 0; i < this.soundTracks.length; i++) {
  14277. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14278. this.soundTracks[i].soundCollection[j].pause();
  14279. }
  14280. }
  14281. };
  14282. Scene.prototype._enableAudio = function () {
  14283. var i;
  14284. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14285. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14286. this.mainSoundTrack.soundCollection[i].play();
  14287. }
  14288. }
  14289. for (i = 0; i < this.soundTracks.length; i++) {
  14290. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14291. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14292. this.soundTracks[i].soundCollection[j].play();
  14293. }
  14294. }
  14295. }
  14296. };
  14297. Object.defineProperty(Scene.prototype, "headphone", {
  14298. get: function () {
  14299. return this._headphone;
  14300. },
  14301. set: function (value) {
  14302. this._headphone = value;
  14303. if (BABYLON.AudioEngine) {
  14304. if (this._headphone) {
  14305. this._switchAudioModeForHeadphones();
  14306. }
  14307. else {
  14308. this._switchAudioModeForNormalSpeakers();
  14309. }
  14310. }
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. Scene.prototype._switchAudioModeForHeadphones = function () {
  14316. this.mainSoundTrack.switchPanningModelToHRTF();
  14317. for (var i = 0; i < this.soundTracks.length; i++) {
  14318. this.soundTracks[i].switchPanningModelToHRTF();
  14319. }
  14320. };
  14321. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14322. this.mainSoundTrack.switchPanningModelToEqualPower();
  14323. for (var i = 0; i < this.soundTracks.length; i++) {
  14324. this.soundTracks[i].switchPanningModelToEqualPower();
  14325. }
  14326. };
  14327. Scene.prototype.enableDepthRenderer = function () {
  14328. if (this._depthRenderer) {
  14329. return this._depthRenderer;
  14330. }
  14331. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14332. return this._depthRenderer;
  14333. };
  14334. Scene.prototype.disableDepthRenderer = function () {
  14335. if (!this._depthRenderer) {
  14336. return;
  14337. }
  14338. this._depthRenderer.dispose();
  14339. this._depthRenderer = null;
  14340. };
  14341. Scene.prototype.freezeMaterials = function () {
  14342. for (var i = 0; i < this.materials.length; i++) {
  14343. this.materials[i].freeze();
  14344. }
  14345. };
  14346. Scene.prototype.unfreezeMaterials = function () {
  14347. for (var i = 0; i < this.materials.length; i++) {
  14348. this.materials[i].unfreeze();
  14349. }
  14350. };
  14351. Scene.prototype.dispose = function () {
  14352. this.beforeRender = null;
  14353. this.afterRender = null;
  14354. this.skeletons = [];
  14355. this._boundingBoxRenderer.dispose();
  14356. if (this._depthRenderer) {
  14357. this._depthRenderer.dispose();
  14358. }
  14359. // Debug layer
  14360. this.debugLayer.hide();
  14361. // Events
  14362. if (this.onDispose) {
  14363. this.onDispose();
  14364. }
  14365. this._onBeforeRenderCallbacks = [];
  14366. this._onAfterRenderCallbacks = [];
  14367. this.detachControl();
  14368. // Release sounds & sounds tracks
  14369. if (BABYLON.AudioEngine) {
  14370. this.disposeSounds();
  14371. }
  14372. // Detach cameras
  14373. var canvas = this._engine.getRenderingCanvas();
  14374. var index;
  14375. for (index = 0; index < this.cameras.length; index++) {
  14376. this.cameras[index].detachControl(canvas);
  14377. }
  14378. // Release lights
  14379. while (this.lights.length) {
  14380. this.lights[0].dispose();
  14381. }
  14382. // Release meshes
  14383. while (this.meshes.length) {
  14384. this.meshes[0].dispose(true);
  14385. }
  14386. // Release cameras
  14387. while (this.cameras.length) {
  14388. this.cameras[0].dispose();
  14389. }
  14390. // Release materials
  14391. while (this.materials.length) {
  14392. this.materials[0].dispose();
  14393. }
  14394. // Release particles
  14395. while (this.particleSystems.length) {
  14396. this.particleSystems[0].dispose();
  14397. }
  14398. // Release sprites
  14399. while (this.spriteManagers.length) {
  14400. this.spriteManagers[0].dispose();
  14401. }
  14402. // Release layers
  14403. while (this.layers.length) {
  14404. this.layers[0].dispose();
  14405. }
  14406. // Release textures
  14407. while (this.textures.length) {
  14408. this.textures[0].dispose();
  14409. }
  14410. // Post-processes
  14411. this.postProcessManager.dispose();
  14412. // Physics
  14413. if (this._physicsEngine) {
  14414. this.disablePhysicsEngine();
  14415. }
  14416. // Remove from engine
  14417. index = this._engine.scenes.indexOf(this);
  14418. if (index > -1) {
  14419. this._engine.scenes.splice(index, 1);
  14420. }
  14421. this._engine.wipeCaches();
  14422. };
  14423. // Release sounds & sounds tracks
  14424. Scene.prototype.disposeSounds = function () {
  14425. this.mainSoundTrack.dispose();
  14426. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14427. this.soundTracks[scIndex].dispose();
  14428. }
  14429. };
  14430. // Octrees
  14431. Scene.prototype.getWorldExtends = function () {
  14432. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14433. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14434. for (var index = 0; index < this.meshes.length; index++) {
  14435. var mesh = this.meshes[index];
  14436. mesh.computeWorldMatrix(true);
  14437. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14438. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14439. BABYLON.Tools.CheckExtends(minBox, min, max);
  14440. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14441. }
  14442. return {
  14443. min: min,
  14444. max: max
  14445. };
  14446. };
  14447. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14448. if (maxCapacity === void 0) { maxCapacity = 64; }
  14449. if (maxDepth === void 0) { maxDepth = 2; }
  14450. if (!this._selectionOctree) {
  14451. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14452. }
  14453. var worldExtends = this.getWorldExtends();
  14454. // Update octree
  14455. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14456. return this._selectionOctree;
  14457. };
  14458. // Picking
  14459. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14460. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14461. var engine = this._engine;
  14462. if (!camera) {
  14463. if (!this.activeCamera)
  14464. throw new Error("Active camera not set");
  14465. camera = this.activeCamera;
  14466. }
  14467. var cameraViewport = camera.viewport;
  14468. var viewport = cameraViewport.toGlobal(engine);
  14469. // Moving coordinates to local viewport world
  14470. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14471. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14472. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14473. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14474. };
  14475. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14476. var engine = this._engine;
  14477. if (!camera) {
  14478. if (!this.activeCamera)
  14479. throw new Error("Active camera not set");
  14480. camera = this.activeCamera;
  14481. }
  14482. var cameraViewport = camera.viewport;
  14483. var viewport = cameraViewport.toGlobal(engine);
  14484. var identity = BABYLON.Matrix.Identity();
  14485. // Moving coordinates to local viewport world
  14486. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14487. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14488. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14489. };
  14490. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14491. var pickingInfo = null;
  14492. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14493. var mesh = this.meshes[meshIndex];
  14494. if (predicate) {
  14495. if (!predicate(mesh)) {
  14496. continue;
  14497. }
  14498. }
  14499. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14500. continue;
  14501. }
  14502. var world = mesh.getWorldMatrix();
  14503. var ray = rayFunction(world);
  14504. var result = mesh.intersects(ray, fastCheck);
  14505. if (!result || !result.hit)
  14506. continue;
  14507. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14508. continue;
  14509. pickingInfo = result;
  14510. if (fastCheck) {
  14511. break;
  14512. }
  14513. }
  14514. return pickingInfo || new BABYLON.PickingInfo();
  14515. };
  14516. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14517. var pickingInfo = null;
  14518. camera = camera || this.activeCamera;
  14519. if (this.spriteManagers.length > 0) {
  14520. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14521. var spriteManager = this.spriteManagers[spriteIndex];
  14522. if (!spriteManager.isPickable) {
  14523. continue;
  14524. }
  14525. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14526. if (!result || !result.hit)
  14527. continue;
  14528. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14529. continue;
  14530. pickingInfo = result;
  14531. if (fastCheck) {
  14532. break;
  14533. }
  14534. }
  14535. }
  14536. return pickingInfo || new BABYLON.PickingInfo();
  14537. };
  14538. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14539. var _this = this;
  14540. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14541. /// <param name="x">X position on screen</param>
  14542. /// <param name="y">Y position on screen</param>
  14543. /// <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>
  14544. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14545. /// <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>
  14546. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14547. };
  14548. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14549. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14550. /// <param name="x">X position on screen</param>
  14551. /// <param name="y">Y position on screen</param>
  14552. /// <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>
  14553. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14554. /// <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>
  14555. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14556. };
  14557. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14558. var _this = this;
  14559. return this._internalPick(function (world) {
  14560. if (!_this._pickWithRayInverseMatrix) {
  14561. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14562. }
  14563. world.invertToRef(_this._pickWithRayInverseMatrix);
  14564. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14565. }, predicate, fastCheck);
  14566. };
  14567. Scene.prototype.setPointerOverMesh = function (mesh) {
  14568. if (this._pointerOverMesh === mesh) {
  14569. return;
  14570. }
  14571. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14572. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14573. }
  14574. this._pointerOverMesh = mesh;
  14575. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14576. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14577. }
  14578. };
  14579. Scene.prototype.getPointerOverMesh = function () {
  14580. return this._pointerOverMesh;
  14581. };
  14582. Scene.prototype.setPointerOverSprite = function (sprite) {
  14583. if (this._pointerOverSprite === sprite) {
  14584. return;
  14585. }
  14586. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14587. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14588. }
  14589. this._pointerOverSprite = sprite;
  14590. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14591. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14592. }
  14593. };
  14594. Scene.prototype.getPointerOverSprite = function () {
  14595. return this._pointerOverSprite;
  14596. };
  14597. // Physics
  14598. Scene.prototype.getPhysicsEngine = function () {
  14599. return this._physicsEngine;
  14600. };
  14601. /**
  14602. * Enables physics to the current scene
  14603. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14604. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14605. * @return {boolean} was the physics engine initialized
  14606. */
  14607. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14608. if (this._physicsEngine) {
  14609. return true;
  14610. }
  14611. try {
  14612. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14613. return true;
  14614. }
  14615. catch (e) {
  14616. BABYLON.Tools.Error(e.message);
  14617. return false;
  14618. }
  14619. };
  14620. Scene.prototype.disablePhysicsEngine = function () {
  14621. if (!this._physicsEngine) {
  14622. return;
  14623. }
  14624. this._physicsEngine.dispose();
  14625. this._physicsEngine = undefined;
  14626. };
  14627. Scene.prototype.isPhysicsEnabled = function () {
  14628. return this._physicsEngine !== undefined;
  14629. };
  14630. /**
  14631. *
  14632. * Sets the gravity of the physics engine (and NOT of the scene)
  14633. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14634. */
  14635. Scene.prototype.setGravity = function (gravity) {
  14636. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14637. if (!this._physicsEngine) {
  14638. return;
  14639. }
  14640. this._physicsEngine.setGravity(gravity);
  14641. };
  14642. /**
  14643. * Legacy support, using the new API
  14644. * @Deprecated
  14645. */
  14646. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14647. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14648. if (parts.parts) {
  14649. options = parts;
  14650. parts = parts.parts;
  14651. }
  14652. var mainMesh = parts[0].mesh;
  14653. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14654. for (var index = 1; index < parts.length; index++) {
  14655. var mesh = parts[index].mesh;
  14656. if (mesh.parent !== mainMesh) {
  14657. mesh.position = mesh.position.subtract(mainMesh.position);
  14658. mesh.parent = mainMesh;
  14659. }
  14660. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14661. }
  14662. mainMesh.physicsImpostor.forceUpdate();
  14663. };
  14664. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14665. var mesh = compound.parts[0].mesh;
  14666. mesh.physicsImpostor.dispose(true);
  14667. mesh.physicsImpostor = null;
  14668. };
  14669. // Misc.
  14670. Scene.prototype.createDefaultCameraOrLight = function () {
  14671. // Light
  14672. if (this.lights.length === 0) {
  14673. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14674. }
  14675. // Camera
  14676. if (!this.activeCamera) {
  14677. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14678. // Compute position
  14679. var worldExtends = this.getWorldExtends();
  14680. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14681. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14682. camera.setTarget(worldCenter);
  14683. this.activeCamera = camera;
  14684. }
  14685. };
  14686. // Tags
  14687. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14688. if (tagsQuery === undefined) {
  14689. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14690. return list;
  14691. }
  14692. var listByTags = [];
  14693. forEach = forEach || (function (item) { return; });
  14694. for (var i in list) {
  14695. var item = list[i];
  14696. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14697. listByTags.push(item);
  14698. forEach(item);
  14699. }
  14700. }
  14701. return listByTags;
  14702. };
  14703. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14704. return this._getByTags(this.meshes, tagsQuery, forEach);
  14705. };
  14706. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14707. return this._getByTags(this.cameras, tagsQuery, forEach);
  14708. };
  14709. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14710. return this._getByTags(this.lights, tagsQuery, forEach);
  14711. };
  14712. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14713. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14714. };
  14715. // Statics
  14716. Scene._FOGMODE_NONE = 0;
  14717. Scene._FOGMODE_EXP = 1;
  14718. Scene._FOGMODE_EXP2 = 2;
  14719. Scene._FOGMODE_LINEAR = 3;
  14720. Scene.MinDeltaTime = 1.0;
  14721. Scene.MaxDeltaTime = 1000.0;
  14722. return Scene;
  14723. })();
  14724. BABYLON.Scene = Scene;
  14725. })(BABYLON || (BABYLON = {}));
  14726. var BABYLON;
  14727. (function (BABYLON) {
  14728. var VertexBuffer = (function () {
  14729. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14730. if (engine instanceof BABYLON.Mesh) {
  14731. this._engine = engine.getScene().getEngine();
  14732. }
  14733. else {
  14734. this._engine = engine;
  14735. }
  14736. this._updatable = updatable;
  14737. this._data = data;
  14738. if (!postponeInternalCreation) {
  14739. this.create();
  14740. }
  14741. this._kind = kind;
  14742. if (stride) {
  14743. this._strideSize = stride;
  14744. return;
  14745. }
  14746. // Deduce stride from kind
  14747. switch (kind) {
  14748. case VertexBuffer.PositionKind:
  14749. this._strideSize = 3;
  14750. break;
  14751. case VertexBuffer.NormalKind:
  14752. this._strideSize = 3;
  14753. break;
  14754. case VertexBuffer.UVKind:
  14755. case VertexBuffer.UV2Kind:
  14756. case VertexBuffer.UV3Kind:
  14757. case VertexBuffer.UV4Kind:
  14758. case VertexBuffer.UV5Kind:
  14759. case VertexBuffer.UV6Kind:
  14760. this._strideSize = 2;
  14761. break;
  14762. case VertexBuffer.ColorKind:
  14763. this._strideSize = 4;
  14764. break;
  14765. case VertexBuffer.MatricesIndicesKind:
  14766. case VertexBuffer.MatricesIndicesExtraKind:
  14767. this._strideSize = 4;
  14768. break;
  14769. case VertexBuffer.MatricesWeightsKind:
  14770. case VertexBuffer.MatricesWeightsExtraKind:
  14771. this._strideSize = 4;
  14772. break;
  14773. }
  14774. }
  14775. // Properties
  14776. VertexBuffer.prototype.isUpdatable = function () {
  14777. return this._updatable;
  14778. };
  14779. VertexBuffer.prototype.getData = function () {
  14780. return this._data;
  14781. };
  14782. VertexBuffer.prototype.getBuffer = function () {
  14783. return this._buffer;
  14784. };
  14785. VertexBuffer.prototype.getStrideSize = function () {
  14786. return this._strideSize;
  14787. };
  14788. // Methods
  14789. VertexBuffer.prototype.create = function (data) {
  14790. if (!data && this._buffer) {
  14791. return; // nothing to do
  14792. }
  14793. data = data || this._data;
  14794. if (!this._buffer) {
  14795. if (this._updatable) {
  14796. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14797. }
  14798. else {
  14799. this._buffer = this._engine.createVertexBuffer(data);
  14800. }
  14801. }
  14802. if (this._updatable) {
  14803. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14804. this._data = data;
  14805. }
  14806. };
  14807. VertexBuffer.prototype.update = function (data) {
  14808. this.create(data);
  14809. };
  14810. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14811. if (!this._buffer) {
  14812. return;
  14813. }
  14814. if (this._updatable) {
  14815. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14816. this._data = null;
  14817. }
  14818. };
  14819. VertexBuffer.prototype.dispose = function () {
  14820. if (!this._buffer) {
  14821. return;
  14822. }
  14823. if (this._engine._releaseBuffer(this._buffer)) {
  14824. this._buffer = null;
  14825. }
  14826. };
  14827. Object.defineProperty(VertexBuffer, "PositionKind", {
  14828. get: function () {
  14829. return VertexBuffer._PositionKind;
  14830. },
  14831. enumerable: true,
  14832. configurable: true
  14833. });
  14834. Object.defineProperty(VertexBuffer, "NormalKind", {
  14835. get: function () {
  14836. return VertexBuffer._NormalKind;
  14837. },
  14838. enumerable: true,
  14839. configurable: true
  14840. });
  14841. Object.defineProperty(VertexBuffer, "UVKind", {
  14842. get: function () {
  14843. return VertexBuffer._UVKind;
  14844. },
  14845. enumerable: true,
  14846. configurable: true
  14847. });
  14848. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14849. get: function () {
  14850. return VertexBuffer._UV2Kind;
  14851. },
  14852. enumerable: true,
  14853. configurable: true
  14854. });
  14855. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14856. get: function () {
  14857. return VertexBuffer._UV3Kind;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14863. get: function () {
  14864. return VertexBuffer._UV4Kind;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14870. get: function () {
  14871. return VertexBuffer._UV5Kind;
  14872. },
  14873. enumerable: true,
  14874. configurable: true
  14875. });
  14876. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14877. get: function () {
  14878. return VertexBuffer._UV6Kind;
  14879. },
  14880. enumerable: true,
  14881. configurable: true
  14882. });
  14883. Object.defineProperty(VertexBuffer, "ColorKind", {
  14884. get: function () {
  14885. return VertexBuffer._ColorKind;
  14886. },
  14887. enumerable: true,
  14888. configurable: true
  14889. });
  14890. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14891. get: function () {
  14892. return VertexBuffer._MatricesIndicesKind;
  14893. },
  14894. enumerable: true,
  14895. configurable: true
  14896. });
  14897. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14898. get: function () {
  14899. return VertexBuffer._MatricesWeightsKind;
  14900. },
  14901. enumerable: true,
  14902. configurable: true
  14903. });
  14904. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14905. get: function () {
  14906. return VertexBuffer._MatricesIndicesExtraKind;
  14907. },
  14908. enumerable: true,
  14909. configurable: true
  14910. });
  14911. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14912. get: function () {
  14913. return VertexBuffer._MatricesWeightsExtraKind;
  14914. },
  14915. enumerable: true,
  14916. configurable: true
  14917. });
  14918. // Enums
  14919. VertexBuffer._PositionKind = "position";
  14920. VertexBuffer._NormalKind = "normal";
  14921. VertexBuffer._UVKind = "uv";
  14922. VertexBuffer._UV2Kind = "uv2";
  14923. VertexBuffer._UV3Kind = "uv3";
  14924. VertexBuffer._UV4Kind = "uv4";
  14925. VertexBuffer._UV5Kind = "uv5";
  14926. VertexBuffer._UV6Kind = "uv6";
  14927. VertexBuffer._ColorKind = "color";
  14928. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14929. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14930. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14931. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14932. return VertexBuffer;
  14933. })();
  14934. BABYLON.VertexBuffer = VertexBuffer;
  14935. })(BABYLON || (BABYLON = {}));
  14936. var BABYLON;
  14937. (function (BABYLON) {
  14938. /**
  14939. * Creates an instance based on a source mesh.
  14940. */
  14941. var InstancedMesh = (function (_super) {
  14942. __extends(InstancedMesh, _super);
  14943. function InstancedMesh(name, source) {
  14944. _super.call(this, name, source.getScene());
  14945. source.instances.push(this);
  14946. this._sourceMesh = source;
  14947. this.position.copyFrom(source.position);
  14948. this.rotation.copyFrom(source.rotation);
  14949. this.scaling.copyFrom(source.scaling);
  14950. if (source.rotationQuaternion) {
  14951. this.rotationQuaternion = source.rotationQuaternion.clone();
  14952. }
  14953. this.infiniteDistance = source.infiniteDistance;
  14954. this.setPivotMatrix(source.getPivotMatrix());
  14955. this.refreshBoundingInfo();
  14956. this._syncSubMeshes();
  14957. }
  14958. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14959. // Methods
  14960. get: function () {
  14961. return this._sourceMesh.receiveShadows;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(InstancedMesh.prototype, "material", {
  14967. get: function () {
  14968. return this._sourceMesh.material;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14974. get: function () {
  14975. return this._sourceMesh.visibility;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14981. get: function () {
  14982. return this._sourceMesh.skeleton;
  14983. },
  14984. enumerable: true,
  14985. configurable: true
  14986. });
  14987. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14988. get: function () {
  14989. return this._sourceMesh.renderingGroupId;
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. InstancedMesh.prototype.getTotalVertices = function () {
  14995. return this._sourceMesh.getTotalVertices();
  14996. };
  14997. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14998. get: function () {
  14999. return this._sourceMesh;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15005. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15006. };
  15007. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15008. return this._sourceMesh.isVerticesDataPresent(kind);
  15009. };
  15010. InstancedMesh.prototype.getIndices = function () {
  15011. return this._sourceMesh.getIndices();
  15012. };
  15013. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15014. get: function () {
  15015. return this._sourceMesh._positions;
  15016. },
  15017. enumerable: true,
  15018. configurable: true
  15019. });
  15020. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15021. var meshBB = this._sourceMesh.getBoundingInfo();
  15022. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15023. this._updateBoundingInfo();
  15024. };
  15025. InstancedMesh.prototype._preActivate = function () {
  15026. if (this._currentLOD) {
  15027. this._currentLOD._preActivate();
  15028. }
  15029. };
  15030. InstancedMesh.prototype._activate = function (renderId) {
  15031. if (this._currentLOD) {
  15032. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15033. }
  15034. };
  15035. InstancedMesh.prototype.getLOD = function (camera) {
  15036. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15037. if (this._currentLOD === this.sourceMesh) {
  15038. return this;
  15039. }
  15040. return this._currentLOD;
  15041. };
  15042. InstancedMesh.prototype._syncSubMeshes = function () {
  15043. this.releaseSubMeshes();
  15044. if (this._sourceMesh.subMeshes) {
  15045. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15046. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15047. }
  15048. }
  15049. };
  15050. InstancedMesh.prototype._generatePointsArray = function () {
  15051. return this._sourceMesh._generatePointsArray();
  15052. };
  15053. // Clone
  15054. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15055. var result = this._sourceMesh.createInstance(name);
  15056. // Deep copy
  15057. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15058. // Bounding info
  15059. this.refreshBoundingInfo();
  15060. // Parent
  15061. if (newParent) {
  15062. result.parent = newParent;
  15063. }
  15064. if (!doNotCloneChildren) {
  15065. // Children
  15066. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15067. var mesh = this.getScene().meshes[index];
  15068. if (mesh.parent === this) {
  15069. mesh.clone(mesh.name, result);
  15070. }
  15071. }
  15072. }
  15073. result.computeWorldMatrix(true);
  15074. return result;
  15075. };
  15076. // Dispoe
  15077. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15078. // Remove from mesh
  15079. var index = this._sourceMesh.instances.indexOf(this);
  15080. this._sourceMesh.instances.splice(index, 1);
  15081. _super.prototype.dispose.call(this, doNotRecurse);
  15082. };
  15083. return InstancedMesh;
  15084. })(BABYLON.AbstractMesh);
  15085. BABYLON.InstancedMesh = InstancedMesh;
  15086. })(BABYLON || (BABYLON = {}));
  15087. var BABYLON;
  15088. (function (BABYLON) {
  15089. var _InstancesBatch = (function () {
  15090. function _InstancesBatch() {
  15091. this.mustReturn = false;
  15092. this.visibleInstances = new Array();
  15093. this.renderSelf = new Array();
  15094. }
  15095. return _InstancesBatch;
  15096. })();
  15097. BABYLON._InstancesBatch = _InstancesBatch;
  15098. var Mesh = (function (_super) {
  15099. __extends(Mesh, _super);
  15100. /**
  15101. * @constructor
  15102. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15103. * @param {Scene} scene - The scene to add this mesh to.
  15104. * @param {Node} parent - The parent of this mesh, if it has one
  15105. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15106. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15107. * When false, achieved by calling a clone(), also passing False.
  15108. * This will make creation of children, recursive.
  15109. */
  15110. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15111. if (parent === void 0) { parent = null; }
  15112. _super.call(this, name, scene);
  15113. // Members
  15114. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15115. this.instances = new Array();
  15116. this._LODLevels = new Array();
  15117. this._onBeforeRenderCallbacks = new Array();
  15118. this._onAfterRenderCallbacks = new Array();
  15119. this._visibleInstances = {};
  15120. this._renderIdForInstances = new Array();
  15121. this._batchCache = new _InstancesBatch();
  15122. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15123. this._sideOrientation = Mesh._DEFAULTSIDE;
  15124. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15125. if (source) {
  15126. // Geometry
  15127. if (source._geometry) {
  15128. source._geometry.applyToMesh(this);
  15129. }
  15130. // Deep copy
  15131. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  15132. // Pivot
  15133. this.setPivotMatrix(source.getPivotMatrix());
  15134. this.id = name + "." + source.id;
  15135. // Material
  15136. this.material = source.material;
  15137. var index;
  15138. if (!doNotCloneChildren) {
  15139. // Children
  15140. for (index = 0; index < scene.meshes.length; index++) {
  15141. var mesh = scene.meshes[index];
  15142. if (mesh.parent === source) {
  15143. // doNotCloneChildren is always going to be False
  15144. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15145. }
  15146. }
  15147. }
  15148. // Particles
  15149. for (index = 0; index < scene.particleSystems.length; index++) {
  15150. var system = scene.particleSystems[index];
  15151. if (system.emitter === source) {
  15152. system.clone(system.name, this);
  15153. }
  15154. }
  15155. this.computeWorldMatrix(true);
  15156. }
  15157. // Parent
  15158. if (parent !== null) {
  15159. this.parent = parent;
  15160. }
  15161. }
  15162. Object.defineProperty(Mesh, "FRONTSIDE", {
  15163. get: function () {
  15164. return Mesh._FRONTSIDE;
  15165. },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. Object.defineProperty(Mesh, "BACKSIDE", {
  15170. get: function () {
  15171. return Mesh._BACKSIDE;
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15177. get: function () {
  15178. return Mesh._DOUBLESIDE;
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15184. get: function () {
  15185. return Mesh._DEFAULTSIDE;
  15186. },
  15187. enumerable: true,
  15188. configurable: true
  15189. });
  15190. Object.defineProperty(Mesh, "NO_CAP", {
  15191. get: function () {
  15192. return Mesh._NO_CAP;
  15193. },
  15194. enumerable: true,
  15195. configurable: true
  15196. });
  15197. Object.defineProperty(Mesh, "CAP_START", {
  15198. get: function () {
  15199. return Mesh._CAP_START;
  15200. },
  15201. enumerable: true,
  15202. configurable: true
  15203. });
  15204. Object.defineProperty(Mesh, "CAP_END", {
  15205. get: function () {
  15206. return Mesh._CAP_END;
  15207. },
  15208. enumerable: true,
  15209. configurable: true
  15210. });
  15211. Object.defineProperty(Mesh, "CAP_ALL", {
  15212. get: function () {
  15213. return Mesh._CAP_ALL;
  15214. },
  15215. enumerable: true,
  15216. configurable: true
  15217. });
  15218. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15219. // Methods
  15220. get: function () {
  15221. return this._LODLevels.length > 0;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Mesh.prototype._sortLODLevels = function () {
  15227. this._LODLevels.sort(function (a, b) {
  15228. if (a.distance < b.distance) {
  15229. return 1;
  15230. }
  15231. if (a.distance > b.distance) {
  15232. return -1;
  15233. }
  15234. return 0;
  15235. });
  15236. };
  15237. /**
  15238. * Add a mesh as LOD level triggered at the given distance.
  15239. * @param {number} distance - the distance from the center of the object to show this level
  15240. * @param {Mesh} mesh - the mesh to be added as LOD level
  15241. * @return {Mesh} this mesh (for chaining)
  15242. */
  15243. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15244. if (mesh && mesh._masterMesh) {
  15245. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15246. return this;
  15247. }
  15248. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15249. this._LODLevels.push(level);
  15250. if (mesh) {
  15251. mesh._masterMesh = this;
  15252. }
  15253. this._sortLODLevels();
  15254. return this;
  15255. };
  15256. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15257. for (var index = 0; index < this._LODLevels.length; index++) {
  15258. var level = this._LODLevels[index];
  15259. if (level.distance === distance) {
  15260. return level.mesh;
  15261. }
  15262. }
  15263. return null;
  15264. };
  15265. /**
  15266. * Remove a mesh from the LOD array
  15267. * @param {Mesh} mesh - the mesh to be removed.
  15268. * @return {Mesh} this mesh (for chaining)
  15269. */
  15270. Mesh.prototype.removeLODLevel = function (mesh) {
  15271. for (var index = 0; index < this._LODLevels.length; index++) {
  15272. if (this._LODLevels[index].mesh === mesh) {
  15273. this._LODLevels.splice(index, 1);
  15274. if (mesh) {
  15275. mesh._masterMesh = null;
  15276. }
  15277. }
  15278. }
  15279. this._sortLODLevels();
  15280. return this;
  15281. };
  15282. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15283. if (!this._LODLevels || this._LODLevels.length === 0) {
  15284. return this;
  15285. }
  15286. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15287. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15288. if (this.onLODLevelSelection) {
  15289. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15290. }
  15291. return this;
  15292. }
  15293. for (var index = 0; index < this._LODLevels.length; index++) {
  15294. var level = this._LODLevels[index];
  15295. if (level.distance < distanceToCamera) {
  15296. if (level.mesh) {
  15297. level.mesh._preActivate();
  15298. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15299. }
  15300. if (this.onLODLevelSelection) {
  15301. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15302. }
  15303. return level.mesh;
  15304. }
  15305. }
  15306. if (this.onLODLevelSelection) {
  15307. this.onLODLevelSelection(distanceToCamera, this, this);
  15308. }
  15309. return this;
  15310. };
  15311. Object.defineProperty(Mesh.prototype, "geometry", {
  15312. get: function () {
  15313. return this._geometry;
  15314. },
  15315. enumerable: true,
  15316. configurable: true
  15317. });
  15318. Mesh.prototype.getTotalVertices = function () {
  15319. if (!this._geometry) {
  15320. return 0;
  15321. }
  15322. return this._geometry.getTotalVertices();
  15323. };
  15324. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15325. if (!this._geometry) {
  15326. return null;
  15327. }
  15328. return this._geometry.getVerticesData(kind, copyWhenShared);
  15329. };
  15330. Mesh.prototype.getVertexBuffer = function (kind) {
  15331. if (!this._geometry) {
  15332. return undefined;
  15333. }
  15334. return this._geometry.getVertexBuffer(kind);
  15335. };
  15336. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15337. if (!this._geometry) {
  15338. if (this._delayInfo) {
  15339. return this._delayInfo.indexOf(kind) !== -1;
  15340. }
  15341. return false;
  15342. }
  15343. return this._geometry.isVerticesDataPresent(kind);
  15344. };
  15345. Mesh.prototype.getVerticesDataKinds = function () {
  15346. if (!this._geometry) {
  15347. var result = [];
  15348. if (this._delayInfo) {
  15349. for (var kind in this._delayInfo) {
  15350. result.push(kind);
  15351. }
  15352. }
  15353. return result;
  15354. }
  15355. return this._geometry.getVerticesDataKinds();
  15356. };
  15357. Mesh.prototype.getTotalIndices = function () {
  15358. if (!this._geometry) {
  15359. return 0;
  15360. }
  15361. return this._geometry.getTotalIndices();
  15362. };
  15363. Mesh.prototype.getIndices = function (copyWhenShared) {
  15364. if (!this._geometry) {
  15365. return [];
  15366. }
  15367. return this._geometry.getIndices(copyWhenShared);
  15368. };
  15369. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15370. get: function () {
  15371. return this._masterMesh !== null && this._masterMesh !== undefined;
  15372. },
  15373. enumerable: true,
  15374. configurable: true
  15375. });
  15376. Mesh.prototype.isReady = function () {
  15377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15378. return false;
  15379. }
  15380. return _super.prototype.isReady.call(this);
  15381. };
  15382. Mesh.prototype.isDisposed = function () {
  15383. return this._isDisposed;
  15384. };
  15385. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15386. get: function () {
  15387. return this._sideOrientation;
  15388. },
  15389. set: function (sideO) {
  15390. this._sideOrientation = sideO;
  15391. },
  15392. enumerable: true,
  15393. configurable: true
  15394. });
  15395. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15396. get: function () {
  15397. return this._areNormalsFrozen;
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15403. Mesh.prototype.freezeNormals = function () {
  15404. this._areNormalsFrozen = true;
  15405. };
  15406. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15407. Mesh.prototype.unfreezeNormals = function () {
  15408. this._areNormalsFrozen = false;
  15409. };
  15410. // Methods
  15411. Mesh.prototype._preActivate = function () {
  15412. var sceneRenderId = this.getScene().getRenderId();
  15413. if (this._preActivateId === sceneRenderId) {
  15414. return;
  15415. }
  15416. this._preActivateId = sceneRenderId;
  15417. this._visibleInstances = null;
  15418. };
  15419. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15420. if (!this._visibleInstances) {
  15421. this._visibleInstances = {};
  15422. this._visibleInstances.defaultRenderId = renderId;
  15423. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15424. }
  15425. if (!this._visibleInstances[renderId]) {
  15426. this._visibleInstances[renderId] = new Array();
  15427. }
  15428. this._visibleInstances[renderId].push(instance);
  15429. };
  15430. Mesh.prototype.refreshBoundingInfo = function () {
  15431. if (this._boundingInfo.isLocked) {
  15432. return;
  15433. }
  15434. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15435. if (data) {
  15436. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15437. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15438. }
  15439. if (this.subMeshes) {
  15440. for (var index = 0; index < this.subMeshes.length; index++) {
  15441. this.subMeshes[index].refreshBoundingInfo();
  15442. }
  15443. }
  15444. this._updateBoundingInfo();
  15445. };
  15446. Mesh.prototype._createGlobalSubMesh = function () {
  15447. var totalVertices = this.getTotalVertices();
  15448. if (!totalVertices || !this.getIndices()) {
  15449. return null;
  15450. }
  15451. this.releaseSubMeshes();
  15452. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15453. };
  15454. Mesh.prototype.subdivide = function (count) {
  15455. if (count < 1) {
  15456. return;
  15457. }
  15458. var totalIndices = this.getTotalIndices();
  15459. var subdivisionSize = (totalIndices / count) | 0;
  15460. var offset = 0;
  15461. // Ensure that subdivisionSize is a multiple of 3
  15462. while (subdivisionSize % 3 !== 0) {
  15463. subdivisionSize++;
  15464. }
  15465. this.releaseSubMeshes();
  15466. for (var index = 0; index < count; index++) {
  15467. if (offset >= totalIndices) {
  15468. break;
  15469. }
  15470. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15471. offset += subdivisionSize;
  15472. }
  15473. this.synchronizeInstances();
  15474. };
  15475. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15476. if (!this._geometry) {
  15477. var vertexData = new BABYLON.VertexData();
  15478. vertexData.set(data, kind);
  15479. var scene = this.getScene();
  15480. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15481. }
  15482. else {
  15483. this._geometry.setVerticesData(kind, data, updatable, stride);
  15484. }
  15485. };
  15486. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15487. if (!this._geometry) {
  15488. return;
  15489. }
  15490. if (!makeItUnique) {
  15491. this._geometry.updateVerticesData(kind, data, updateExtends);
  15492. }
  15493. else {
  15494. this.makeGeometryUnique();
  15495. this.updateVerticesData(kind, data, updateExtends, false);
  15496. }
  15497. };
  15498. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15499. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15500. if (!this._geometry) {
  15501. return;
  15502. }
  15503. if (!makeItUnique) {
  15504. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15505. }
  15506. else {
  15507. this.makeGeometryUnique();
  15508. this.updateVerticesDataDirectly(kind, data, offset, false);
  15509. }
  15510. };
  15511. // Mesh positions update function :
  15512. // updates the mesh positions according to the positionFunction returned values.
  15513. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15514. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15515. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15516. if (computeNormals === void 0) { computeNormals = true; }
  15517. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15518. positionFunction(positions);
  15519. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15520. if (computeNormals) {
  15521. var indices = this.getIndices();
  15522. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15523. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15524. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15525. }
  15526. };
  15527. Mesh.prototype.makeGeometryUnique = function () {
  15528. if (!this._geometry) {
  15529. return;
  15530. }
  15531. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15532. geometry.applyToMesh(this);
  15533. };
  15534. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15535. if (!this._geometry) {
  15536. var vertexData = new BABYLON.VertexData();
  15537. vertexData.indices = indices;
  15538. var scene = this.getScene();
  15539. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15540. }
  15541. else {
  15542. this._geometry.setIndices(indices, totalVertices);
  15543. }
  15544. };
  15545. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15546. var engine = this.getScene().getEngine();
  15547. // Wireframe
  15548. var indexToBind;
  15549. if (this._unIndexed) {
  15550. indexToBind = null;
  15551. }
  15552. else {
  15553. switch (fillMode) {
  15554. case BABYLON.Material.PointFillMode:
  15555. indexToBind = null;
  15556. break;
  15557. case BABYLON.Material.WireFrameFillMode:
  15558. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15559. break;
  15560. default:
  15561. case BABYLON.Material.TriangleFillMode:
  15562. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15563. break;
  15564. }
  15565. }
  15566. // VBOs
  15567. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15568. };
  15569. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15570. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15571. return;
  15572. }
  15573. if (this.onBeforeDraw) {
  15574. this.onBeforeDraw();
  15575. }
  15576. var engine = this.getScene().getEngine();
  15577. // Draw order
  15578. switch (fillMode) {
  15579. case BABYLON.Material.PointFillMode:
  15580. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15581. break;
  15582. case BABYLON.Material.WireFrameFillMode:
  15583. if (this._unIndexed) {
  15584. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15585. }
  15586. else {
  15587. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15588. }
  15589. break;
  15590. default:
  15591. if (this._unIndexed) {
  15592. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15593. }
  15594. else {
  15595. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15596. }
  15597. }
  15598. };
  15599. Mesh.prototype.registerBeforeRender = function (func) {
  15600. this._onBeforeRenderCallbacks.push(func);
  15601. };
  15602. Mesh.prototype.unregisterBeforeRender = function (func) {
  15603. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15604. if (index > -1) {
  15605. this._onBeforeRenderCallbacks.splice(index, 1);
  15606. }
  15607. };
  15608. Mesh.prototype.registerAfterRender = function (func) {
  15609. this._onAfterRenderCallbacks.push(func);
  15610. };
  15611. Mesh.prototype.unregisterAfterRender = function (func) {
  15612. var index = this._onAfterRenderCallbacks.indexOf(func);
  15613. if (index > -1) {
  15614. this._onAfterRenderCallbacks.splice(index, 1);
  15615. }
  15616. };
  15617. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15618. var scene = this.getScene();
  15619. this._batchCache.mustReturn = false;
  15620. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15621. this._batchCache.visibleInstances[subMeshId] = null;
  15622. if (this._visibleInstances) {
  15623. var currentRenderId = scene.getRenderId();
  15624. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15625. var selfRenderId = this._renderId;
  15626. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15627. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15628. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15629. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15630. }
  15631. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15632. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15633. this._batchCache.mustReturn = true;
  15634. return this._batchCache;
  15635. }
  15636. if (currentRenderId !== selfRenderId) {
  15637. this._batchCache.renderSelf[subMeshId] = false;
  15638. }
  15639. }
  15640. this._renderIdForInstances[subMeshId] = currentRenderId;
  15641. }
  15642. return this._batchCache;
  15643. };
  15644. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15645. var visibleInstances = batch.visibleInstances[subMesh._id];
  15646. var matricesCount = visibleInstances.length + 1;
  15647. var bufferSize = matricesCount * 16 * 4;
  15648. while (this._instancesBufferSize < bufferSize) {
  15649. this._instancesBufferSize *= 2;
  15650. }
  15651. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15652. if (this._worldMatricesInstancesBuffer) {
  15653. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15654. }
  15655. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15656. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15657. }
  15658. var offset = 0;
  15659. var instancesCount = 0;
  15660. var world = this.getWorldMatrix();
  15661. if (batch.renderSelf[subMesh._id]) {
  15662. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15663. offset += 16;
  15664. instancesCount++;
  15665. }
  15666. if (visibleInstances) {
  15667. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15668. var instance = visibleInstances[instanceIndex];
  15669. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15670. offset += 16;
  15671. instancesCount++;
  15672. }
  15673. }
  15674. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15675. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15676. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15677. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15678. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15679. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15680. this._draw(subMesh, fillMode, instancesCount);
  15681. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15682. };
  15683. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15684. var scene = this.getScene();
  15685. var engine = scene.getEngine();
  15686. if (hardwareInstancedRendering) {
  15687. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15688. }
  15689. else {
  15690. if (batch.renderSelf[subMesh._id]) {
  15691. // Draw
  15692. if (onBeforeDraw) {
  15693. onBeforeDraw(false, this.getWorldMatrix());
  15694. }
  15695. this._draw(subMesh, fillMode);
  15696. }
  15697. if (batch.visibleInstances[subMesh._id]) {
  15698. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15699. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15700. // World
  15701. var world = instance.getWorldMatrix();
  15702. if (onBeforeDraw) {
  15703. onBeforeDraw(true, world);
  15704. }
  15705. // Draw
  15706. this._draw(subMesh, fillMode);
  15707. }
  15708. }
  15709. }
  15710. };
  15711. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15712. var scene = this.getScene();
  15713. // Managing instances
  15714. var batch = this._getInstancesRenderList(subMesh._id);
  15715. if (batch.mustReturn) {
  15716. return;
  15717. }
  15718. // Checking geometry state
  15719. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15720. return;
  15721. }
  15722. var callbackIndex;
  15723. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15724. this._onBeforeRenderCallbacks[callbackIndex](this);
  15725. }
  15726. var engine = scene.getEngine();
  15727. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15728. // Material
  15729. var effectiveMaterial = subMesh.getMaterial();
  15730. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15731. return;
  15732. }
  15733. // Outline - step 1
  15734. var savedDepthWrite = engine.getDepthWrite();
  15735. if (this.renderOutline) {
  15736. engine.setDepthWrite(false);
  15737. scene.getOutlineRenderer().render(subMesh, batch);
  15738. engine.setDepthWrite(savedDepthWrite);
  15739. }
  15740. effectiveMaterial._preBind();
  15741. var effect = effectiveMaterial.getEffect();
  15742. // Bind
  15743. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15744. this._bind(subMesh, effect, fillMode);
  15745. var world = this.getWorldMatrix();
  15746. effectiveMaterial.bind(world, this);
  15747. // Alpha mode
  15748. if (enableAlphaMode) {
  15749. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15750. }
  15751. // Draw
  15752. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15753. if (isInstance) {
  15754. effectiveMaterial.bindOnlyWorldMatrix(world);
  15755. }
  15756. });
  15757. // Unbind
  15758. effectiveMaterial.unbind();
  15759. // Outline - step 2
  15760. if (this.renderOutline && savedDepthWrite) {
  15761. engine.setDepthWrite(true);
  15762. engine.setColorWrite(false);
  15763. scene.getOutlineRenderer().render(subMesh, batch);
  15764. engine.setColorWrite(true);
  15765. }
  15766. // Overlay
  15767. if (this.renderOverlay) {
  15768. var currentMode = engine.getAlphaMode();
  15769. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15770. scene.getOutlineRenderer().render(subMesh, batch, true);
  15771. engine.setAlphaMode(currentMode);
  15772. }
  15773. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15774. this._onAfterRenderCallbacks[callbackIndex](this);
  15775. }
  15776. };
  15777. Mesh.prototype.getEmittedParticleSystems = function () {
  15778. var results = new Array();
  15779. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15780. var particleSystem = this.getScene().particleSystems[index];
  15781. if (particleSystem.emitter === this) {
  15782. results.push(particleSystem);
  15783. }
  15784. }
  15785. return results;
  15786. };
  15787. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15788. var results = new Array();
  15789. var descendants = this.getDescendants();
  15790. descendants.push(this);
  15791. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15792. var particleSystem = this.getScene().particleSystems[index];
  15793. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15794. results.push(particleSystem);
  15795. }
  15796. }
  15797. return results;
  15798. };
  15799. Mesh.prototype._checkDelayState = function () {
  15800. var _this = this;
  15801. var that = this;
  15802. var scene = this.getScene();
  15803. if (this._geometry) {
  15804. this._geometry.load(scene);
  15805. }
  15806. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15807. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15808. scene._addPendingData(that);
  15809. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15810. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15811. if (data instanceof ArrayBuffer) {
  15812. _this._delayLoadingFunction(data, _this);
  15813. }
  15814. else {
  15815. _this._delayLoadingFunction(JSON.parse(data), _this);
  15816. }
  15817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15818. scene._removePendingData(_this);
  15819. }, function () { }, scene.database, getBinaryData);
  15820. }
  15821. };
  15822. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15823. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15824. return false;
  15825. }
  15826. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15827. return false;
  15828. }
  15829. this._checkDelayState();
  15830. return true;
  15831. };
  15832. Mesh.prototype.setMaterialByID = function (id) {
  15833. var materials = this.getScene().materials;
  15834. var index;
  15835. for (index = 0; index < materials.length; index++) {
  15836. if (materials[index].id === id) {
  15837. this.material = materials[index];
  15838. return;
  15839. }
  15840. }
  15841. // Multi
  15842. var multiMaterials = this.getScene().multiMaterials;
  15843. for (index = 0; index < multiMaterials.length; index++) {
  15844. if (multiMaterials[index].id === id) {
  15845. this.material = multiMaterials[index];
  15846. return;
  15847. }
  15848. }
  15849. };
  15850. Mesh.prototype.getAnimatables = function () {
  15851. var results = [];
  15852. if (this.material) {
  15853. results.push(this.material);
  15854. }
  15855. if (this.skeleton) {
  15856. results.push(this.skeleton);
  15857. }
  15858. return results;
  15859. };
  15860. // Geometry
  15861. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15862. // Position
  15863. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15864. return;
  15865. }
  15866. this._resetPointsArrayCache();
  15867. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15868. var temp = [];
  15869. var index;
  15870. for (index = 0; index < data.length; index += 3) {
  15871. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15872. }
  15873. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15874. // Normals
  15875. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15876. return;
  15877. }
  15878. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15879. temp = [];
  15880. for (index = 0; index < data.length; index += 3) {
  15881. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15882. }
  15883. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15884. // flip faces?
  15885. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15886. this.flipFaces();
  15887. }
  15888. };
  15889. // Will apply current transform to mesh and reset world matrix
  15890. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15891. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15892. this.scaling.copyFromFloats(1, 1, 1);
  15893. this.position.copyFromFloats(0, 0, 0);
  15894. this.rotation.copyFromFloats(0, 0, 0);
  15895. //only if quaternion is already set
  15896. if (this.rotationQuaternion) {
  15897. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15898. }
  15899. this._worldMatrix = BABYLON.Matrix.Identity();
  15900. };
  15901. // Cache
  15902. Mesh.prototype._resetPointsArrayCache = function () {
  15903. this._positions = null;
  15904. };
  15905. Mesh.prototype._generatePointsArray = function () {
  15906. if (this._positions)
  15907. return true;
  15908. this._positions = [];
  15909. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15910. if (!data) {
  15911. return false;
  15912. }
  15913. for (var index = 0; index < data.length; index += 3) {
  15914. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15915. }
  15916. return true;
  15917. };
  15918. // Clone
  15919. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15920. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15921. };
  15922. // Dispose
  15923. Mesh.prototype.dispose = function (doNotRecurse) {
  15924. if (this._geometry) {
  15925. this._geometry.releaseForMesh(this, true);
  15926. }
  15927. // Instances
  15928. if (this._worldMatricesInstancesBuffer) {
  15929. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15930. this._worldMatricesInstancesBuffer = null;
  15931. }
  15932. while (this.instances.length) {
  15933. this.instances[0].dispose();
  15934. }
  15935. _super.prototype.dispose.call(this, doNotRecurse);
  15936. };
  15937. // Geometric tools
  15938. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15939. var _this = this;
  15940. var scene = this.getScene();
  15941. var onload = function (img) {
  15942. // Getting height map data
  15943. var canvas = document.createElement("canvas");
  15944. var context = canvas.getContext("2d");
  15945. var heightMapWidth = img.width;
  15946. var heightMapHeight = img.height;
  15947. canvas.width = heightMapWidth;
  15948. canvas.height = heightMapHeight;
  15949. context.drawImage(img, 0, 0);
  15950. // Create VertexData from map data
  15951. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15952. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15953. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15954. //execute success callback, if set
  15955. if (onSuccess) {
  15956. onSuccess(_this);
  15957. }
  15958. };
  15959. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15960. };
  15961. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15963. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15964. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15965. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15966. return;
  15967. }
  15968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15969. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15970. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15971. var position = BABYLON.Vector3.Zero();
  15972. var normal = BABYLON.Vector3.Zero();
  15973. var uv = BABYLON.Vector2.Zero();
  15974. for (var index = 0; index < positions.length; index += 3) {
  15975. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15976. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15977. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15978. // Compute height
  15979. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15980. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15981. var pos = (u + v * heightMapWidth) * 4;
  15982. var r = buffer[pos] / 255.0;
  15983. var g = buffer[pos + 1] / 255.0;
  15984. var b = buffer[pos + 2] / 255.0;
  15985. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15986. normal.normalize();
  15987. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15988. position = position.add(normal);
  15989. position.toArray(positions, index);
  15990. }
  15991. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15992. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15993. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15994. };
  15995. Mesh.prototype.convertToFlatShadedMesh = function () {
  15996. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15997. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15998. var kinds = this.getVerticesDataKinds();
  15999. var vbs = [];
  16000. var data = [];
  16001. var newdata = [];
  16002. var updatableNormals = false;
  16003. var kindIndex;
  16004. var kind;
  16005. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16006. kind = kinds[kindIndex];
  16007. var vertexBuffer = this.getVertexBuffer(kind);
  16008. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16009. updatableNormals = vertexBuffer.isUpdatable();
  16010. kinds.splice(kindIndex, 1);
  16011. kindIndex--;
  16012. continue;
  16013. }
  16014. vbs[kind] = vertexBuffer;
  16015. data[kind] = vbs[kind].getData();
  16016. newdata[kind] = [];
  16017. }
  16018. // Save previous submeshes
  16019. var previousSubmeshes = this.subMeshes.slice(0);
  16020. var indices = this.getIndices();
  16021. var totalIndices = this.getTotalIndices();
  16022. // Generating unique vertices per face
  16023. var index;
  16024. for (index = 0; index < totalIndices; index++) {
  16025. var vertexIndex = indices[index];
  16026. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16027. kind = kinds[kindIndex];
  16028. var stride = vbs[kind].getStrideSize();
  16029. for (var offset = 0; offset < stride; offset++) {
  16030. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16031. }
  16032. }
  16033. }
  16034. // Updating faces & normal
  16035. var normals = [];
  16036. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  16037. for (index = 0; index < totalIndices; index += 3) {
  16038. indices[index] = index;
  16039. indices[index + 1] = index + 1;
  16040. indices[index + 2] = index + 2;
  16041. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16042. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16043. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16044. var p1p2 = p1.subtract(p2);
  16045. var p3p2 = p3.subtract(p2);
  16046. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16047. // Store same normals for every vertex
  16048. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16049. normals.push(normal.x);
  16050. normals.push(normal.y);
  16051. normals.push(normal.z);
  16052. }
  16053. }
  16054. this.setIndices(indices);
  16055. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16056. // Updating vertex buffers
  16057. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16058. kind = kinds[kindIndex];
  16059. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16060. }
  16061. // Updating submeshes
  16062. this.releaseSubMeshes();
  16063. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16064. var previousOne = previousSubmeshes[submeshIndex];
  16065. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16066. }
  16067. this.synchronizeInstances();
  16068. };
  16069. Mesh.prototype.convertToUnIndexedMesh = function () {
  16070. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16071. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16072. var kinds = this.getVerticesDataKinds();
  16073. var vbs = [];
  16074. var data = [];
  16075. var newdata = [];
  16076. var updatableNormals = false;
  16077. var kindIndex;
  16078. var kind;
  16079. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16080. kind = kinds[kindIndex];
  16081. var vertexBuffer = this.getVertexBuffer(kind);
  16082. vbs[kind] = vertexBuffer;
  16083. data[kind] = vbs[kind].getData();
  16084. newdata[kind] = [];
  16085. }
  16086. // Save previous submeshes
  16087. var previousSubmeshes = this.subMeshes.slice(0);
  16088. var indices = this.getIndices();
  16089. var totalIndices = this.getTotalIndices();
  16090. // Generating unique vertices per face
  16091. var index;
  16092. for (index = 0; index < totalIndices; index++) {
  16093. var vertexIndex = indices[index];
  16094. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16095. kind = kinds[kindIndex];
  16096. var stride = vbs[kind].getStrideSize();
  16097. for (var offset = 0; offset < stride; offset++) {
  16098. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16099. }
  16100. }
  16101. }
  16102. // Updating indices
  16103. for (index = 0; index < totalIndices; index += 3) {
  16104. indices[index] = index;
  16105. indices[index + 1] = index + 1;
  16106. indices[index + 2] = index + 2;
  16107. }
  16108. this.setIndices(indices);
  16109. // Updating vertex buffers
  16110. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16111. kind = kinds[kindIndex];
  16112. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16113. }
  16114. // Updating submeshes
  16115. this.releaseSubMeshes();
  16116. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16117. var previousOne = previousSubmeshes[submeshIndex];
  16118. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16119. }
  16120. this._unIndexed = true;
  16121. this.synchronizeInstances();
  16122. };
  16123. // will inverse faces orientations, and invert normals too if specified
  16124. Mesh.prototype.flipFaces = function (flipNormals) {
  16125. if (flipNormals === void 0) { flipNormals = false; }
  16126. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16127. var i;
  16128. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16129. for (i = 0; i < vertex_data.normals.length; i++) {
  16130. vertex_data.normals[i] *= -1;
  16131. }
  16132. }
  16133. var temp;
  16134. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16135. // reassign indices
  16136. temp = vertex_data.indices[i + 1];
  16137. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16138. vertex_data.indices[i + 2] = temp;
  16139. }
  16140. vertex_data.applyToMesh(this);
  16141. };
  16142. // Instances
  16143. Mesh.prototype.createInstance = function (name) {
  16144. return new BABYLON.InstancedMesh(name, this);
  16145. };
  16146. Mesh.prototype.synchronizeInstances = function () {
  16147. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16148. var instance = this.instances[instanceIndex];
  16149. instance._syncSubMeshes();
  16150. }
  16151. };
  16152. /**
  16153. * Simplify the mesh according to the given array of settings.
  16154. * Function will return immediately and will simplify async.
  16155. * @param settings a collection of simplification settings.
  16156. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16157. * @param type the type of simplification to run.
  16158. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16159. */
  16160. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16161. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16162. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16163. this.getScene().simplificationQueue.addTask({
  16164. settings: settings,
  16165. parallelProcessing: parallelProcessing,
  16166. mesh: this,
  16167. simplificationType: simplificationType,
  16168. successCallback: successCallback
  16169. });
  16170. };
  16171. /**
  16172. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16173. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16174. * This should be used together with the simplification to avoid disappearing triangles.
  16175. * @param successCallback an optional success callback to be called after the optimization finished.
  16176. */
  16177. Mesh.prototype.optimizeIndices = function (successCallback) {
  16178. var _this = this;
  16179. var indices = this.getIndices();
  16180. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16181. var vectorPositions = [];
  16182. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16183. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16184. }
  16185. var dupes = [];
  16186. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16187. var realPos = vectorPositions.length - 1 - iteration;
  16188. var testedPosition = vectorPositions[realPos];
  16189. for (var j = 0; j < realPos; ++j) {
  16190. var againstPosition = vectorPositions[j];
  16191. if (testedPosition.equals(againstPosition)) {
  16192. dupes[realPos] = j;
  16193. break;
  16194. }
  16195. }
  16196. }, function () {
  16197. for (var i = 0; i < indices.length; ++i) {
  16198. indices[i] = dupes[indices[i]] || indices[i];
  16199. }
  16200. //indices are now reordered
  16201. var originalSubMeshes = _this.subMeshes.slice(0);
  16202. _this.setIndices(indices);
  16203. _this.subMeshes = originalSubMeshes;
  16204. if (successCallback) {
  16205. successCallback(_this);
  16206. }
  16207. });
  16208. };
  16209. // Statics
  16210. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16211. var mesh = new Mesh(parsedMesh.name, scene);
  16212. mesh.id = parsedMesh.id;
  16213. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16214. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16215. if (parsedMesh.rotationQuaternion) {
  16216. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16217. }
  16218. else if (parsedMesh.rotation) {
  16219. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16220. }
  16221. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16222. if (parsedMesh.localMatrix) {
  16223. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16224. }
  16225. else if (parsedMesh.pivotMatrix) {
  16226. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16227. }
  16228. mesh.setEnabled(parsedMesh.isEnabled);
  16229. mesh.isVisible = parsedMesh.isVisible;
  16230. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16231. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16232. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16233. if (parsedMesh.applyFog !== undefined) {
  16234. mesh.applyFog = parsedMesh.applyFog;
  16235. }
  16236. if (parsedMesh.pickable !== undefined) {
  16237. mesh.isPickable = parsedMesh.pickable;
  16238. }
  16239. if (parsedMesh.alphaIndex !== undefined) {
  16240. mesh.alphaIndex = parsedMesh.alphaIndex;
  16241. }
  16242. mesh.receiveShadows = parsedMesh.receiveShadows;
  16243. mesh.billboardMode = parsedMesh.billboardMode;
  16244. if (parsedMesh.visibility !== undefined) {
  16245. mesh.visibility = parsedMesh.visibility;
  16246. }
  16247. mesh.checkCollisions = parsedMesh.checkCollisions;
  16248. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16249. // freezeWorldMatrix
  16250. if (parsedMesh.freezeWorldMatrix) {
  16251. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16252. }
  16253. // Parent
  16254. if (parsedMesh.parentId) {
  16255. mesh._waitingParentId = parsedMesh.parentId;
  16256. }
  16257. // Actions
  16258. if (parsedMesh.actions !== undefined) {
  16259. mesh._waitingActions = parsedMesh.actions;
  16260. }
  16261. // Geometry
  16262. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16263. if (parsedMesh.delayLoadingFile) {
  16264. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16265. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16266. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16267. if (parsedMesh._binaryInfo) {
  16268. mesh._binaryInfo = parsedMesh._binaryInfo;
  16269. }
  16270. mesh._delayInfo = [];
  16271. if (parsedMesh.hasUVs) {
  16272. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16273. }
  16274. if (parsedMesh.hasUVs2) {
  16275. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16276. }
  16277. if (parsedMesh.hasUVs3) {
  16278. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16279. }
  16280. if (parsedMesh.hasUVs4) {
  16281. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16282. }
  16283. if (parsedMesh.hasUVs5) {
  16284. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16285. }
  16286. if (parsedMesh.hasUVs6) {
  16287. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16288. }
  16289. if (parsedMesh.hasColors) {
  16290. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16291. }
  16292. if (parsedMesh.hasMatricesIndices) {
  16293. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16294. }
  16295. if (parsedMesh.hasMatricesWeights) {
  16296. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16297. }
  16298. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16299. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16300. mesh._checkDelayState();
  16301. }
  16302. }
  16303. else {
  16304. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16305. }
  16306. // Material
  16307. if (parsedMesh.materialId) {
  16308. mesh.setMaterialByID(parsedMesh.materialId);
  16309. }
  16310. else {
  16311. mesh.material = null;
  16312. }
  16313. // Skeleton
  16314. if (parsedMesh.skeletonId > -1) {
  16315. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16316. if (parsedMesh.numBoneInfluencers) {
  16317. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16318. }
  16319. }
  16320. // Animations
  16321. if (parsedMesh.animations) {
  16322. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16323. var parsedAnimation = parsedMesh.animations[animationIndex];
  16324. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16325. }
  16326. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16327. }
  16328. if (parsedMesh.autoAnimate) {
  16329. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16330. }
  16331. // Layer Mask
  16332. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16333. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16334. }
  16335. else {
  16336. mesh.layerMask = 0x0FFFFFFF;
  16337. }
  16338. // Instances
  16339. if (parsedMesh.instances) {
  16340. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16341. var parsedInstance = parsedMesh.instances[index];
  16342. var instance = mesh.createInstance(parsedInstance.name);
  16343. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16344. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16345. if (parsedInstance.rotationQuaternion) {
  16346. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16347. }
  16348. else if (parsedInstance.rotation) {
  16349. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16350. }
  16351. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16352. instance.checkCollisions = mesh.checkCollisions;
  16353. if (parsedMesh.animations) {
  16354. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16355. parsedAnimation = parsedMesh.animations[animationIndex];
  16356. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16357. }
  16358. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16359. }
  16360. }
  16361. }
  16362. return mesh;
  16363. };
  16364. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16365. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16366. pathArray: pathArray,
  16367. closeArray: closeArray,
  16368. closePath: closePath,
  16369. offset: offset,
  16370. updatable: updatable,
  16371. sideOrientation: sideOrientation,
  16372. instance: instance
  16373. }, scene);
  16374. };
  16375. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16376. var options = {
  16377. radius: radius,
  16378. tessellation: tessellation,
  16379. sideOrientation: sideOrientation,
  16380. updatable: updatable
  16381. };
  16382. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16383. };
  16384. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16385. var options = {
  16386. size: size,
  16387. sideOrientation: sideOrientation,
  16388. updatable: updatable
  16389. };
  16390. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16391. };
  16392. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16393. var options = {
  16394. segments: segments,
  16395. diameterX: diameter,
  16396. diameterY: diameter,
  16397. diameterZ: diameter,
  16398. sideOrientation: sideOrientation,
  16399. updatable: updatable
  16400. };
  16401. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16402. };
  16403. // Cylinder and cone
  16404. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16405. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16406. if (scene !== undefined) {
  16407. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16408. updatable = scene;
  16409. }
  16410. scene = subdivisions;
  16411. subdivisions = 1;
  16412. }
  16413. var options = {
  16414. height: height,
  16415. diameterTop: diameterTop,
  16416. diameterBottom: diameterBottom,
  16417. tessellation: tessellation,
  16418. subdivisions: subdivisions,
  16419. sideOrientation: sideOrientation,
  16420. updatable: updatable
  16421. };
  16422. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16423. };
  16424. // Torus (Code from SharpDX.org)
  16425. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16426. var options = {
  16427. diameter: diameter,
  16428. thickness: thickness,
  16429. tessellation: tessellation,
  16430. sideOrientation: sideOrientation,
  16431. updatable: updatable
  16432. };
  16433. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16434. };
  16435. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16436. var options = {
  16437. radius: radius,
  16438. tube: tube,
  16439. radialSegments: radialSegments,
  16440. tubularSegments: tubularSegments,
  16441. p: p,
  16442. q: q,
  16443. sideOrientation: sideOrientation,
  16444. updatable: updatable
  16445. };
  16446. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16447. };
  16448. // Lines
  16449. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16450. var options = {
  16451. points: points,
  16452. updatable: updatable,
  16453. instance: instance
  16454. };
  16455. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16456. };
  16457. // Dashed Lines
  16458. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16459. var options = {
  16460. points: points,
  16461. dashSize: dashSize,
  16462. gapSize: gapSize,
  16463. dashNb: dashNb,
  16464. updatable: updatable
  16465. };
  16466. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16467. };
  16468. // Extrusion
  16469. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16470. var options = {
  16471. shape: shape,
  16472. path: path,
  16473. scale: scale,
  16474. rotation: rotation,
  16475. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16476. sideOrientation: sideOrientation,
  16477. instance: instance,
  16478. updatable: updatable
  16479. };
  16480. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16481. };
  16482. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16483. var options = {
  16484. shape: shape,
  16485. path: path,
  16486. scaleFunction: scaleFunction,
  16487. rotationFunction: rotationFunction,
  16488. ribbonCloseArray: ribbonCloseArray,
  16489. ribbonClosePath: ribbonClosePath,
  16490. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16491. sideOrientation: sideOrientation,
  16492. instance: instance,
  16493. updatable: updatable
  16494. };
  16495. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16496. };
  16497. // Lathe
  16498. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16499. var options = {
  16500. shape: shape,
  16501. radius: radius,
  16502. tessellation: tessellation,
  16503. sideOrientation: sideOrientation,
  16504. updatable: updatable
  16505. };
  16506. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16507. };
  16508. // Plane & ground
  16509. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16510. var options = {
  16511. size: size,
  16512. width: size,
  16513. height: size,
  16514. sideOrientation: sideOrientation,
  16515. updatable: updatable
  16516. };
  16517. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16518. };
  16519. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16520. var options = {
  16521. width: width,
  16522. height: height,
  16523. subdivisions: subdivisions,
  16524. updatable: updatable
  16525. };
  16526. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16527. };
  16528. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16529. var options = {
  16530. xmin: xmin,
  16531. zmin: zmin,
  16532. xmax: xmax,
  16533. zmax: zmax,
  16534. subdivisions: subdivisions,
  16535. precision: precision,
  16536. updatable: updatable
  16537. };
  16538. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16539. };
  16540. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16541. var options = {
  16542. width: width,
  16543. height: height,
  16544. subdivisions: subdivisions,
  16545. minHeight: minHeight,
  16546. maxHeight: maxHeight,
  16547. updatable: updatable,
  16548. onReady: onReady
  16549. };
  16550. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16551. };
  16552. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16553. var options = {
  16554. path: path,
  16555. radius: radius,
  16556. tessellation: tessellation,
  16557. radiusFunction: radiusFunction,
  16558. arc: 1,
  16559. cap: cap,
  16560. updatable: updatable,
  16561. sideOrientation: sideOrientation,
  16562. instance: instance
  16563. };
  16564. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16565. };
  16566. Mesh.CreatePolyhedron = function (name, options, scene) {
  16567. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16568. };
  16569. Mesh.CreateIcoSphere = function (name, options, scene) {
  16570. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16571. };
  16572. // Decals
  16573. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16574. var options = {
  16575. position: position,
  16576. normal: normal,
  16577. size: size,
  16578. angle: angle
  16579. };
  16580. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16581. };
  16582. // Skeletons
  16583. /**
  16584. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16585. */
  16586. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16587. var source;
  16588. if (!this._sourcePositions) {
  16589. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16590. this._sourcePositions = new Float32Array(source);
  16591. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16592. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16593. }
  16594. }
  16595. return this._sourcePositions;
  16596. };
  16597. /**
  16598. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16599. */
  16600. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16601. var source;
  16602. if (!this._sourceNormals) {
  16603. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16604. this._sourceNormals = new Float32Array(source);
  16605. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16606. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16607. }
  16608. }
  16609. return this._sourceNormals;
  16610. };
  16611. /**
  16612. * Update the vertex buffers by applying transformation from the bones
  16613. * @param {skeleton} skeleton to apply
  16614. */
  16615. Mesh.prototype.applySkeleton = function (skeleton) {
  16616. if (!this.geometry) {
  16617. return;
  16618. }
  16619. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16620. return;
  16621. }
  16622. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16623. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16624. return this;
  16625. }
  16626. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16627. return this;
  16628. }
  16629. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16630. return this;
  16631. }
  16632. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16633. return this;
  16634. }
  16635. if (!this._sourcePositions) {
  16636. this.setPositionsForCPUSkinning();
  16637. }
  16638. if (!this._sourceNormals) {
  16639. this.setNormalsForCPUSkinning();
  16640. }
  16641. // positionsData checks for not being Float32Array will only pass at most once
  16642. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16643. if (!(positionsData instanceof Float32Array)) {
  16644. positionsData = new Float32Array(positionsData);
  16645. }
  16646. // normalsData checks for not being Float32Array will only pass at most once
  16647. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16648. if (!(normalsData instanceof Float32Array)) {
  16649. normalsData = new Float32Array(normalsData);
  16650. }
  16651. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16652. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16653. var needExtras = this.numBoneInfluencers > 4;
  16654. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16655. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16656. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16657. var tempVector3 = BABYLON.Vector3.Zero();
  16658. var finalMatrix = new BABYLON.Matrix();
  16659. var tempMatrix = new BABYLON.Matrix();
  16660. var matWeightIdx = 0;
  16661. var inf;
  16662. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16663. var weight;
  16664. for (inf = 0; inf < 4; inf++) {
  16665. weight = matricesWeightsData[matWeightIdx + inf];
  16666. if (weight > 0) {
  16667. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16668. finalMatrix.addToSelf(tempMatrix);
  16669. }
  16670. else
  16671. break;
  16672. }
  16673. if (needExtras) {
  16674. for (inf = 0; inf < 4; inf++) {
  16675. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16676. if (weight > 0) {
  16677. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16678. finalMatrix.addToSelf(tempMatrix);
  16679. }
  16680. else
  16681. break;
  16682. }
  16683. }
  16684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16685. tempVector3.toArray(positionsData, index);
  16686. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16687. tempVector3.toArray(normalsData, index);
  16688. finalMatrix.reset();
  16689. }
  16690. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16691. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16692. return this;
  16693. };
  16694. // Tools
  16695. Mesh.MinMax = function (meshes) {
  16696. var minVector = null;
  16697. var maxVector = null;
  16698. for (var i in meshes) {
  16699. var mesh = meshes[i];
  16700. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16701. if (!minVector) {
  16702. minVector = boundingBox.minimumWorld;
  16703. maxVector = boundingBox.maximumWorld;
  16704. continue;
  16705. }
  16706. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16707. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16708. }
  16709. return {
  16710. min: minVector,
  16711. max: maxVector
  16712. };
  16713. };
  16714. Mesh.Center = function (meshesOrMinMaxVector) {
  16715. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16716. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16717. };
  16718. /**
  16719. * Merge the array of meshes into a single mesh for performance reasons.
  16720. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16721. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16722. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16723. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16724. */
  16725. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16726. if (disposeSource === void 0) { disposeSource = true; }
  16727. var index;
  16728. if (!allow32BitsIndices) {
  16729. var totalVertices = 0;
  16730. // Counting vertices
  16731. for (index = 0; index < meshes.length; index++) {
  16732. if (meshes[index]) {
  16733. totalVertices += meshes[index].getTotalVertices();
  16734. if (totalVertices > 65536) {
  16735. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16736. return null;
  16737. }
  16738. }
  16739. }
  16740. }
  16741. // Merge
  16742. var vertexData;
  16743. var otherVertexData;
  16744. var source;
  16745. for (index = 0; index < meshes.length; index++) {
  16746. if (meshes[index]) {
  16747. meshes[index].computeWorldMatrix(true);
  16748. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16749. otherVertexData.transform(meshes[index].getWorldMatrix());
  16750. if (vertexData) {
  16751. vertexData.merge(otherVertexData);
  16752. }
  16753. else {
  16754. vertexData = otherVertexData;
  16755. source = meshes[index];
  16756. }
  16757. }
  16758. }
  16759. if (!meshSubclass) {
  16760. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16761. }
  16762. vertexData.applyToMesh(meshSubclass);
  16763. // Setting properties
  16764. meshSubclass.material = source.material;
  16765. meshSubclass.checkCollisions = source.checkCollisions;
  16766. // Cleaning
  16767. if (disposeSource) {
  16768. for (index = 0; index < meshes.length; index++) {
  16769. if (meshes[index]) {
  16770. meshes[index].dispose();
  16771. }
  16772. }
  16773. }
  16774. return meshSubclass;
  16775. };
  16776. // Consts
  16777. Mesh._FRONTSIDE = 0;
  16778. Mesh._BACKSIDE = 1;
  16779. Mesh._DOUBLESIDE = 2;
  16780. Mesh._DEFAULTSIDE = 0;
  16781. Mesh._NO_CAP = 0;
  16782. Mesh._CAP_START = 1;
  16783. Mesh._CAP_END = 2;
  16784. Mesh._CAP_ALL = 3;
  16785. return Mesh;
  16786. })(BABYLON.AbstractMesh);
  16787. BABYLON.Mesh = Mesh;
  16788. })(BABYLON || (BABYLON = {}));
  16789. var BABYLON;
  16790. (function (BABYLON) {
  16791. var SubMesh = (function () {
  16792. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16793. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16794. this.materialIndex = materialIndex;
  16795. this.verticesStart = verticesStart;
  16796. this.verticesCount = verticesCount;
  16797. this.indexStart = indexStart;
  16798. this.indexCount = indexCount;
  16799. this._renderId = 0;
  16800. this._mesh = mesh;
  16801. this._renderingMesh = renderingMesh || mesh;
  16802. mesh.subMeshes.push(this);
  16803. this._trianglePlanes = [];
  16804. this._id = mesh.subMeshes.length - 1;
  16805. if (createBoundingBox) {
  16806. this.refreshBoundingInfo();
  16807. mesh.computeWorldMatrix(true);
  16808. }
  16809. }
  16810. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16811. get: function () {
  16812. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16813. },
  16814. enumerable: true,
  16815. configurable: true
  16816. });
  16817. SubMesh.prototype.getBoundingInfo = function () {
  16818. if (this.IsGlobal) {
  16819. return this._mesh.getBoundingInfo();
  16820. }
  16821. return this._boundingInfo;
  16822. };
  16823. SubMesh.prototype.getMesh = function () {
  16824. return this._mesh;
  16825. };
  16826. SubMesh.prototype.getRenderingMesh = function () {
  16827. return this._renderingMesh;
  16828. };
  16829. SubMesh.prototype.getMaterial = function () {
  16830. var rootMaterial = this._renderingMesh.material;
  16831. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16832. var multiMaterial = rootMaterial;
  16833. return multiMaterial.getSubMaterial(this.materialIndex);
  16834. }
  16835. if (!rootMaterial) {
  16836. return this._mesh.getScene().defaultMaterial;
  16837. }
  16838. return rootMaterial;
  16839. };
  16840. // Methods
  16841. SubMesh.prototype.refreshBoundingInfo = function () {
  16842. this._lastColliderWorldVertices = null;
  16843. if (this.IsGlobal) {
  16844. return;
  16845. }
  16846. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16847. if (!data) {
  16848. this._boundingInfo = this._mesh._boundingInfo;
  16849. return;
  16850. }
  16851. var indices = this._renderingMesh.getIndices();
  16852. var extend;
  16853. //is this the only submesh?
  16854. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16855. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16856. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16857. }
  16858. else {
  16859. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16860. }
  16861. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16862. };
  16863. SubMesh.prototype._checkCollision = function (collider) {
  16864. return this.getBoundingInfo()._checkCollision(collider);
  16865. };
  16866. SubMesh.prototype.updateBoundingInfo = function (world) {
  16867. if (!this.getBoundingInfo()) {
  16868. this.refreshBoundingInfo();
  16869. }
  16870. this.getBoundingInfo().update(world);
  16871. };
  16872. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16873. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16874. };
  16875. SubMesh.prototype.render = function (enableAlphaMode) {
  16876. this._renderingMesh.render(this, enableAlphaMode);
  16877. };
  16878. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16879. if (!this._linesIndexBuffer) {
  16880. var linesIndices = [];
  16881. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16882. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16883. }
  16884. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16885. this.linesIndexCount = linesIndices.length;
  16886. }
  16887. return this._linesIndexBuffer;
  16888. };
  16889. SubMesh.prototype.canIntersects = function (ray) {
  16890. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16891. };
  16892. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16893. var intersectInfo = null;
  16894. // Triangles test
  16895. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16896. var p0 = positions[indices[index]];
  16897. var p1 = positions[indices[index + 1]];
  16898. var p2 = positions[indices[index + 2]];
  16899. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16900. if (currentIntersectInfo) {
  16901. if (currentIntersectInfo.distance < 0) {
  16902. continue;
  16903. }
  16904. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16905. intersectInfo = currentIntersectInfo;
  16906. intersectInfo.faceId = index / 3;
  16907. if (fastCheck) {
  16908. break;
  16909. }
  16910. }
  16911. }
  16912. }
  16913. return intersectInfo;
  16914. };
  16915. // Clone
  16916. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16917. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16918. if (!this.IsGlobal) {
  16919. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16920. }
  16921. return result;
  16922. };
  16923. // Dispose
  16924. SubMesh.prototype.dispose = function () {
  16925. if (this._linesIndexBuffer) {
  16926. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16927. this._linesIndexBuffer = null;
  16928. }
  16929. // Remove from mesh
  16930. var index = this._mesh.subMeshes.indexOf(this);
  16931. this._mesh.subMeshes.splice(index, 1);
  16932. };
  16933. // Statics
  16934. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16935. var minVertexIndex = Number.MAX_VALUE;
  16936. var maxVertexIndex = -Number.MAX_VALUE;
  16937. renderingMesh = renderingMesh || mesh;
  16938. var indices = renderingMesh.getIndices();
  16939. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16940. var vertexIndex = indices[index];
  16941. if (vertexIndex < minVertexIndex)
  16942. minVertexIndex = vertexIndex;
  16943. if (vertexIndex > maxVertexIndex)
  16944. maxVertexIndex = vertexIndex;
  16945. }
  16946. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16947. };
  16948. return SubMesh;
  16949. })();
  16950. BABYLON.SubMesh = SubMesh;
  16951. })(BABYLON || (BABYLON = {}));
  16952. var BABYLON;
  16953. (function (BABYLON) {
  16954. var MeshBuilder = (function () {
  16955. function MeshBuilder() {
  16956. }
  16957. MeshBuilder.CreateBox = function (name, options, scene) {
  16958. var box = new BABYLON.Mesh(name, scene);
  16959. var vertexData = BABYLON.VertexData.CreateBox(options);
  16960. vertexData.applyToMesh(box, options.updatable);
  16961. return box;
  16962. };
  16963. MeshBuilder.CreateSphere = function (name, options, scene) {
  16964. var sphere = new BABYLON.Mesh(name, scene);
  16965. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16966. vertexData.applyToMesh(sphere, options.updatable);
  16967. return sphere;
  16968. };
  16969. MeshBuilder.CreateDisc = function (name, options, scene) {
  16970. var disc = new BABYLON.Mesh(name, scene);
  16971. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16972. vertexData.applyToMesh(disc, options.updatable);
  16973. return disc;
  16974. };
  16975. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16976. var sphere = new BABYLON.Mesh(name, scene);
  16977. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16978. vertexData.applyToMesh(sphere, options.updatable);
  16979. return sphere;
  16980. };
  16981. ;
  16982. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16983. var pathArray = options.pathArray;
  16984. var closeArray = options.closeArray;
  16985. var closePath = options.closePath;
  16986. var offset = options.offset;
  16987. var sideOrientation = options.sideOrientation;
  16988. var instance = options.instance;
  16989. var updatable = options.updatable;
  16990. if (instance) {
  16991. // positionFunction : ribbon case
  16992. // only pathArray and sideOrientation parameters are taken into account for positions update
  16993. var positionFunction = function (positions) {
  16994. var minlg = pathArray[0].length;
  16995. var i = 0;
  16996. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16997. for (var si = 1; si <= ns; si++) {
  16998. for (var p = 0; p < pathArray.length; p++) {
  16999. var path = pathArray[p];
  17000. var l = path.length;
  17001. minlg = (minlg < l) ? minlg : l;
  17002. var j = 0;
  17003. while (j < minlg) {
  17004. positions[i] = path[j].x;
  17005. positions[i + 1] = path[j].y;
  17006. positions[i + 2] = path[j].z;
  17007. j++;
  17008. i += 3;
  17009. }
  17010. if (instance._closePath) {
  17011. positions[i] = path[0].x;
  17012. positions[i + 1] = path[0].y;
  17013. positions[i + 2] = path[0].z;
  17014. i += 3;
  17015. }
  17016. }
  17017. }
  17018. };
  17019. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17020. positionFunction(positions);
  17021. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17022. if (!(instance.areNormalsFrozen)) {
  17023. var indices = instance.getIndices();
  17024. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17025. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17026. if (instance._closePath) {
  17027. var indexFirst = 0;
  17028. var indexLast = 0;
  17029. for (var p = 0; p < pathArray.length; p++) {
  17030. indexFirst = instance._idx[p] * 3;
  17031. if (p + 1 < pathArray.length) {
  17032. indexLast = (instance._idx[p + 1] - 1) * 3;
  17033. }
  17034. else {
  17035. indexLast = normals.length - 3;
  17036. }
  17037. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  17038. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  17039. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  17040. normals[indexLast] = normals[indexFirst];
  17041. normals[indexLast + 1] = normals[indexFirst + 1];
  17042. normals[indexLast + 2] = normals[indexFirst + 2];
  17043. }
  17044. }
  17045. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17046. }
  17047. return instance;
  17048. }
  17049. else {
  17050. var ribbon = new BABYLON.Mesh(name, scene);
  17051. ribbon.sideOrientation = sideOrientation;
  17052. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17053. if (closePath) {
  17054. ribbon._idx = vertexData._idx;
  17055. }
  17056. ribbon._closePath = closePath;
  17057. ribbon._closeArray = closeArray;
  17058. vertexData.applyToMesh(ribbon, updatable);
  17059. return ribbon;
  17060. }
  17061. };
  17062. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17063. var cylinder = new BABYLON.Mesh(name, scene);
  17064. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17065. vertexData.applyToMesh(cylinder, options.updatable);
  17066. return cylinder;
  17067. };
  17068. MeshBuilder.CreateTorus = function (name, options, scene) {
  17069. var torus = new BABYLON.Mesh(name, scene);
  17070. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17071. vertexData.applyToMesh(torus, options.updatable);
  17072. return torus;
  17073. };
  17074. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17075. var torusKnot = new BABYLON.Mesh(name, scene);
  17076. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17077. vertexData.applyToMesh(torusKnot, options.updatable);
  17078. return torusKnot;
  17079. };
  17080. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17081. var instance = options.instance;
  17082. var lines = options.lines;
  17083. if (instance) {
  17084. var positionFunction = function (positions) {
  17085. var i = 0;
  17086. for (var l = 0; l < lines.length; l++) {
  17087. var points = lines[l];
  17088. for (var p = 0; p < points.length; p++) {
  17089. positions[i] = points[p].x;
  17090. positions[i + 1] = points[p].y;
  17091. positions[i + 2] = points[p].z;
  17092. i += 3;
  17093. }
  17094. }
  17095. };
  17096. instance.updateMeshPositions(positionFunction, false);
  17097. return instance;
  17098. }
  17099. // line system creation
  17100. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17101. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17102. vertexData.applyToMesh(lineSystem, options.updatable);
  17103. return lineSystem;
  17104. };
  17105. MeshBuilder.CreateLines = function (name, options, scene) {
  17106. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17107. return lines;
  17108. };
  17109. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17110. var points = options.points;
  17111. var instance = options.instance;
  17112. var gapSize = options.gapSize;
  17113. var dashNb = options.dashNb;
  17114. var dashSize = options.dashSize;
  17115. if (instance) {
  17116. var positionFunction = function (positions) {
  17117. var curvect = BABYLON.Vector3.Zero();
  17118. var nbSeg = positions.length / 6;
  17119. var lg = 0;
  17120. var nb = 0;
  17121. var shft = 0;
  17122. var dashshft = 0;
  17123. var curshft = 0;
  17124. var p = 0;
  17125. var i = 0;
  17126. var j = 0;
  17127. for (i = 0; i < points.length - 1; i++) {
  17128. points[i + 1].subtractToRef(points[i], curvect);
  17129. lg += curvect.length();
  17130. }
  17131. shft = lg / nbSeg;
  17132. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17133. for (i = 0; i < points.length - 1; i++) {
  17134. points[i + 1].subtractToRef(points[i], curvect);
  17135. nb = Math.floor(curvect.length() / shft);
  17136. curvect.normalize();
  17137. j = 0;
  17138. while (j < nb && p < positions.length) {
  17139. curshft = shft * j;
  17140. positions[p] = points[i].x + curshft * curvect.x;
  17141. positions[p + 1] = points[i].y + curshft * curvect.y;
  17142. positions[p + 2] = points[i].z + curshft * curvect.z;
  17143. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17144. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17145. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17146. p += 6;
  17147. j++;
  17148. }
  17149. }
  17150. while (p < positions.length) {
  17151. positions[p] = points[i].x;
  17152. positions[p + 1] = points[i].y;
  17153. positions[p + 2] = points[i].z;
  17154. p += 3;
  17155. }
  17156. };
  17157. instance.updateMeshPositions(positionFunction, false);
  17158. return instance;
  17159. }
  17160. // dashed lines creation
  17161. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17162. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17163. vertexData.applyToMesh(dashedLines, options.updatable);
  17164. dashedLines.dashSize = dashSize;
  17165. dashedLines.gapSize = gapSize;
  17166. return dashedLines;
  17167. };
  17168. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17169. var path = options.path;
  17170. var shape = options.shape;
  17171. var scale = options.scale || 1;
  17172. var rotation = options.rotation || 0;
  17173. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17174. var updatable = options.updatable;
  17175. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17176. var instance = options.instance;
  17177. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17178. };
  17179. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17180. var path = options.path;
  17181. var shape = options.shape;
  17182. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17183. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17184. var ribbonCloseArray = options.ribbonCloseArray || false;
  17185. var ribbonClosePath = options.ribbonClosePath || false;
  17186. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17187. var updatable = options.updatable;
  17188. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17189. var instance = options.instance;
  17190. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17191. };
  17192. MeshBuilder.CreateLathe = function (name, options, scene) {
  17193. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17194. var closed = (options.closed === undefined) ? true : options.closed;
  17195. var shape = options.shape;
  17196. var radius = options.radius || 1;
  17197. var tessellation = options.tessellation || 64;
  17198. var updatable = options.updatable;
  17199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17200. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17201. var pi2 = Math.PI * 2;
  17202. var paths = new Array();
  17203. var i = 0;
  17204. var p = 0;
  17205. var step = pi2 / tessellation * arc;
  17206. var rotated;
  17207. var path = new Array();
  17208. ;
  17209. for (i = 0; i <= tessellation; i++) {
  17210. var path = [];
  17211. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17212. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17213. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17214. }
  17215. for (p = 0; p < shape.length; p++) {
  17216. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17217. path.push(rotated);
  17218. }
  17219. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17220. 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));
  17221. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17222. }
  17223. paths.push(path);
  17224. }
  17225. // lathe ribbon
  17226. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17227. return lathe;
  17228. };
  17229. MeshBuilder.CreatePlane = function (name, options, scene) {
  17230. var plane = new BABYLON.Mesh(name, scene);
  17231. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17232. vertexData.applyToMesh(plane, options.updatable);
  17233. if (options.sourcePlane) {
  17234. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17235. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17236. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17237. plane.rotate(vectorProduct, product);
  17238. }
  17239. return plane;
  17240. };
  17241. MeshBuilder.CreateGround = function (name, options, scene) {
  17242. var ground = new BABYLON.GroundMesh(name, scene);
  17243. ground._setReady(false);
  17244. ground._subdivisions = options.subdivisions || 1;
  17245. ground._width = options.width || 1;
  17246. ground._height = options.height || 1;
  17247. ground._maxX = ground._width / 2;
  17248. ground._maxZ = ground._height / 2;
  17249. ground._minX = -ground._maxX;
  17250. ground._minZ = -ground._maxZ;
  17251. var vertexData = BABYLON.VertexData.CreateGround(options);
  17252. vertexData.applyToMesh(ground, options.updatable);
  17253. ground._setReady(true);
  17254. return ground;
  17255. };
  17256. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17257. var tiledGround = new BABYLON.Mesh(name, scene);
  17258. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17259. vertexData.applyToMesh(tiledGround, options.updatable);
  17260. return tiledGround;
  17261. };
  17262. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17263. var width = options.width || 10;
  17264. var height = options.height || 10;
  17265. var subdivisions = options.subdivisions || 1;
  17266. var minHeight = options.minHeight;
  17267. var maxHeight = options.maxHeight || 10;
  17268. var updatable = options.updatable;
  17269. var onReady = options.onReady;
  17270. var ground = new BABYLON.GroundMesh(name, scene);
  17271. ground._subdivisions = subdivisions;
  17272. ground._width = width;
  17273. ground._height = height;
  17274. ground._maxX = ground._width / 2;
  17275. ground._maxZ = ground._height / 2;
  17276. ground._minX = -ground._maxX;
  17277. ground._minZ = -ground._maxZ;
  17278. ground._setReady(false);
  17279. var onload = function (img) {
  17280. // Getting height map data
  17281. var canvas = document.createElement("canvas");
  17282. var context = canvas.getContext("2d");
  17283. var bufferWidth = img.width;
  17284. var bufferHeight = img.height;
  17285. canvas.width = bufferWidth;
  17286. canvas.height = bufferHeight;
  17287. context.drawImage(img, 0, 0);
  17288. // Create VertexData from map data
  17289. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17290. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17291. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17292. width: width, height: height,
  17293. subdivisions: subdivisions,
  17294. minHeight: minHeight, maxHeight: maxHeight,
  17295. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17296. });
  17297. vertexData.applyToMesh(ground, updatable);
  17298. ground._setReady(true);
  17299. //execute ready callback, if set
  17300. if (onReady) {
  17301. onReady(ground);
  17302. }
  17303. };
  17304. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17305. return ground;
  17306. };
  17307. MeshBuilder.CreateTube = function (name, options, scene) {
  17308. var path = options.path;
  17309. var radius = options.radius || 1;
  17310. var tessellation = options.tessellation || 64;
  17311. var radiusFunction = options.radiusFunction;
  17312. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17313. var updatable = options.updatable;
  17314. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17315. var instance = options.instance;
  17316. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17317. // tube geometry
  17318. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17319. var tangents = path3D.getTangents();
  17320. var normals = path3D.getNormals();
  17321. var distances = path3D.getDistances();
  17322. var pi2 = Math.PI * 2;
  17323. var step = pi2 / tessellation * arc;
  17324. var returnRadius = function () { return radius; };
  17325. var radiusFunctionFinal = radiusFunction || returnRadius;
  17326. var circlePath;
  17327. var rad;
  17328. var normal;
  17329. var rotated;
  17330. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17331. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17332. for (var i = 0; i < path.length; i++) {
  17333. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17334. circlePath = Array(); // current circle array
  17335. normal = normals[i]; // current normal
  17336. for (var t = 0; t < tessellation; t++) {
  17337. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17338. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17339. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17340. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17341. circlePath[t] = rotated;
  17342. }
  17343. circlePaths[index] = circlePath;
  17344. index++;
  17345. }
  17346. // cap
  17347. var capPath = function (nbPoints, pathIndex) {
  17348. var pointCap = Array();
  17349. for (var i = 0; i < nbPoints; i++) {
  17350. pointCap.push(path[pathIndex]);
  17351. }
  17352. return pointCap;
  17353. };
  17354. switch (cap) {
  17355. case BABYLON.Mesh.NO_CAP:
  17356. break;
  17357. case BABYLON.Mesh.CAP_START:
  17358. circlePaths[0] = capPath(tessellation, 0);
  17359. circlePaths[1] = circlePaths[2].slice(0);
  17360. break;
  17361. case BABYLON.Mesh.CAP_END:
  17362. circlePaths[index] = circlePaths[index - 1].slice(0);
  17363. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17364. break;
  17365. case BABYLON.Mesh.CAP_ALL:
  17366. circlePaths[0] = capPath(tessellation, 0);
  17367. circlePaths[1] = circlePaths[2].slice(0);
  17368. circlePaths[index] = circlePaths[index - 1].slice(0);
  17369. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17370. break;
  17371. default:
  17372. break;
  17373. }
  17374. return circlePaths;
  17375. };
  17376. var path3D;
  17377. var pathArray;
  17378. if (instance) {
  17379. var arc = options.arc || instance.arc;
  17380. path3D = (instance.path3D).update(path);
  17381. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17382. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17383. instance.path3D = path3D;
  17384. instance.pathArray = pathArray;
  17385. instance.arc = arc;
  17386. return instance;
  17387. }
  17388. // tube creation
  17389. path3D = new BABYLON.Path3D(path);
  17390. var newPathArray = new Array();
  17391. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17392. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17393. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17394. tube.pathArray = pathArray;
  17395. tube.path3D = path3D;
  17396. tube.tessellation = tessellation;
  17397. tube.cap = cap;
  17398. tube.arc = options.arc;
  17399. return tube;
  17400. };
  17401. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17402. var polyhedron = new BABYLON.Mesh(name, scene);
  17403. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17404. vertexData.applyToMesh(polyhedron, options.updatable);
  17405. return polyhedron;
  17406. };
  17407. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17408. var indices = sourceMesh.getIndices();
  17409. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17410. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17411. var position = options.position || BABYLON.Vector3.Zero();
  17412. var normal = options.normal || BABYLON.Vector3.Up();
  17413. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17414. var angle = options.angle || 0;
  17415. // Getting correct rotation
  17416. if (!normal) {
  17417. var target = new BABYLON.Vector3(0, 0, 1);
  17418. var camera = sourceMesh.getScene().activeCamera;
  17419. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17420. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17421. }
  17422. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17423. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17424. var pitch = Math.atan2(normal.y, len);
  17425. // Matrix
  17426. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17427. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17428. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17429. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17430. var vertexData = new BABYLON.VertexData();
  17431. vertexData.indices = [];
  17432. vertexData.positions = [];
  17433. vertexData.normals = [];
  17434. vertexData.uvs = [];
  17435. var currentVertexDataIndex = 0;
  17436. var extractDecalVector3 = function (indexId) {
  17437. var vertexId = indices[indexId];
  17438. var result = new BABYLON.PositionNormalVertex();
  17439. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17440. // Send vector to decal local world
  17441. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17442. // Get normal
  17443. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17444. return result;
  17445. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17446. var clip = function (vertices, axis) {
  17447. if (vertices.length === 0) {
  17448. return vertices;
  17449. }
  17450. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17451. var clipVertices = function (v0, v1) {
  17452. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17453. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17454. };
  17455. var result = new Array();
  17456. for (var index = 0; index < vertices.length; index += 3) {
  17457. var v1Out;
  17458. var v2Out;
  17459. var v3Out;
  17460. var total = 0;
  17461. var nV1, nV2, nV3, nV4;
  17462. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17463. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17464. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17465. v1Out = d1 > 0;
  17466. v2Out = d2 > 0;
  17467. v3Out = d3 > 0;
  17468. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17469. switch (total) {
  17470. case 0:
  17471. result.push(vertices[index]);
  17472. result.push(vertices[index + 1]);
  17473. result.push(vertices[index + 2]);
  17474. break;
  17475. case 1:
  17476. if (v1Out) {
  17477. nV1 = vertices[index + 1];
  17478. nV2 = vertices[index + 2];
  17479. nV3 = clipVertices(vertices[index], nV1);
  17480. nV4 = clipVertices(vertices[index], nV2);
  17481. }
  17482. if (v2Out) {
  17483. nV1 = vertices[index];
  17484. nV2 = vertices[index + 2];
  17485. nV3 = clipVertices(vertices[index + 1], nV1);
  17486. nV4 = clipVertices(vertices[index + 1], nV2);
  17487. result.push(nV3);
  17488. result.push(nV2.clone());
  17489. result.push(nV1.clone());
  17490. result.push(nV2.clone());
  17491. result.push(nV3.clone());
  17492. result.push(nV4);
  17493. break;
  17494. }
  17495. if (v3Out) {
  17496. nV1 = vertices[index];
  17497. nV2 = vertices[index + 1];
  17498. nV3 = clipVertices(vertices[index + 2], nV1);
  17499. nV4 = clipVertices(vertices[index + 2], nV2);
  17500. }
  17501. result.push(nV1.clone());
  17502. result.push(nV2.clone());
  17503. result.push(nV3);
  17504. result.push(nV4);
  17505. result.push(nV3.clone());
  17506. result.push(nV2.clone());
  17507. break;
  17508. case 2:
  17509. if (!v1Out) {
  17510. nV1 = vertices[index].clone();
  17511. nV2 = clipVertices(nV1, vertices[index + 1]);
  17512. nV3 = clipVertices(nV1, vertices[index + 2]);
  17513. result.push(nV1);
  17514. result.push(nV2);
  17515. result.push(nV3);
  17516. }
  17517. if (!v2Out) {
  17518. nV1 = vertices[index + 1].clone();
  17519. nV2 = clipVertices(nV1, vertices[index + 2]);
  17520. nV3 = clipVertices(nV1, vertices[index]);
  17521. result.push(nV1);
  17522. result.push(nV2);
  17523. result.push(nV3);
  17524. }
  17525. if (!v3Out) {
  17526. nV1 = vertices[index + 2].clone();
  17527. nV2 = clipVertices(nV1, vertices[index]);
  17528. nV3 = clipVertices(nV1, vertices[index + 1]);
  17529. result.push(nV1);
  17530. result.push(nV2);
  17531. result.push(nV3);
  17532. }
  17533. break;
  17534. case 3:
  17535. break;
  17536. }
  17537. }
  17538. return result;
  17539. };
  17540. for (var index = 0; index < indices.length; index += 3) {
  17541. var faceVertices = new Array();
  17542. faceVertices.push(extractDecalVector3(index));
  17543. faceVertices.push(extractDecalVector3(index + 1));
  17544. faceVertices.push(extractDecalVector3(index + 2));
  17545. // Clip
  17546. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17547. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17548. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17549. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17550. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17551. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17552. if (faceVertices.length === 0) {
  17553. continue;
  17554. }
  17555. // Add UVs and get back to world
  17556. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17557. var vertex = faceVertices[vIndex];
  17558. //TODO check for Int32Array
  17559. vertexData.indices.push(currentVertexDataIndex);
  17560. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17561. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17562. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17563. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17564. currentVertexDataIndex++;
  17565. }
  17566. }
  17567. // Return mesh
  17568. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17569. vertexData.applyToMesh(decal);
  17570. decal.position = position.clone();
  17571. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17572. return decal;
  17573. };
  17574. // Privates
  17575. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17576. // extrusion geometry
  17577. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17578. var tangents = path3D.getTangents();
  17579. var normals = path3D.getNormals();
  17580. var binormals = path3D.getBinormals();
  17581. var distances = path3D.getDistances();
  17582. var angle = 0;
  17583. var returnScale = function () { return scale; };
  17584. var returnRotation = function () { return rotation; };
  17585. var rotate = custom ? rotateFunction : returnRotation;
  17586. var scl = custom ? scaleFunction : returnScale;
  17587. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17588. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17589. for (var i = 0; i < curve.length; i++) {
  17590. var shapePath = new Array();
  17591. var angleStep = rotate(i, distances[i]);
  17592. var scaleRatio = scl(i, distances[i]);
  17593. for (var p = 0; p < shape.length; p++) {
  17594. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17595. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17596. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17597. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17598. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17599. shapePath[p] = rotated;
  17600. }
  17601. shapePaths[index] = shapePath;
  17602. angle += angleStep;
  17603. index++;
  17604. }
  17605. // cap
  17606. var capPath = function (shapePath) {
  17607. var pointCap = Array();
  17608. var barycenter = BABYLON.Vector3.Zero();
  17609. var i;
  17610. for (i = 0; i < shapePath.length; i++) {
  17611. barycenter.addInPlace(shapePath[i]);
  17612. }
  17613. barycenter.scaleInPlace(1 / shapePath.length);
  17614. for (i = 0; i < shapePath.length; i++) {
  17615. pointCap.push(barycenter);
  17616. }
  17617. return pointCap;
  17618. };
  17619. switch (cap) {
  17620. case BABYLON.Mesh.NO_CAP:
  17621. break;
  17622. case BABYLON.Mesh.CAP_START:
  17623. shapePaths[0] = capPath(shapePaths[2]);
  17624. shapePaths[1] = shapePaths[2].slice(0);
  17625. break;
  17626. case BABYLON.Mesh.CAP_END:
  17627. shapePaths[index] = shapePaths[index - 1];
  17628. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17629. break;
  17630. case BABYLON.Mesh.CAP_ALL:
  17631. shapePaths[0] = capPath(shapePaths[2]);
  17632. shapePaths[1] = shapePaths[2].slice(0);
  17633. shapePaths[index] = shapePaths[index - 1];
  17634. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17635. break;
  17636. default:
  17637. break;
  17638. }
  17639. return shapePaths;
  17640. };
  17641. var path3D;
  17642. var pathArray;
  17643. if (instance) {
  17644. path3D = (instance.path3D).update(curve);
  17645. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17646. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17647. return instance;
  17648. }
  17649. // extruded shape creation
  17650. path3D = new BABYLON.Path3D(curve);
  17651. var newShapePaths = new Array();
  17652. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17653. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17654. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17655. extrudedGeneric.pathArray = pathArray;
  17656. extrudedGeneric.path3D = path3D;
  17657. extrudedGeneric.cap = cap;
  17658. return extrudedGeneric;
  17659. };
  17660. return MeshBuilder;
  17661. })();
  17662. BABYLON.MeshBuilder = MeshBuilder;
  17663. })(BABYLON || (BABYLON = {}));
  17664. var BABYLON;
  17665. (function (BABYLON) {
  17666. var BaseTexture = (function () {
  17667. function BaseTexture(scene) {
  17668. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17669. this.hasAlpha = false;
  17670. this.getAlphaFromRGB = false;
  17671. this.level = 1;
  17672. this.isCube = false;
  17673. this.isRenderTarget = false;
  17674. this.animations = new Array();
  17675. this.coordinatesIndex = 0;
  17676. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17677. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17678. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17679. this.anisotropicFilteringLevel = 4;
  17680. this._scene = scene;
  17681. this._scene.textures.push(this);
  17682. }
  17683. BaseTexture.prototype.getScene = function () {
  17684. return this._scene;
  17685. };
  17686. BaseTexture.prototype.getTextureMatrix = function () {
  17687. return null;
  17688. };
  17689. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17690. return null;
  17691. };
  17692. BaseTexture.prototype.getInternalTexture = function () {
  17693. return this._texture;
  17694. };
  17695. BaseTexture.prototype.isReady = function () {
  17696. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17697. return true;
  17698. }
  17699. if (this._texture) {
  17700. return this._texture.isReady;
  17701. }
  17702. return false;
  17703. };
  17704. BaseTexture.prototype.getSize = function () {
  17705. if (this._texture._width) {
  17706. return { width: this._texture._width, height: this._texture._height };
  17707. }
  17708. if (this._texture._size) {
  17709. return { width: this._texture._size, height: this._texture._size };
  17710. }
  17711. return { width: 0, height: 0 };
  17712. };
  17713. BaseTexture.prototype.getBaseSize = function () {
  17714. if (!this.isReady())
  17715. return { width: 0, height: 0 };
  17716. if (this._texture._size) {
  17717. return { width: this._texture._size, height: this._texture._size };
  17718. }
  17719. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17720. };
  17721. BaseTexture.prototype.scale = function (ratio) {
  17722. };
  17723. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17724. get: function () {
  17725. return false;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17731. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17732. for (var index = 0; index < texturesCache.length; index++) {
  17733. var texturesCacheEntry = texturesCache[index];
  17734. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17735. texturesCache.splice(index, 1);
  17736. return;
  17737. }
  17738. }
  17739. };
  17740. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17741. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17742. for (var index = 0; index < texturesCache.length; index++) {
  17743. var texturesCacheEntry = texturesCache[index];
  17744. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17745. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17746. texturesCacheEntry.references++;
  17747. return texturesCacheEntry;
  17748. }
  17749. }
  17750. }
  17751. return null;
  17752. };
  17753. BaseTexture.prototype.delayLoad = function () {
  17754. };
  17755. BaseTexture.prototype.clone = function () {
  17756. return null;
  17757. };
  17758. BaseTexture.prototype.releaseInternalTexture = function () {
  17759. if (this._texture) {
  17760. this._scene.getEngine().releaseInternalTexture(this._texture);
  17761. delete this._texture;
  17762. }
  17763. };
  17764. BaseTexture.prototype.dispose = function () {
  17765. // Animations
  17766. this.getScene().stopAnimation(this);
  17767. // Remove from scene
  17768. var index = this._scene.textures.indexOf(this);
  17769. if (index >= 0) {
  17770. this._scene.textures.splice(index, 1);
  17771. }
  17772. if (this._texture === undefined) {
  17773. return;
  17774. }
  17775. // Release
  17776. this.releaseInternalTexture();
  17777. // Callback
  17778. if (this.onDispose) {
  17779. this.onDispose();
  17780. }
  17781. };
  17782. BaseTexture.prototype.serialize = function () {
  17783. var serializationObject = {};
  17784. if (!this.name) {
  17785. return null;
  17786. }
  17787. serializationObject.name = this.name;
  17788. serializationObject.hasAlpha = this.hasAlpha;
  17789. serializationObject.level = this.level;
  17790. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17791. serializationObject.coordinatesMode = this.coordinatesMode;
  17792. serializationObject.wrapU = this.wrapU;
  17793. serializationObject.wrapV = this.wrapV;
  17794. // Animations
  17795. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17796. return serializationObject;
  17797. };
  17798. return BaseTexture;
  17799. })();
  17800. BABYLON.BaseTexture = BaseTexture;
  17801. })(BABYLON || (BABYLON = {}));
  17802. var BABYLON;
  17803. (function (BABYLON) {
  17804. var Texture = (function (_super) {
  17805. __extends(Texture, _super);
  17806. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17807. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17808. if (onLoad === void 0) { onLoad = null; }
  17809. if (onError === void 0) { onError = null; }
  17810. if (buffer === void 0) { buffer = null; }
  17811. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17812. _super.call(this, scene);
  17813. this.uOffset = 0;
  17814. this.vOffset = 0;
  17815. this.uScale = 1.0;
  17816. this.vScale = 1.0;
  17817. this.uAng = 0;
  17818. this.vAng = 0;
  17819. this.wAng = 0;
  17820. this.name = url;
  17821. this.url = url;
  17822. this._noMipmap = noMipmap;
  17823. this._invertY = invertY;
  17824. this._samplingMode = samplingMode;
  17825. this._buffer = buffer;
  17826. this._deleteBuffer = deleteBuffer;
  17827. if (!url) {
  17828. return;
  17829. }
  17830. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17831. if (!this._texture) {
  17832. if (!scene.useDelayedTextureLoading) {
  17833. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17834. if (deleteBuffer) {
  17835. delete this._buffer;
  17836. }
  17837. }
  17838. else {
  17839. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17840. this._delayedOnLoad = onLoad;
  17841. this._delayedOnError = onError;
  17842. }
  17843. }
  17844. else {
  17845. BABYLON.Tools.SetImmediate(function () {
  17846. if (onLoad) {
  17847. onLoad();
  17848. }
  17849. });
  17850. }
  17851. }
  17852. Texture.prototype.delayLoad = function () {
  17853. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17854. return;
  17855. }
  17856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17857. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17858. if (!this._texture) {
  17859. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17860. if (this._deleteBuffer) {
  17861. delete this._buffer;
  17862. }
  17863. }
  17864. };
  17865. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17866. if (!this._texture) {
  17867. return;
  17868. }
  17869. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17870. };
  17871. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17872. x *= this.uScale;
  17873. y *= this.vScale;
  17874. x -= 0.5 * this.uScale;
  17875. y -= 0.5 * this.vScale;
  17876. z -= 0.5;
  17877. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17878. t.x += 0.5 * this.uScale + this.uOffset;
  17879. t.y += 0.5 * this.vScale + this.vOffset;
  17880. t.z += 0.5;
  17881. };
  17882. Texture.prototype.getTextureMatrix = function () {
  17883. if (this.uOffset === this._cachedUOffset &&
  17884. this.vOffset === this._cachedVOffset &&
  17885. this.uScale === this._cachedUScale &&
  17886. this.vScale === this._cachedVScale &&
  17887. this.uAng === this._cachedUAng &&
  17888. this.vAng === this._cachedVAng &&
  17889. this.wAng === this._cachedWAng) {
  17890. return this._cachedTextureMatrix;
  17891. }
  17892. this._cachedUOffset = this.uOffset;
  17893. this._cachedVOffset = this.vOffset;
  17894. this._cachedUScale = this.uScale;
  17895. this._cachedVScale = this.vScale;
  17896. this._cachedUAng = this.uAng;
  17897. this._cachedVAng = this.vAng;
  17898. this._cachedWAng = this.wAng;
  17899. if (!this._cachedTextureMatrix) {
  17900. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17901. this._rowGenerationMatrix = new BABYLON.Matrix();
  17902. this._t0 = BABYLON.Vector3.Zero();
  17903. this._t1 = BABYLON.Vector3.Zero();
  17904. this._t2 = BABYLON.Vector3.Zero();
  17905. }
  17906. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17907. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17908. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17909. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17910. this._t1.subtractInPlace(this._t0);
  17911. this._t2.subtractInPlace(this._t0);
  17912. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17913. this._cachedTextureMatrix.m[0] = this._t1.x;
  17914. this._cachedTextureMatrix.m[1] = this._t1.y;
  17915. this._cachedTextureMatrix.m[2] = this._t1.z;
  17916. this._cachedTextureMatrix.m[4] = this._t2.x;
  17917. this._cachedTextureMatrix.m[5] = this._t2.y;
  17918. this._cachedTextureMatrix.m[6] = this._t2.z;
  17919. this._cachedTextureMatrix.m[8] = this._t0.x;
  17920. this._cachedTextureMatrix.m[9] = this._t0.y;
  17921. this._cachedTextureMatrix.m[10] = this._t0.z;
  17922. return this._cachedTextureMatrix;
  17923. };
  17924. Texture.prototype.getReflectionTextureMatrix = function () {
  17925. if (this.uOffset === this._cachedUOffset &&
  17926. this.vOffset === this._cachedVOffset &&
  17927. this.uScale === this._cachedUScale &&
  17928. this.vScale === this._cachedVScale &&
  17929. this.coordinatesMode === this._cachedCoordinatesMode) {
  17930. return this._cachedTextureMatrix;
  17931. }
  17932. if (!this._cachedTextureMatrix) {
  17933. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17934. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17935. }
  17936. this._cachedCoordinatesMode = this.coordinatesMode;
  17937. switch (this.coordinatesMode) {
  17938. case Texture.PLANAR_MODE:
  17939. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17940. this._cachedTextureMatrix[0] = this.uScale;
  17941. this._cachedTextureMatrix[5] = this.vScale;
  17942. this._cachedTextureMatrix[12] = this.uOffset;
  17943. this._cachedTextureMatrix[13] = this.vOffset;
  17944. break;
  17945. case Texture.PROJECTION_MODE:
  17946. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17947. this._projectionModeMatrix.m[0] = 0.5;
  17948. this._projectionModeMatrix.m[5] = -0.5;
  17949. this._projectionModeMatrix.m[10] = 0.0;
  17950. this._projectionModeMatrix.m[12] = 0.5;
  17951. this._projectionModeMatrix.m[13] = 0.5;
  17952. this._projectionModeMatrix.m[14] = 1.0;
  17953. this._projectionModeMatrix.m[15] = 1.0;
  17954. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17955. break;
  17956. default:
  17957. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17958. break;
  17959. }
  17960. return this._cachedTextureMatrix;
  17961. };
  17962. Texture.prototype.clone = function () {
  17963. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17964. // Base texture
  17965. newTexture.hasAlpha = this.hasAlpha;
  17966. newTexture.level = this.level;
  17967. newTexture.wrapU = this.wrapU;
  17968. newTexture.wrapV = this.wrapV;
  17969. newTexture.coordinatesIndex = this.coordinatesIndex;
  17970. newTexture.coordinatesMode = this.coordinatesMode;
  17971. // Texture
  17972. newTexture.uOffset = this.uOffset;
  17973. newTexture.vOffset = this.vOffset;
  17974. newTexture.uScale = this.uScale;
  17975. newTexture.vScale = this.vScale;
  17976. newTexture.uAng = this.uAng;
  17977. newTexture.vAng = this.vAng;
  17978. newTexture.wAng = this.wAng;
  17979. return newTexture;
  17980. };
  17981. Texture.prototype.serialize = function () {
  17982. if (!this.name) {
  17983. return null;
  17984. }
  17985. var serializationObject = _super.prototype.serialize.call(this);
  17986. serializationObject.uOffset = this.uOffset;
  17987. serializationObject.vOffset = this.vOffset;
  17988. serializationObject.uScale = this.uScale;
  17989. serializationObject.vScale = this.vScale;
  17990. serializationObject.uAng = this.uAng;
  17991. serializationObject.vAng = this.vAng;
  17992. serializationObject.wAng = this.wAng;
  17993. return serializationObject;
  17994. };
  17995. // Statics
  17996. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17997. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17998. if (onLoad === void 0) { onLoad = null; }
  17999. if (onError === void 0) { onError = null; }
  18000. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  18001. };
  18002. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18003. if (parsedTexture.isCube) {
  18004. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18005. }
  18006. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18007. return null;
  18008. }
  18009. var texture;
  18010. if (parsedTexture.mirrorPlane) {
  18011. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18012. texture._waitingRenderList = parsedTexture.renderList;
  18013. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18014. }
  18015. else if (parsedTexture.isRenderTarget) {
  18016. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18017. texture._waitingRenderList = parsedTexture.renderList;
  18018. }
  18019. else {
  18020. if (parsedTexture.base64String) {
  18021. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18022. }
  18023. else {
  18024. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18025. }
  18026. }
  18027. texture.name = parsedTexture.name;
  18028. texture.hasAlpha = parsedTexture.hasAlpha;
  18029. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18030. texture.level = parsedTexture.level;
  18031. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18032. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18033. texture.uOffset = parsedTexture.uOffset;
  18034. texture.vOffset = parsedTexture.vOffset;
  18035. texture.uScale = parsedTexture.uScale;
  18036. texture.vScale = parsedTexture.vScale;
  18037. texture.uAng = parsedTexture.uAng;
  18038. texture.vAng = parsedTexture.vAng;
  18039. texture.wAng = parsedTexture.wAng;
  18040. texture.wrapU = parsedTexture.wrapU;
  18041. texture.wrapV = parsedTexture.wrapV;
  18042. // Animations
  18043. if (parsedTexture.animations) {
  18044. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18045. var parsedAnimation = parsedTexture.animations[animationIndex];
  18046. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18047. }
  18048. }
  18049. return texture;
  18050. };
  18051. // Constants
  18052. Texture.NEAREST_SAMPLINGMODE = 1;
  18053. Texture.BILINEAR_SAMPLINGMODE = 2;
  18054. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18055. Texture.EXPLICIT_MODE = 0;
  18056. Texture.SPHERICAL_MODE = 1;
  18057. Texture.PLANAR_MODE = 2;
  18058. Texture.CUBIC_MODE = 3;
  18059. Texture.PROJECTION_MODE = 4;
  18060. Texture.SKYBOX_MODE = 5;
  18061. Texture.INVCUBIC_MODE = 6;
  18062. Texture.EQUIRECTANGULAR_MODE = 7;
  18063. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18064. Texture.CLAMP_ADDRESSMODE = 0;
  18065. Texture.WRAP_ADDRESSMODE = 1;
  18066. Texture.MIRROR_ADDRESSMODE = 2;
  18067. return Texture;
  18068. })(BABYLON.BaseTexture);
  18069. BABYLON.Texture = Texture;
  18070. })(BABYLON || (BABYLON = {}));
  18071. var BABYLON;
  18072. (function (BABYLON) {
  18073. var CubeTexture = (function (_super) {
  18074. __extends(CubeTexture, _super);
  18075. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18076. _super.call(this, scene);
  18077. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18078. this.name = rootUrl;
  18079. this.url = rootUrl;
  18080. this._noMipmap = noMipmap;
  18081. this.hasAlpha = false;
  18082. if (!rootUrl && !files) {
  18083. return;
  18084. }
  18085. this._texture = this._getFromCache(rootUrl, noMipmap);
  18086. if (!files) {
  18087. if (!extensions) {
  18088. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18089. }
  18090. files = [];
  18091. for (var index = 0; index < extensions.length; index++) {
  18092. files.push(rootUrl + extensions[index]);
  18093. }
  18094. this._extensions = extensions;
  18095. }
  18096. this._files = files;
  18097. if (!this._texture) {
  18098. if (!scene.useDelayedTextureLoading) {
  18099. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18100. }
  18101. else {
  18102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18103. }
  18104. }
  18105. this.isCube = true;
  18106. this._textureMatrix = BABYLON.Matrix.Identity();
  18107. }
  18108. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18109. return new CubeTexture("", scene, null, noMipmap, files);
  18110. };
  18111. CubeTexture.prototype.clone = function () {
  18112. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18113. // Base texture
  18114. newTexture.level = this.level;
  18115. newTexture.wrapU = this.wrapU;
  18116. newTexture.wrapV = this.wrapV;
  18117. newTexture.coordinatesIndex = this.coordinatesIndex;
  18118. newTexture.coordinatesMode = this.coordinatesMode;
  18119. return newTexture;
  18120. };
  18121. // Methods
  18122. CubeTexture.prototype.delayLoad = function () {
  18123. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18124. return;
  18125. }
  18126. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18127. this._texture = this._getFromCache(this.url, this._noMipmap);
  18128. if (!this._texture) {
  18129. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18130. }
  18131. };
  18132. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18133. return this._textureMatrix;
  18134. };
  18135. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18136. var texture = null;
  18137. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18138. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18139. texture.name = parsedTexture.name;
  18140. texture.hasAlpha = parsedTexture.hasAlpha;
  18141. texture.level = parsedTexture.level;
  18142. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18143. }
  18144. return texture;
  18145. };
  18146. CubeTexture.prototype.serialize = function () {
  18147. if (!this.name) {
  18148. return null;
  18149. }
  18150. var serializationObject = {};
  18151. serializationObject.name = this.name;
  18152. serializationObject.hasAlpha = this.hasAlpha;
  18153. serializationObject.isCube = true;
  18154. serializationObject.level = this.level;
  18155. serializationObject.coordinatesMode = this.coordinatesMode;
  18156. return serializationObject;
  18157. };
  18158. return CubeTexture;
  18159. })(BABYLON.BaseTexture);
  18160. BABYLON.CubeTexture = CubeTexture;
  18161. })(BABYLON || (BABYLON = {}));
  18162. var BABYLON;
  18163. (function (BABYLON) {
  18164. var RenderTargetTexture = (function (_super) {
  18165. __extends(RenderTargetTexture, _super);
  18166. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18167. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18168. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18169. if (isCube === void 0) { isCube = false; }
  18170. _super.call(this, null, scene, !generateMipMaps);
  18171. this.isCube = isCube;
  18172. this.renderList = new Array();
  18173. this.renderParticles = true;
  18174. this.renderSprites = false;
  18175. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18176. this._currentRefreshId = -1;
  18177. this._refreshRate = 1;
  18178. this.name = name;
  18179. this.isRenderTarget = true;
  18180. this._size = size;
  18181. this._generateMipMaps = generateMipMaps;
  18182. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18183. if (isCube) {
  18184. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18185. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18186. this._textureMatrix = BABYLON.Matrix.Identity();
  18187. }
  18188. else {
  18189. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18190. }
  18191. // Rendering groups
  18192. this._renderingManager = new BABYLON.RenderingManager(scene);
  18193. }
  18194. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18195. get: function () {
  18196. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18202. get: function () {
  18203. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18209. get: function () {
  18210. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18211. },
  18212. enumerable: true,
  18213. configurable: true
  18214. });
  18215. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18216. this._currentRefreshId = -1;
  18217. };
  18218. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18219. get: function () {
  18220. return this._refreshRate;
  18221. },
  18222. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18223. set: function (value) {
  18224. this._refreshRate = value;
  18225. this.resetRefreshCounter();
  18226. },
  18227. enumerable: true,
  18228. configurable: true
  18229. });
  18230. RenderTargetTexture.prototype._shouldRender = function () {
  18231. if (this._currentRefreshId === -1) {
  18232. this._currentRefreshId = 1;
  18233. return true;
  18234. }
  18235. if (this.refreshRate === this._currentRefreshId) {
  18236. this._currentRefreshId = 1;
  18237. return true;
  18238. }
  18239. this._currentRefreshId++;
  18240. return false;
  18241. };
  18242. RenderTargetTexture.prototype.isReady = function () {
  18243. if (!this.getScene().renderTargetsEnabled) {
  18244. return false;
  18245. }
  18246. return _super.prototype.isReady.call(this);
  18247. };
  18248. RenderTargetTexture.prototype.getRenderSize = function () {
  18249. return this._size;
  18250. };
  18251. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18252. get: function () {
  18253. return true;
  18254. },
  18255. enumerable: true,
  18256. configurable: true
  18257. });
  18258. RenderTargetTexture.prototype.scale = function (ratio) {
  18259. var newSize = this._size * ratio;
  18260. this.resize(newSize, this._generateMipMaps);
  18261. };
  18262. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18263. if (this.isCube) {
  18264. return this._textureMatrix;
  18265. }
  18266. return _super.prototype.getReflectionTextureMatrix.call(this);
  18267. };
  18268. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18269. this.releaseInternalTexture();
  18270. if (this.isCube) {
  18271. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18272. }
  18273. else {
  18274. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18275. }
  18276. };
  18277. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18278. var scene = this.getScene();
  18279. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18280. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18281. }
  18282. if (this._waitingRenderList) {
  18283. this.renderList = [];
  18284. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18285. var id = this._waitingRenderList[index];
  18286. this.renderList.push(scene.getMeshByID(id));
  18287. }
  18288. delete this._waitingRenderList;
  18289. }
  18290. if (this.renderList && this.renderList.length === 0) {
  18291. return;
  18292. }
  18293. // Prepare renderingManager
  18294. this._renderingManager.reset();
  18295. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18296. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18297. var mesh = currentRenderList[meshIndex];
  18298. if (mesh) {
  18299. if (!mesh.isReady()) {
  18300. // Reset _currentRefreshId
  18301. this.resetRefreshCounter();
  18302. continue;
  18303. }
  18304. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18305. mesh._activate(scene.getRenderId());
  18306. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18307. var subMesh = mesh.subMeshes[subIndex];
  18308. scene._activeIndices += subMesh.indexCount;
  18309. this._renderingManager.dispatch(subMesh);
  18310. }
  18311. }
  18312. }
  18313. }
  18314. if (this.isCube) {
  18315. for (var face = 0; face < 6; face++) {
  18316. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18317. scene.incrementRenderId();
  18318. }
  18319. }
  18320. else {
  18321. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18322. }
  18323. if (this.onAfterUnbind) {
  18324. this.onAfterUnbind();
  18325. }
  18326. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18327. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18328. }
  18329. scene.resetCachedMaterial();
  18330. };
  18331. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18332. var scene = this.getScene();
  18333. var engine = scene.getEngine();
  18334. // Bind
  18335. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18336. if (this.isCube) {
  18337. engine.bindFramebuffer(this._texture, faceIndex);
  18338. }
  18339. else {
  18340. engine.bindFramebuffer(this._texture);
  18341. }
  18342. }
  18343. if (this.onBeforeRender) {
  18344. this.onBeforeRender(faceIndex);
  18345. }
  18346. // Clear
  18347. if (this.onClear) {
  18348. this.onClear(engine);
  18349. }
  18350. else {
  18351. engine.clear(scene.clearColor, true, true);
  18352. }
  18353. if (!this._doNotChangeAspectRatio) {
  18354. scene.updateTransformMatrix(true);
  18355. }
  18356. // Render
  18357. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18358. if (useCameraPostProcess) {
  18359. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18360. }
  18361. if (!this._doNotChangeAspectRatio) {
  18362. scene.updateTransformMatrix(true);
  18363. }
  18364. if (this.onAfterRender) {
  18365. this.onAfterRender(faceIndex);
  18366. }
  18367. // Dump ?
  18368. if (dumpForDebug) {
  18369. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18370. }
  18371. // Unbind
  18372. if (!this.isCube || faceIndex === 5) {
  18373. if (this.isCube) {
  18374. if (faceIndex === 5) {
  18375. engine.generateMipMapsForCubemap(this._texture);
  18376. }
  18377. }
  18378. engine.unBindFramebuffer(this._texture, this.isCube);
  18379. }
  18380. };
  18381. RenderTargetTexture.prototype.clone = function () {
  18382. var textureSize = this.getSize();
  18383. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18384. // Base texture
  18385. newTexture.hasAlpha = this.hasAlpha;
  18386. newTexture.level = this.level;
  18387. // RenderTarget Texture
  18388. newTexture.coordinatesMode = this.coordinatesMode;
  18389. newTexture.renderList = this.renderList.slice(0);
  18390. return newTexture;
  18391. };
  18392. RenderTargetTexture.prototype.serialize = function () {
  18393. if (!this.name) {
  18394. return null;
  18395. }
  18396. var serializationObject = _super.prototype.serialize.call(this);
  18397. serializationObject.renderTargetSize = this.getRenderSize();
  18398. serializationObject.renderList = [];
  18399. for (var index = 0; index < this.renderList.length; index++) {
  18400. serializationObject.renderList.push(this.renderList[index].id);
  18401. }
  18402. return serializationObject;
  18403. };
  18404. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18405. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18406. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18407. return RenderTargetTexture;
  18408. })(BABYLON.Texture);
  18409. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18410. })(BABYLON || (BABYLON = {}));
  18411. var BABYLON;
  18412. (function (BABYLON) {
  18413. var ProceduralTexture = (function (_super) {
  18414. __extends(ProceduralTexture, _super);
  18415. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18416. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18417. if (isCube === void 0) { isCube = false; }
  18418. _super.call(this, null, scene, !generateMipMaps);
  18419. this.isCube = isCube;
  18420. this.isEnabled = true;
  18421. this._currentRefreshId = -1;
  18422. this._refreshRate = 1;
  18423. this._vertexDeclaration = [2];
  18424. this._vertexStrideSize = 2 * 4;
  18425. this._uniforms = new Array();
  18426. this._samplers = new Array();
  18427. this._textures = new Array();
  18428. this._floats = new Array();
  18429. this._floatsArrays = {};
  18430. this._colors3 = new Array();
  18431. this._colors4 = new Array();
  18432. this._vectors2 = new Array();
  18433. this._vectors3 = new Array();
  18434. this._matrices = new Array();
  18435. this._fallbackTextureUsed = false;
  18436. scene._proceduralTextures.push(this);
  18437. this.name = name;
  18438. this.isRenderTarget = true;
  18439. this._size = size;
  18440. this._generateMipMaps = generateMipMaps;
  18441. this.setFragment(fragment);
  18442. this._fallbackTexture = fallbackTexture;
  18443. if (isCube) {
  18444. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18445. this.setFloat("face", 0);
  18446. }
  18447. else {
  18448. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18449. }
  18450. // VBO
  18451. var vertices = [];
  18452. vertices.push(1, 1);
  18453. vertices.push(-1, 1);
  18454. vertices.push(-1, -1);
  18455. vertices.push(1, -1);
  18456. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18457. // Indices
  18458. var indices = [];
  18459. indices.push(0);
  18460. indices.push(1);
  18461. indices.push(2);
  18462. indices.push(0);
  18463. indices.push(2);
  18464. indices.push(3);
  18465. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18466. }
  18467. ProceduralTexture.prototype.reset = function () {
  18468. if (this._effect === undefined) {
  18469. return;
  18470. }
  18471. var engine = this.getScene().getEngine();
  18472. engine._releaseEffect(this._effect);
  18473. };
  18474. ProceduralTexture.prototype.isReady = function () {
  18475. var _this = this;
  18476. var engine = this.getScene().getEngine();
  18477. var shaders;
  18478. if (!this._fragment) {
  18479. return false;
  18480. }
  18481. if (this._fallbackTextureUsed) {
  18482. return true;
  18483. }
  18484. if (this._fragment.fragmentElement !== undefined) {
  18485. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18486. }
  18487. else {
  18488. shaders = { vertex: "procedural", fragment: this._fragment };
  18489. }
  18490. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18491. _this.releaseInternalTexture();
  18492. if (_this._fallbackTexture) {
  18493. _this._texture = _this._fallbackTexture._texture;
  18494. _this._texture.references++;
  18495. }
  18496. _this._fallbackTextureUsed = true;
  18497. });
  18498. return this._effect.isReady();
  18499. };
  18500. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18501. this._currentRefreshId = -1;
  18502. };
  18503. ProceduralTexture.prototype.setFragment = function (fragment) {
  18504. this._fragment = fragment;
  18505. };
  18506. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18507. get: function () {
  18508. return this._refreshRate;
  18509. },
  18510. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18511. set: function (value) {
  18512. this._refreshRate = value;
  18513. this.resetRefreshCounter();
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. ProceduralTexture.prototype._shouldRender = function () {
  18519. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18520. return false;
  18521. }
  18522. if (this._fallbackTextureUsed) {
  18523. return false;
  18524. }
  18525. if (this._currentRefreshId === -1) {
  18526. this._currentRefreshId = 1;
  18527. return true;
  18528. }
  18529. if (this.refreshRate === this._currentRefreshId) {
  18530. this._currentRefreshId = 1;
  18531. return true;
  18532. }
  18533. this._currentRefreshId++;
  18534. return false;
  18535. };
  18536. ProceduralTexture.prototype.getRenderSize = function () {
  18537. return this._size;
  18538. };
  18539. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18540. if (this._fallbackTextureUsed) {
  18541. return;
  18542. }
  18543. this.releaseInternalTexture();
  18544. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18545. };
  18546. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18547. if (this._uniforms.indexOf(uniformName) === -1) {
  18548. this._uniforms.push(uniformName);
  18549. }
  18550. };
  18551. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18552. if (this._samplers.indexOf(name) === -1) {
  18553. this._samplers.push(name);
  18554. }
  18555. this._textures[name] = texture;
  18556. return this;
  18557. };
  18558. ProceduralTexture.prototype.setFloat = function (name, value) {
  18559. this._checkUniform(name);
  18560. this._floats[name] = value;
  18561. return this;
  18562. };
  18563. ProceduralTexture.prototype.setFloats = function (name, value) {
  18564. this._checkUniform(name);
  18565. this._floatsArrays[name] = value;
  18566. return this;
  18567. };
  18568. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18569. this._checkUniform(name);
  18570. this._colors3[name] = value;
  18571. return this;
  18572. };
  18573. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18574. this._checkUniform(name);
  18575. this._colors4[name] = value;
  18576. return this;
  18577. };
  18578. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18579. this._checkUniform(name);
  18580. this._vectors2[name] = value;
  18581. return this;
  18582. };
  18583. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18584. this._checkUniform(name);
  18585. this._vectors3[name] = value;
  18586. return this;
  18587. };
  18588. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18589. this._checkUniform(name);
  18590. this._matrices[name] = value;
  18591. return this;
  18592. };
  18593. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18594. var scene = this.getScene();
  18595. var engine = scene.getEngine();
  18596. // Render
  18597. engine.enableEffect(this._effect);
  18598. engine.setState(false);
  18599. // Texture
  18600. for (var name in this._textures) {
  18601. this._effect.setTexture(name, this._textures[name]);
  18602. }
  18603. // Float
  18604. for (name in this._floats) {
  18605. this._effect.setFloat(name, this._floats[name]);
  18606. }
  18607. // Floats
  18608. for (name in this._floatsArrays) {
  18609. this._effect.setArray(name, this._floatsArrays[name]);
  18610. }
  18611. // Color3
  18612. for (name in this._colors3) {
  18613. this._effect.setColor3(name, this._colors3[name]);
  18614. }
  18615. // Color4
  18616. for (name in this._colors4) {
  18617. var color = this._colors4[name];
  18618. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18619. }
  18620. // Vector2
  18621. for (name in this._vectors2) {
  18622. this._effect.setVector2(name, this._vectors2[name]);
  18623. }
  18624. // Vector3
  18625. for (name in this._vectors3) {
  18626. this._effect.setVector3(name, this._vectors3[name]);
  18627. }
  18628. // Matrix
  18629. for (name in this._matrices) {
  18630. this._effect.setMatrix(name, this._matrices[name]);
  18631. }
  18632. // VBOs
  18633. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18634. if (this.isCube) {
  18635. for (var face = 0; face < 6; face++) {
  18636. engine.bindFramebuffer(this._texture, face);
  18637. this._effect.setFloat("face", face);
  18638. // Clear
  18639. engine.clear(scene.clearColor, true, true);
  18640. // Draw order
  18641. engine.draw(true, 0, 6);
  18642. // Mipmaps
  18643. if (face === 5) {
  18644. engine.generateMipMapsForCubemap(this._texture);
  18645. }
  18646. }
  18647. }
  18648. else {
  18649. engine.bindFramebuffer(this._texture);
  18650. // Clear
  18651. engine.clear(scene.clearColor, true, true);
  18652. // Draw order
  18653. engine.draw(true, 0, 6);
  18654. }
  18655. // Unbind
  18656. engine.unBindFramebuffer(this._texture, this.isCube);
  18657. if (this.onGenerated) {
  18658. this.onGenerated();
  18659. }
  18660. };
  18661. ProceduralTexture.prototype.clone = function () {
  18662. var textureSize = this.getSize();
  18663. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18664. // Base texture
  18665. newTexture.hasAlpha = this.hasAlpha;
  18666. newTexture.level = this.level;
  18667. // RenderTarget Texture
  18668. newTexture.coordinatesMode = this.coordinatesMode;
  18669. return newTexture;
  18670. };
  18671. ProceduralTexture.prototype.dispose = function () {
  18672. var index = this.getScene()._proceduralTextures.indexOf(this);
  18673. if (index >= 0) {
  18674. this.getScene()._proceduralTextures.splice(index, 1);
  18675. }
  18676. _super.prototype.dispose.call(this);
  18677. };
  18678. return ProceduralTexture;
  18679. })(BABYLON.Texture);
  18680. BABYLON.ProceduralTexture = ProceduralTexture;
  18681. })(BABYLON || (BABYLON = {}));
  18682. var BABYLON;
  18683. (function (BABYLON) {
  18684. var MirrorTexture = (function (_super) {
  18685. __extends(MirrorTexture, _super);
  18686. function MirrorTexture(name, size, scene, generateMipMaps) {
  18687. var _this = this;
  18688. _super.call(this, name, size, scene, generateMipMaps, true);
  18689. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18690. this._transformMatrix = BABYLON.Matrix.Zero();
  18691. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18692. this.onBeforeRender = function () {
  18693. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18694. _this._savedViewMatrix = scene.getViewMatrix();
  18695. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18696. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18697. scene.clipPlane = _this.mirrorPlane;
  18698. scene.getEngine().cullBackFaces = false;
  18699. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18700. };
  18701. this.onAfterRender = function () {
  18702. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18703. scene.getEngine().cullBackFaces = true;
  18704. scene._mirroredCameraPosition = null;
  18705. delete scene.clipPlane;
  18706. };
  18707. }
  18708. MirrorTexture.prototype.clone = function () {
  18709. var textureSize = this.getSize();
  18710. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18711. // Base texture
  18712. newTexture.hasAlpha = this.hasAlpha;
  18713. newTexture.level = this.level;
  18714. // Mirror Texture
  18715. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18716. newTexture.renderList = this.renderList.slice(0);
  18717. return newTexture;
  18718. };
  18719. MirrorTexture.prototype.serialize = function () {
  18720. if (!this.name) {
  18721. return null;
  18722. }
  18723. var serializationObject = _super.prototype.serialize.call(this);
  18724. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18725. return serializationObject;
  18726. };
  18727. return MirrorTexture;
  18728. })(BABYLON.RenderTargetTexture);
  18729. BABYLON.MirrorTexture = MirrorTexture;
  18730. })(BABYLON || (BABYLON = {}));
  18731. var BABYLON;
  18732. (function (BABYLON) {
  18733. /**
  18734. * Creates a refraction texture used by refraction channel of the standard material.
  18735. * @param name the texture name
  18736. * @param size size of the underlying texture
  18737. * @param scene root scene
  18738. */
  18739. var RefractionTexture = (function (_super) {
  18740. __extends(RefractionTexture, _super);
  18741. function RefractionTexture(name, size, scene, generateMipMaps) {
  18742. var _this = this;
  18743. _super.call(this, name, size, scene, generateMipMaps, true);
  18744. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18745. this.depth = 2.0;
  18746. this.onBeforeRender = function () {
  18747. scene.clipPlane = _this.refractionPlane;
  18748. };
  18749. this.onAfterRender = function () {
  18750. delete scene.clipPlane;
  18751. };
  18752. }
  18753. RefractionTexture.prototype.clone = function () {
  18754. var textureSize = this.getSize();
  18755. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18756. // Base texture
  18757. newTexture.hasAlpha = this.hasAlpha;
  18758. newTexture.level = this.level;
  18759. // Refraction Texture
  18760. newTexture.refractionPlane = this.refractionPlane.clone();
  18761. newTexture.renderList = this.renderList.slice(0);
  18762. newTexture.depth = this.depth;
  18763. return newTexture;
  18764. };
  18765. RefractionTexture.prototype.serialize = function () {
  18766. if (!this.name) {
  18767. return null;
  18768. }
  18769. var serializationObject = _super.prototype.serialize.call(this);
  18770. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18771. serializationObject.depth = this.depth;
  18772. return serializationObject;
  18773. };
  18774. return RefractionTexture;
  18775. })(BABYLON.RenderTargetTexture);
  18776. BABYLON.RefractionTexture = RefractionTexture;
  18777. })(BABYLON || (BABYLON = {}));
  18778. var BABYLON;
  18779. (function (BABYLON) {
  18780. var DynamicTexture = (function (_super) {
  18781. __extends(DynamicTexture, _super);
  18782. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18784. _super.call(this, null, scene, !generateMipMaps);
  18785. this.name = name;
  18786. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18787. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18788. this._generateMipMaps = generateMipMaps;
  18789. if (options.getContext) {
  18790. this._canvas = options;
  18791. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18792. }
  18793. else {
  18794. this._canvas = document.createElement("canvas");
  18795. if (options.width) {
  18796. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18797. }
  18798. else {
  18799. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18800. }
  18801. }
  18802. var textureSize = this.getSize();
  18803. this._canvas.width = textureSize.width;
  18804. this._canvas.height = textureSize.height;
  18805. this._context = this._canvas.getContext("2d");
  18806. }
  18807. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18808. get: function () {
  18809. return true;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. DynamicTexture.prototype.scale = function (ratio) {
  18815. var textureSize = this.getSize();
  18816. textureSize.width *= ratio;
  18817. textureSize.height *= ratio;
  18818. this._canvas.width = textureSize.width;
  18819. this._canvas.height = textureSize.height;
  18820. this.releaseInternalTexture();
  18821. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18822. };
  18823. DynamicTexture.prototype.getContext = function () {
  18824. return this._context;
  18825. };
  18826. DynamicTexture.prototype.clear = function () {
  18827. var size = this.getSize();
  18828. this._context.fillRect(0, 0, size.width, size.height);
  18829. };
  18830. DynamicTexture.prototype.update = function (invertY) {
  18831. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18832. };
  18833. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18834. if (update === void 0) { update = true; }
  18835. var size = this.getSize();
  18836. if (clearColor) {
  18837. this._context.fillStyle = clearColor;
  18838. this._context.fillRect(0, 0, size.width, size.height);
  18839. }
  18840. this._context.font = font;
  18841. if (x === null) {
  18842. var textSize = this._context.measureText(text);
  18843. x = (size.width - textSize.width) / 2;
  18844. }
  18845. this._context.fillStyle = color;
  18846. this._context.fillText(text, x, y);
  18847. if (update) {
  18848. this.update(invertY);
  18849. }
  18850. };
  18851. DynamicTexture.prototype.clone = function () {
  18852. var textureSize = this.getSize();
  18853. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18854. // Base texture
  18855. newTexture.hasAlpha = this.hasAlpha;
  18856. newTexture.level = this.level;
  18857. // Dynamic Texture
  18858. newTexture.wrapU = this.wrapU;
  18859. newTexture.wrapV = this.wrapV;
  18860. return newTexture;
  18861. };
  18862. return DynamicTexture;
  18863. })(BABYLON.Texture);
  18864. BABYLON.DynamicTexture = DynamicTexture;
  18865. })(BABYLON || (BABYLON = {}));
  18866. var BABYLON;
  18867. (function (BABYLON) {
  18868. var VideoTexture = (function (_super) {
  18869. __extends(VideoTexture, _super);
  18870. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18871. var _this = this;
  18872. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18873. if (invertY === void 0) { invertY = false; }
  18874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18875. _super.call(this, null, scene, !generateMipMaps, invertY);
  18876. this._autoLaunch = true;
  18877. this.name = name;
  18878. this.video = document.createElement("video");
  18879. this.video.autoplay = false;
  18880. this.video.loop = true;
  18881. this.video.addEventListener("canplaythrough", function () {
  18882. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18883. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18884. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18885. }
  18886. else {
  18887. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18888. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18889. generateMipMaps = false;
  18890. }
  18891. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18892. _this._texture.isReady = true;
  18893. });
  18894. urls.forEach(function (url) {
  18895. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18896. var source = document.createElement("source");
  18897. source.src = url;
  18898. _this.video.appendChild(source);
  18899. });
  18900. this._lastUpdate = BABYLON.Tools.Now;
  18901. }
  18902. VideoTexture.prototype.update = function () {
  18903. if (this._autoLaunch) {
  18904. this._autoLaunch = false;
  18905. this.video.play();
  18906. }
  18907. var now = BABYLON.Tools.Now;
  18908. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18909. return false;
  18910. }
  18911. this._lastUpdate = now;
  18912. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18913. return true;
  18914. };
  18915. return VideoTexture;
  18916. })(BABYLON.Texture);
  18917. BABYLON.VideoTexture = VideoTexture;
  18918. })(BABYLON || (BABYLON = {}));
  18919. var BABYLON;
  18920. (function (BABYLON) {
  18921. var CustomProceduralTexture = (function (_super) {
  18922. __extends(CustomProceduralTexture, _super);
  18923. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18924. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18925. this._animate = true;
  18926. this._time = 0;
  18927. this._texturePath = texturePath;
  18928. //Try to load json
  18929. this.loadJson(texturePath);
  18930. this.refreshRate = 1;
  18931. }
  18932. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18933. var _this = this;
  18934. var that = this;
  18935. function noConfigFile() {
  18936. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18937. try {
  18938. that.setFragment(that._texturePath);
  18939. }
  18940. catch (ex) {
  18941. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18942. }
  18943. }
  18944. var configFileUrl = jsonUrl + "/config.json";
  18945. var xhr = new XMLHttpRequest();
  18946. xhr.open("GET", configFileUrl, true);
  18947. xhr.addEventListener("load", function () {
  18948. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18949. try {
  18950. _this._config = JSON.parse(xhr.response);
  18951. _this.updateShaderUniforms();
  18952. _this.updateTextures();
  18953. _this.setFragment(_this._texturePath + "/custom");
  18954. _this._animate = _this._config.animate;
  18955. _this.refreshRate = _this._config.refreshrate;
  18956. }
  18957. catch (ex) {
  18958. noConfigFile();
  18959. }
  18960. }
  18961. else {
  18962. noConfigFile();
  18963. }
  18964. }, false);
  18965. xhr.addEventListener("error", function () {
  18966. noConfigFile();
  18967. }, false);
  18968. try {
  18969. xhr.send();
  18970. }
  18971. catch (ex) {
  18972. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18973. }
  18974. };
  18975. CustomProceduralTexture.prototype.isReady = function () {
  18976. if (!_super.prototype.isReady.call(this)) {
  18977. return false;
  18978. }
  18979. for (var name in this._textures) {
  18980. var texture = this._textures[name];
  18981. if (!texture.isReady()) {
  18982. return false;
  18983. }
  18984. }
  18985. return true;
  18986. };
  18987. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18988. if (this._animate) {
  18989. this._time += this.getScene().getAnimationRatio() * 0.03;
  18990. this.updateShaderUniforms();
  18991. }
  18992. _super.prototype.render.call(this, useCameraPostProcess);
  18993. };
  18994. CustomProceduralTexture.prototype.updateTextures = function () {
  18995. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18996. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18997. }
  18998. };
  18999. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  19000. if (this._config) {
  19001. for (var j = 0; j < this._config.uniforms.length; j++) {
  19002. var uniform = this._config.uniforms[j];
  19003. switch (uniform.type) {
  19004. case "float":
  19005. this.setFloat(uniform.name, uniform.value);
  19006. break;
  19007. case "color3":
  19008. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  19009. break;
  19010. case "color4":
  19011. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  19012. break;
  19013. case "vector2":
  19014. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  19015. break;
  19016. case "vector3":
  19017. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  19018. break;
  19019. }
  19020. }
  19021. }
  19022. this.setFloat("time", this._time);
  19023. };
  19024. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  19025. get: function () {
  19026. return this._animate;
  19027. },
  19028. set: function (value) {
  19029. this._animate = value;
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. return CustomProceduralTexture;
  19035. })(BABYLON.ProceduralTexture);
  19036. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  19037. })(BABYLON || (BABYLON = {}));
  19038. var BABYLON;
  19039. (function (BABYLON) {
  19040. var EffectFallbacks = (function () {
  19041. function EffectFallbacks() {
  19042. this._defines = {};
  19043. this._currentRank = 32;
  19044. this._maxRank = -1;
  19045. }
  19046. EffectFallbacks.prototype.addFallback = function (rank, define) {
  19047. if (!this._defines[rank]) {
  19048. if (rank < this._currentRank) {
  19049. this._currentRank = rank;
  19050. }
  19051. if (rank > this._maxRank) {
  19052. this._maxRank = rank;
  19053. }
  19054. this._defines[rank] = new Array();
  19055. }
  19056. this._defines[rank].push(define);
  19057. };
  19058. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19059. this._meshRank = rank;
  19060. this._mesh = mesh;
  19061. if (rank > this._maxRank) {
  19062. this._maxRank = rank;
  19063. }
  19064. };
  19065. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19066. get: function () {
  19067. return this._currentRank <= this._maxRank;
  19068. },
  19069. enumerable: true,
  19070. configurable: true
  19071. });
  19072. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19073. var currentFallbacks = this._defines[this._currentRank];
  19074. for (var index = 0; index < currentFallbacks.length; index++) {
  19075. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19076. }
  19077. if (this._mesh && this._currentRank === this._meshRank) {
  19078. this._mesh.computeBonesUsingShaders = false;
  19079. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19080. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19081. }
  19082. this._currentRank++;
  19083. return currentDefines;
  19084. };
  19085. return EffectFallbacks;
  19086. })();
  19087. BABYLON.EffectFallbacks = EffectFallbacks;
  19088. var Effect = (function () {
  19089. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19090. var _this = this;
  19091. this._isReady = false;
  19092. this._compilationError = "";
  19093. this._valueCache = [];
  19094. this._engine = engine;
  19095. this.name = baseName;
  19096. this.defines = defines;
  19097. this._uniformsNames = uniformsNames.concat(samplers);
  19098. this._samplers = samplers;
  19099. this._attributesNames = attributesNames;
  19100. this.onError = onError;
  19101. this.onCompiled = onCompiled;
  19102. var vertexSource;
  19103. var fragmentSource;
  19104. if (baseName.vertexElement) {
  19105. vertexSource = document.getElementById(baseName.vertexElement);
  19106. if (!vertexSource) {
  19107. vertexSource = baseName.vertexElement;
  19108. }
  19109. }
  19110. else {
  19111. vertexSource = baseName.vertex || baseName;
  19112. }
  19113. if (baseName.fragmentElement) {
  19114. fragmentSource = document.getElementById(baseName.fragmentElement);
  19115. if (!fragmentSource) {
  19116. fragmentSource = baseName.fragmentElement;
  19117. }
  19118. }
  19119. else {
  19120. fragmentSource = baseName.fragment || baseName;
  19121. }
  19122. this._loadVertexShader(vertexSource, function (vertexCode) {
  19123. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19124. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19125. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19126. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19127. });
  19128. });
  19129. });
  19130. });
  19131. }
  19132. // Properties
  19133. Effect.prototype.isReady = function () {
  19134. return this._isReady;
  19135. };
  19136. Effect.prototype.getProgram = function () {
  19137. return this._program;
  19138. };
  19139. Effect.prototype.getAttributesNames = function () {
  19140. return this._attributesNames;
  19141. };
  19142. Effect.prototype.getAttributeLocation = function (index) {
  19143. return this._attributes[index];
  19144. };
  19145. Effect.prototype.getAttributeLocationByName = function (name) {
  19146. var index = this._attributesNames.indexOf(name);
  19147. return this._attributes[index];
  19148. };
  19149. Effect.prototype.getAttributesCount = function () {
  19150. return this._attributes.length;
  19151. };
  19152. Effect.prototype.getUniformIndex = function (uniformName) {
  19153. return this._uniformsNames.indexOf(uniformName);
  19154. };
  19155. Effect.prototype.getUniform = function (uniformName) {
  19156. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19157. };
  19158. Effect.prototype.getSamplers = function () {
  19159. return this._samplers;
  19160. };
  19161. Effect.prototype.getCompilationError = function () {
  19162. return this._compilationError;
  19163. };
  19164. // Methods
  19165. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19166. // DOM element ?
  19167. if (vertex instanceof HTMLElement) {
  19168. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19169. callback(vertexCode);
  19170. return;
  19171. }
  19172. // Is in local store ?
  19173. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19174. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19175. return;
  19176. }
  19177. var vertexShaderUrl;
  19178. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19179. vertexShaderUrl = vertex;
  19180. }
  19181. else {
  19182. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19183. }
  19184. // Vertex shader
  19185. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19186. };
  19187. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19188. // DOM element ?
  19189. if (fragment instanceof HTMLElement) {
  19190. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19191. callback(fragmentCode);
  19192. return;
  19193. }
  19194. // Is in local store ?
  19195. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19196. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19197. return;
  19198. }
  19199. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19200. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19201. return;
  19202. }
  19203. var fragmentShaderUrl;
  19204. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19205. fragmentShaderUrl = fragment;
  19206. }
  19207. else {
  19208. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19209. }
  19210. // Fragment shader
  19211. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19212. };
  19213. Effect.prototype._dumpShadersName = function () {
  19214. if (this.name.vertexElement) {
  19215. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19216. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19217. }
  19218. else if (this.name.vertex) {
  19219. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19220. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19221. }
  19222. else {
  19223. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19224. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19225. }
  19226. };
  19227. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19228. var _this = this;
  19229. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  19230. var match = regex.exec(sourceCode);
  19231. var returnValue = new String(sourceCode);
  19232. while (match != null) {
  19233. var includeFile = match[1];
  19234. if (Effect.IncludesShadersStore[includeFile]) {
  19235. // Substitution
  19236. var includeContent = Effect.IncludesShadersStore[includeFile];
  19237. if (match[2]) {
  19238. var splits = match[3].split(",");
  19239. for (var index = 0; index < splits.length; index += 2) {
  19240. var source = new RegExp(splits[index], "g");
  19241. var dest = splits[index + 1];
  19242. includeContent = includeContent.replace(source, dest);
  19243. }
  19244. }
  19245. if (match[4]) {
  19246. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  19247. }
  19248. // Replace
  19249. returnValue = returnValue.replace(match[0], includeContent);
  19250. }
  19251. else {
  19252. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19253. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19254. Effect.IncludesShadersStore[includeFile] = fileContent;
  19255. _this._processIncludes(returnValue, callback);
  19256. });
  19257. return;
  19258. }
  19259. match = regex.exec(sourceCode);
  19260. }
  19261. callback(returnValue);
  19262. };
  19263. Effect.prototype._processPrecision = function (source) {
  19264. if (source.indexOf("precision highp float") === -1) {
  19265. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19266. source = "precision mediump float;\n" + source;
  19267. }
  19268. else {
  19269. source = "precision highp float;\n" + source;
  19270. }
  19271. }
  19272. else {
  19273. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19274. source = source.replace("precision highp float", "precision mediump float");
  19275. }
  19276. }
  19277. return source;
  19278. };
  19279. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19280. try {
  19281. var engine = this._engine;
  19282. // Precision
  19283. vertexSourceCode = this._processPrecision(vertexSourceCode);
  19284. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  19285. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19286. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19287. this._attributes = engine.getAttributes(this._program, attributesNames);
  19288. for (var index = 0; index < this._samplers.length; index++) {
  19289. var sampler = this.getUniform(this._samplers[index]);
  19290. if (sampler == null) {
  19291. this._samplers.splice(index, 1);
  19292. index--;
  19293. }
  19294. }
  19295. engine.bindSamplers(this);
  19296. this._isReady = true;
  19297. if (this.onCompiled) {
  19298. this.onCompiled(this);
  19299. }
  19300. }
  19301. catch (e) {
  19302. // Is it a problem with precision?
  19303. if (e.message.indexOf("highp") !== -1) {
  19304. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19305. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19306. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19307. return;
  19308. }
  19309. // Let's go through fallbacks then
  19310. if (fallbacks && fallbacks.isMoreFallbacks) {
  19311. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19312. this._dumpShadersName();
  19313. defines = fallbacks.reduce(defines);
  19314. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19315. }
  19316. else {
  19317. BABYLON.Tools.Error("Unable to compile effect: ");
  19318. this._dumpShadersName();
  19319. BABYLON.Tools.Error("Defines: " + defines);
  19320. BABYLON.Tools.Error("Error: " + e.message);
  19321. this._compilationError = e.message;
  19322. if (this.onError) {
  19323. this.onError(this, this._compilationError);
  19324. }
  19325. }
  19326. }
  19327. };
  19328. Object.defineProperty(Effect.prototype, "isSupported", {
  19329. get: function () {
  19330. return this._compilationError === "";
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Effect.prototype._bindTexture = function (channel, texture) {
  19336. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19337. };
  19338. Effect.prototype.setTexture = function (channel, texture) {
  19339. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19340. };
  19341. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19342. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19343. };
  19344. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19345. if (!this._valueCache[uniformName]) {
  19346. this._valueCache[uniformName] = new BABYLON.Matrix();
  19347. }
  19348. for (var index = 0; index < 16; index++) {
  19349. this._valueCache[uniformName].m[index] = matrix.m[index];
  19350. }
  19351. };
  19352. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19353. if (!this._valueCache[uniformName]) {
  19354. this._valueCache[uniformName] = [x, y];
  19355. return;
  19356. }
  19357. this._valueCache[uniformName][0] = x;
  19358. this._valueCache[uniformName][1] = y;
  19359. };
  19360. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19361. if (!this._valueCache[uniformName]) {
  19362. this._valueCache[uniformName] = [x, y, z];
  19363. return;
  19364. }
  19365. this._valueCache[uniformName][0] = x;
  19366. this._valueCache[uniformName][1] = y;
  19367. this._valueCache[uniformName][2] = z;
  19368. };
  19369. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19370. if (!this._valueCache[uniformName]) {
  19371. this._valueCache[uniformName] = [x, y, z, w];
  19372. return;
  19373. }
  19374. this._valueCache[uniformName][0] = x;
  19375. this._valueCache[uniformName][1] = y;
  19376. this._valueCache[uniformName][2] = z;
  19377. this._valueCache[uniformName][3] = w;
  19378. };
  19379. Effect.prototype.setArray = function (uniformName, array) {
  19380. this._engine.setArray(this.getUniform(uniformName), array);
  19381. return this;
  19382. };
  19383. Effect.prototype.setArray2 = function (uniformName, array) {
  19384. this._engine.setArray2(this.getUniform(uniformName), array);
  19385. return this;
  19386. };
  19387. Effect.prototype.setArray3 = function (uniformName, array) {
  19388. this._engine.setArray3(this.getUniform(uniformName), array);
  19389. return this;
  19390. };
  19391. Effect.prototype.setArray4 = function (uniformName, array) {
  19392. this._engine.setArray4(this.getUniform(uniformName), array);
  19393. return this;
  19394. };
  19395. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19396. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19397. return this;
  19398. };
  19399. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19400. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19401. // return this;
  19402. // this._cacheMatrix(uniformName, matrix);
  19403. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19404. return this;
  19405. };
  19406. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19407. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19408. return this;
  19409. };
  19410. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19411. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19412. return this;
  19413. };
  19414. Effect.prototype.setFloat = function (uniformName, value) {
  19415. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19416. return this;
  19417. this._valueCache[uniformName] = value;
  19418. this._engine.setFloat(this.getUniform(uniformName), value);
  19419. return this;
  19420. };
  19421. Effect.prototype.setBool = function (uniformName, bool) {
  19422. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19423. return this;
  19424. this._valueCache[uniformName] = bool;
  19425. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19426. return this;
  19427. };
  19428. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19429. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19430. return this;
  19431. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19432. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19433. return this;
  19434. };
  19435. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19436. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19437. return this;
  19438. this._cacheFloat2(uniformName, x, y);
  19439. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19440. return this;
  19441. };
  19442. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19443. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19444. return this;
  19445. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19446. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19447. return this;
  19448. };
  19449. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19450. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19451. return this;
  19452. this._cacheFloat3(uniformName, x, y, z);
  19453. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19454. return this;
  19455. };
  19456. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19457. 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)
  19458. return this;
  19459. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19460. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19461. return this;
  19462. };
  19463. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19464. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19465. return this;
  19466. this._cacheFloat4(uniformName, x, y, z, w);
  19467. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19468. return this;
  19469. };
  19470. Effect.prototype.setColor3 = function (uniformName, color3) {
  19471. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19472. return this;
  19473. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19474. this._engine.setColor3(this.getUniform(uniformName), color3);
  19475. return this;
  19476. };
  19477. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19478. 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)
  19479. return this;
  19480. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19481. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19482. return this;
  19483. };
  19484. // Statics
  19485. Effect.ShadersStore = {};
  19486. Effect.IncludesShadersStore = {};
  19487. return Effect;
  19488. })();
  19489. BABYLON.Effect = Effect;
  19490. })(BABYLON || (BABYLON = {}));
  19491. var BABYLON;
  19492. (function (BABYLON) {
  19493. var maxSimultaneousLights = 4;
  19494. var MaterialHelper = (function () {
  19495. function MaterialHelper() {
  19496. }
  19497. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19498. var lightIndex = 0;
  19499. var needNormals = false;
  19500. for (var index = 0; index < scene.lights.length; index++) {
  19501. var light = scene.lights[index];
  19502. if (!light.isEnabled()) {
  19503. continue;
  19504. }
  19505. // Excluded check
  19506. if (light._excludedMeshesIds.length > 0) {
  19507. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19508. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19509. if (excludedMesh) {
  19510. light.excludedMeshes.push(excludedMesh);
  19511. }
  19512. }
  19513. light._excludedMeshesIds = [];
  19514. }
  19515. // Included check
  19516. if (light._includedOnlyMeshesIds.length > 0) {
  19517. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19518. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19519. if (includedOnlyMesh) {
  19520. light.includedOnlyMeshes.push(includedOnlyMesh);
  19521. }
  19522. }
  19523. light._includedOnlyMeshesIds = [];
  19524. }
  19525. if (!light.canAffectMesh(mesh)) {
  19526. continue;
  19527. }
  19528. needNormals = true;
  19529. defines["LIGHT" + lightIndex] = true;
  19530. var type;
  19531. if (light instanceof BABYLON.SpotLight) {
  19532. type = "SPOTLIGHT" + lightIndex;
  19533. }
  19534. else if (light instanceof BABYLON.HemisphericLight) {
  19535. type = "HEMILIGHT" + lightIndex;
  19536. }
  19537. else if (light instanceof BABYLON.PointLight) {
  19538. type = "POINTLIGHT" + lightIndex;
  19539. }
  19540. else {
  19541. type = "DIRLIGHT" + lightIndex;
  19542. }
  19543. defines[type] = true;
  19544. // Specular
  19545. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19546. defines["SPECULARTERM"] = true;
  19547. }
  19548. // Shadows
  19549. if (scene.shadowsEnabled) {
  19550. var shadowGenerator = light.getShadowGenerator();
  19551. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19552. defines["SHADOW" + lightIndex] = true;
  19553. defines["SHADOWS"] = true;
  19554. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19555. defines["SHADOWVSM" + lightIndex] = true;
  19556. }
  19557. if (shadowGenerator.usePoissonSampling) {
  19558. defines["SHADOWPCF" + lightIndex] = true;
  19559. }
  19560. }
  19561. }
  19562. lightIndex++;
  19563. if (lightIndex === maxSimultaneousLights)
  19564. break;
  19565. }
  19566. return needNormals;
  19567. };
  19568. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19569. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19570. if (!defines["LIGHT" + lightIndex]) {
  19571. continue;
  19572. }
  19573. if (lightIndex > 0) {
  19574. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19575. }
  19576. if (defines["SHADOW" + lightIndex]) {
  19577. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19578. }
  19579. if (defines["SHADOWPCF" + lightIndex]) {
  19580. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19581. }
  19582. if (defines["SHADOWVSM" + lightIndex]) {
  19583. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19584. }
  19585. }
  19586. };
  19587. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19588. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19589. fallbacks.addCPUSkinningFallback(0, mesh);
  19590. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19591. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19592. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19593. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19594. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19595. }
  19596. }
  19597. };
  19598. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19599. if (defines["INSTANCES"]) {
  19600. attribs.push("world0");
  19601. attribs.push("world1");
  19602. attribs.push("world2");
  19603. attribs.push("world3");
  19604. }
  19605. };
  19606. // Bindings
  19607. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19608. var shadowGenerator = light.getShadowGenerator();
  19609. if (mesh.receiveShadows && shadowGenerator) {
  19610. if (!light.needCube()) {
  19611. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19612. }
  19613. else {
  19614. if (!depthValuesAlreadySet) {
  19615. depthValuesAlreadySet = true;
  19616. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19617. }
  19618. }
  19619. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19620. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19621. }
  19622. return depthValuesAlreadySet;
  19623. };
  19624. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19625. if (light instanceof BABYLON.PointLight) {
  19626. // Point Light
  19627. light.transferToEffect(effect, "vLightData" + lightIndex);
  19628. }
  19629. else if (light instanceof BABYLON.DirectionalLight) {
  19630. // Directional Light
  19631. light.transferToEffect(effect, "vLightData" + lightIndex);
  19632. }
  19633. else if (light instanceof BABYLON.SpotLight) {
  19634. // Spot Light
  19635. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19636. }
  19637. else if (light instanceof BABYLON.HemisphericLight) {
  19638. // Hemispheric Light
  19639. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19640. }
  19641. };
  19642. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19643. var lightIndex = 0;
  19644. var depthValuesAlreadySet = false;
  19645. for (var index = 0; index < scene.lights.length; index++) {
  19646. var light = scene.lights[index];
  19647. if (!light.isEnabled()) {
  19648. continue;
  19649. }
  19650. if (!light.canAffectMesh(mesh)) {
  19651. continue;
  19652. }
  19653. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19654. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19655. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19656. if (defines["SPECULARTERM"]) {
  19657. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19658. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19659. }
  19660. // Shadows
  19661. if (scene.shadowsEnabled) {
  19662. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19663. }
  19664. lightIndex++;
  19665. if (lightIndex === maxSimultaneousLights)
  19666. break;
  19667. }
  19668. };
  19669. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19670. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19671. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19672. effect.setColor3("vFogColor", scene.fogColor);
  19673. }
  19674. };
  19675. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19676. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19677. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19678. }
  19679. };
  19680. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19681. if (defines["LOGARITHMICDEPTH"]) {
  19682. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19683. }
  19684. };
  19685. MaterialHelper.BindClipPlane = function (effect, scene) {
  19686. if (scene.clipPlane) {
  19687. var clipPlane = scene.clipPlane;
  19688. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19689. }
  19690. };
  19691. return MaterialHelper;
  19692. })();
  19693. BABYLON.MaterialHelper = MaterialHelper;
  19694. })(BABYLON || (BABYLON = {}));
  19695. var BABYLON;
  19696. (function (BABYLON) {
  19697. var FresnelParameters = (function () {
  19698. function FresnelParameters() {
  19699. this.isEnabled = true;
  19700. this.leftColor = BABYLON.Color3.White();
  19701. this.rightColor = BABYLON.Color3.Black();
  19702. this.bias = 0;
  19703. this.power = 1;
  19704. }
  19705. FresnelParameters.prototype.clone = function () {
  19706. var newFresnelParameters = new FresnelParameters();
  19707. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19708. return new FresnelParameters;
  19709. };
  19710. FresnelParameters.prototype.serialize = function () {
  19711. var serializationObject = {};
  19712. serializationObject.isEnabled = this.isEnabled;
  19713. serializationObject.leftColor = this.leftColor;
  19714. serializationObject.rightColor = this.rightColor;
  19715. serializationObject.bias = this.bias;
  19716. serializationObject.power = this.power;
  19717. return serializationObject;
  19718. };
  19719. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19720. var fresnelParameters = new FresnelParameters();
  19721. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19722. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19723. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19724. fresnelParameters.bias = parsedFresnelParameters.bias;
  19725. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19726. return fresnelParameters;
  19727. };
  19728. return FresnelParameters;
  19729. })();
  19730. BABYLON.FresnelParameters = FresnelParameters;
  19731. })(BABYLON || (BABYLON = {}));
  19732. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19733. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19734. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19735. 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;
  19736. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19737. };
  19738. var BABYLON;
  19739. (function (BABYLON) {
  19740. var MaterialDefines = (function () {
  19741. function MaterialDefines() {
  19742. }
  19743. MaterialDefines.prototype.isEqual = function (other) {
  19744. for (var index = 0; index < this._keys.length; index++) {
  19745. var prop = this._keys[index];
  19746. if (this[prop] !== other[prop]) {
  19747. return false;
  19748. }
  19749. }
  19750. return true;
  19751. };
  19752. MaterialDefines.prototype.cloneTo = function (other) {
  19753. for (var index = 0; index < this._keys.length; index++) {
  19754. var prop = this._keys[index];
  19755. other[prop] = this[prop];
  19756. }
  19757. };
  19758. MaterialDefines.prototype.reset = function () {
  19759. for (var index = 0; index < this._keys.length; index++) {
  19760. var prop = this._keys[index];
  19761. if (typeof (this[prop]) === "number") {
  19762. this[prop] = 0;
  19763. }
  19764. else {
  19765. this[prop] = false;
  19766. }
  19767. }
  19768. };
  19769. MaterialDefines.prototype.toString = function () {
  19770. var result = "";
  19771. for (var index = 0; index < this._keys.length; index++) {
  19772. var prop = this._keys[index];
  19773. if (typeof (this[prop]) === "number") {
  19774. result += "#define " + prop + " " + this[prop] + "\n";
  19775. }
  19776. else if (this[prop]) {
  19777. result += "#define " + prop + "\n";
  19778. }
  19779. }
  19780. return result;
  19781. };
  19782. return MaterialDefines;
  19783. })();
  19784. BABYLON.MaterialDefines = MaterialDefines;
  19785. var Material = (function () {
  19786. function Material(name, scene, doNotAdd) {
  19787. this.name = name;
  19788. this.checkReadyOnEveryCall = false;
  19789. this.checkReadyOnlyOnce = false;
  19790. this.state = "";
  19791. this.alpha = 1.0;
  19792. this.backFaceCulling = true;
  19793. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19794. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19795. this.disableDepthWrite = false;
  19796. this.fogEnabled = true;
  19797. this.pointSize = 1.0;
  19798. this.zOffset = 0;
  19799. this._wasPreviouslyReady = false;
  19800. this._fillMode = Material.TriangleFillMode;
  19801. this.id = name;
  19802. this._scene = scene;
  19803. if (!doNotAdd) {
  19804. scene.materials.push(this);
  19805. }
  19806. }
  19807. Object.defineProperty(Material, "TriangleFillMode", {
  19808. get: function () {
  19809. return Material._TriangleFillMode;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Material, "WireFrameFillMode", {
  19815. get: function () {
  19816. return Material._WireFrameFillMode;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Material, "PointFillMode", {
  19822. get: function () {
  19823. return Material._PointFillMode;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19829. get: function () {
  19830. return Material._ClockWiseSideOrientation;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19836. get: function () {
  19837. return Material._CounterClockWiseSideOrientation;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Material.prototype, "wireframe", {
  19843. get: function () {
  19844. return this._fillMode === Material.WireFrameFillMode;
  19845. },
  19846. set: function (value) {
  19847. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Material.prototype, "pointsCloud", {
  19853. get: function () {
  19854. return this._fillMode === Material.PointFillMode;
  19855. },
  19856. set: function (value) {
  19857. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(Material.prototype, "fillMode", {
  19863. get: function () {
  19864. return this._fillMode;
  19865. },
  19866. set: function (value) {
  19867. this._fillMode = value;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. Object.defineProperty(Material.prototype, "isFrozen", {
  19873. get: function () {
  19874. return this.checkReadyOnlyOnce;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Material.prototype.freeze = function () {
  19880. this.checkReadyOnlyOnce = true;
  19881. };
  19882. Material.prototype.unfreeze = function () {
  19883. this.checkReadyOnlyOnce = false;
  19884. };
  19885. Material.prototype.isReady = function (mesh, useInstances) {
  19886. return true;
  19887. };
  19888. Material.prototype.getEffect = function () {
  19889. return this._effect;
  19890. };
  19891. Material.prototype.getScene = function () {
  19892. return this._scene;
  19893. };
  19894. Material.prototype.needAlphaBlending = function () {
  19895. return (this.alpha < 1.0);
  19896. };
  19897. Material.prototype.needAlphaTesting = function () {
  19898. return false;
  19899. };
  19900. Material.prototype.getAlphaTestTexture = function () {
  19901. return null;
  19902. };
  19903. Material.prototype.trackCreation = function (onCompiled, onError) {
  19904. };
  19905. Material.prototype.markDirty = function () {
  19906. this._wasPreviouslyReady = false;
  19907. };
  19908. Material.prototype._preBind = function () {
  19909. var engine = this._scene.getEngine();
  19910. engine.enableEffect(this._effect);
  19911. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19912. };
  19913. Material.prototype.bind = function (world, mesh) {
  19914. this._scene._cachedMaterial = this;
  19915. if (this.onBind) {
  19916. this.onBind(this, mesh);
  19917. }
  19918. if (this.disableDepthWrite) {
  19919. var engine = this._scene.getEngine();
  19920. this._cachedDepthWriteState = engine.getDepthWrite();
  19921. engine.setDepthWrite(false);
  19922. }
  19923. };
  19924. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19925. };
  19926. Material.prototype.unbind = function () {
  19927. if (this.disableDepthWrite) {
  19928. var engine = this._scene.getEngine();
  19929. engine.setDepthWrite(this._cachedDepthWriteState);
  19930. }
  19931. };
  19932. Material.prototype.clone = function (name) {
  19933. return null;
  19934. };
  19935. Material.prototype.getBindedMeshes = function () {
  19936. var result = new Array();
  19937. for (var index = 0; index < this._scene.meshes.length; index++) {
  19938. var mesh = this._scene.meshes[index];
  19939. if (mesh.material === this) {
  19940. result.push(mesh);
  19941. }
  19942. }
  19943. return result;
  19944. };
  19945. Material.prototype.dispose = function (forceDisposeEffect) {
  19946. // Animations
  19947. this.getScene().stopAnimation(this);
  19948. // Remove from scene
  19949. var index = this._scene.materials.indexOf(this);
  19950. if (index >= 0) {
  19951. this._scene.materials.splice(index, 1);
  19952. }
  19953. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19954. if (forceDisposeEffect && this._effect) {
  19955. this._scene.getEngine()._releaseEffect(this._effect);
  19956. this._effect = null;
  19957. }
  19958. // Remove from meshes
  19959. for (index = 0; index < this._scene.meshes.length; index++) {
  19960. var mesh = this._scene.meshes[index];
  19961. if (mesh.material === this) {
  19962. mesh.material = null;
  19963. }
  19964. }
  19965. // Callback
  19966. if (this.onDispose) {
  19967. this.onDispose();
  19968. }
  19969. };
  19970. Material.prototype.serialize = function () {
  19971. return BABYLON.SerializationHelper.Serialize(this);
  19972. };
  19973. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19974. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19975. multiMaterial.id = parsedMultiMaterial.id;
  19976. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19977. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19978. var subMatId = parsedMultiMaterial.materials[matIndex];
  19979. if (subMatId) {
  19980. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19981. }
  19982. else {
  19983. multiMaterial.subMaterials.push(null);
  19984. }
  19985. }
  19986. return multiMaterial;
  19987. };
  19988. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19989. if (!parsedMaterial.customType) {
  19990. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19991. }
  19992. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19993. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19994. ;
  19995. };
  19996. Material._TriangleFillMode = 0;
  19997. Material._WireFrameFillMode = 1;
  19998. Material._PointFillMode = 2;
  19999. Material._ClockWiseSideOrientation = 0;
  20000. Material._CounterClockWiseSideOrientation = 1;
  20001. __decorate([
  20002. BABYLON.serialize()
  20003. ], Material.prototype, "id", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  20007. __decorate([
  20008. BABYLON.serialize()
  20009. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  20010. __decorate([
  20011. BABYLON.serialize()
  20012. ], Material.prototype, "state", void 0);
  20013. __decorate([
  20014. BABYLON.serialize()
  20015. ], Material.prototype, "alpha", void 0);
  20016. __decorate([
  20017. BABYLON.serialize()
  20018. ], Material.prototype, "backFaceCulling", void 0);
  20019. __decorate([
  20020. BABYLON.serialize()
  20021. ], Material.prototype, "sideOrientation", void 0);
  20022. __decorate([
  20023. BABYLON.serialize()
  20024. ], Material.prototype, "alphaMode", void 0);
  20025. __decorate([
  20026. BABYLON.serialize()
  20027. ], Material.prototype, "disableDepthWrite", void 0);
  20028. __decorate([
  20029. BABYLON.serialize()
  20030. ], Material.prototype, "fogEnabled", void 0);
  20031. __decorate([
  20032. BABYLON.serialize()
  20033. ], Material.prototype, "pointSize", void 0);
  20034. __decorate([
  20035. BABYLON.serialize()
  20036. ], Material.prototype, "zOffset", void 0);
  20037. __decorate([
  20038. BABYLON.serialize()
  20039. ], Material.prototype, "wireframe", null);
  20040. __decorate([
  20041. BABYLON.serialize()
  20042. ], Material.prototype, "pointsCloud", null);
  20043. __decorate([
  20044. BABYLON.serialize()
  20045. ], Material.prototype, "fillMode", null);
  20046. return Material;
  20047. })();
  20048. BABYLON.Material = Material;
  20049. })(BABYLON || (BABYLON = {}));
  20050. var BABYLON;
  20051. (function (BABYLON) {
  20052. var StandardMaterialDefines = (function (_super) {
  20053. __extends(StandardMaterialDefines, _super);
  20054. function StandardMaterialDefines() {
  20055. _super.call(this);
  20056. this.DIFFUSE = false;
  20057. this.AMBIENT = false;
  20058. this.OPACITY = false;
  20059. this.OPACITYRGB = false;
  20060. this.REFLECTION = false;
  20061. this.EMISSIVE = false;
  20062. this.SPECULAR = false;
  20063. this.BUMP = false;
  20064. this.PARALLAX = false;
  20065. this.PARALLAXOCCLUSION = false;
  20066. this.SPECULAROVERALPHA = false;
  20067. this.CLIPPLANE = false;
  20068. this.ALPHATEST = false;
  20069. this.ALPHAFROMDIFFUSE = false;
  20070. this.POINTSIZE = false;
  20071. this.FOG = false;
  20072. this.LIGHT0 = false;
  20073. this.LIGHT1 = false;
  20074. this.LIGHT2 = false;
  20075. this.LIGHT3 = false;
  20076. this.SPOTLIGHT0 = false;
  20077. this.SPOTLIGHT1 = false;
  20078. this.SPOTLIGHT2 = false;
  20079. this.SPOTLIGHT3 = false;
  20080. this.HEMILIGHT0 = false;
  20081. this.HEMILIGHT1 = false;
  20082. this.HEMILIGHT2 = false;
  20083. this.HEMILIGHT3 = false;
  20084. this.POINTLIGHT0 = false;
  20085. this.POINTLIGHT1 = false;
  20086. this.POINTLIGHT2 = false;
  20087. this.POINTLIGHT3 = false;
  20088. this.DIRLIGHT0 = false;
  20089. this.DIRLIGHT1 = false;
  20090. this.DIRLIGHT2 = false;
  20091. this.DIRLIGHT3 = false;
  20092. this.SPECULARTERM = false;
  20093. this.SHADOW0 = false;
  20094. this.SHADOW1 = false;
  20095. this.SHADOW2 = false;
  20096. this.SHADOW3 = false;
  20097. this.SHADOWS = false;
  20098. this.SHADOWVSM0 = false;
  20099. this.SHADOWVSM1 = false;
  20100. this.SHADOWVSM2 = false;
  20101. this.SHADOWVSM3 = false;
  20102. this.SHADOWPCF0 = false;
  20103. this.SHADOWPCF1 = false;
  20104. this.SHADOWPCF2 = false;
  20105. this.SHADOWPCF3 = false;
  20106. this.DIFFUSEFRESNEL = false;
  20107. this.OPACITYFRESNEL = false;
  20108. this.REFLECTIONFRESNEL = false;
  20109. this.REFRACTIONFRESNEL = false;
  20110. this.EMISSIVEFRESNEL = false;
  20111. this.FRESNEL = false;
  20112. this.NORMAL = false;
  20113. this.UV1 = false;
  20114. this.UV2 = false;
  20115. this.VERTEXCOLOR = false;
  20116. this.VERTEXALPHA = false;
  20117. this.NUM_BONE_INFLUENCERS = 0;
  20118. this.BonesPerMesh = 0;
  20119. this.INSTANCES = false;
  20120. this.GLOSSINESS = false;
  20121. this.ROUGHNESS = false;
  20122. this.EMISSIVEASILLUMINATION = false;
  20123. this.LINKEMISSIVEWITHDIFFUSE = false;
  20124. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20125. this.LIGHTMAP = false;
  20126. this.USELIGHTMAPASSHADOWMAP = false;
  20127. this.REFLECTIONMAP_3D = false;
  20128. this.REFLECTIONMAP_SPHERICAL = false;
  20129. this.REFLECTIONMAP_PLANAR = false;
  20130. this.REFLECTIONMAP_CUBIC = false;
  20131. this.REFLECTIONMAP_PROJECTION = false;
  20132. this.REFLECTIONMAP_SKYBOX = false;
  20133. this.REFLECTIONMAP_EXPLICIT = false;
  20134. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20135. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20136. this.INVERTCUBICMAP = false;
  20137. this.LOGARITHMICDEPTH = false;
  20138. this.REFRACTION = false;
  20139. this.REFRACTIONMAP_3D = false;
  20140. this.REFLECTIONOVERALPHA = false;
  20141. this._keys = Object.keys(this);
  20142. }
  20143. return StandardMaterialDefines;
  20144. })(BABYLON.MaterialDefines);
  20145. var StandardMaterial = (function (_super) {
  20146. __extends(StandardMaterial, _super);
  20147. function StandardMaterial(name, scene) {
  20148. var _this = this;
  20149. _super.call(this, name, scene);
  20150. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20151. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20152. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20153. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20154. this.specularPower = 64;
  20155. this.useAlphaFromDiffuseTexture = false;
  20156. this.useEmissiveAsIllumination = false;
  20157. this.linkEmissiveWithDiffuse = false;
  20158. this.useReflectionFresnelFromSpecular = false;
  20159. this.useSpecularOverAlpha = false;
  20160. this.useReflectionOverAlpha = false;
  20161. this.disableLighting = false;
  20162. this.useParallax = false;
  20163. this.useParallaxOcclusion = false;
  20164. this.parallaxScaleBias = 0.05;
  20165. this.roughness = 0;
  20166. this.indexOfRefraction = 0.98;
  20167. this.invertRefractionY = true;
  20168. this.useLightmapAsShadowmap = false;
  20169. this.useGlossinessFromSpecularMapAlpha = false;
  20170. this._renderTargets = new BABYLON.SmartArray(16);
  20171. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20172. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20173. this._defines = new StandardMaterialDefines();
  20174. this._cachedDefines = new StandardMaterialDefines();
  20175. this._cachedDefines.BonesPerMesh = -1;
  20176. this.getRenderTargetTextures = function () {
  20177. _this._renderTargets.reset();
  20178. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20179. _this._renderTargets.push(_this.reflectionTexture);
  20180. }
  20181. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20182. _this._renderTargets.push(_this.refractionTexture);
  20183. }
  20184. return _this._renderTargets;
  20185. };
  20186. }
  20187. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20188. get: function () {
  20189. return this._useLogarithmicDepth;
  20190. },
  20191. set: function (value) {
  20192. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. StandardMaterial.prototype.needAlphaBlending = function () {
  20198. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20199. };
  20200. StandardMaterial.prototype.needAlphaTesting = function () {
  20201. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20202. };
  20203. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20204. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20205. };
  20206. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20207. return this.diffuseTexture;
  20208. };
  20209. // Methods
  20210. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20211. if (!mesh) {
  20212. return true;
  20213. }
  20214. if (this._defines.INSTANCES !== useInstances) {
  20215. return false;
  20216. }
  20217. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20218. return true;
  20219. }
  20220. return false;
  20221. };
  20222. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20223. if (this.isFrozen) {
  20224. if (this._wasPreviouslyReady) {
  20225. return true;
  20226. }
  20227. }
  20228. var scene = this.getScene();
  20229. if (!this.checkReadyOnEveryCall) {
  20230. if (this._renderId === scene.getRenderId()) {
  20231. if (this._checkCache(scene, mesh, useInstances)) {
  20232. return true;
  20233. }
  20234. }
  20235. }
  20236. var engine = scene.getEngine();
  20237. var needNormals = false;
  20238. var needUVs = false;
  20239. this._defines.reset();
  20240. // Textures
  20241. if (scene.texturesEnabled) {
  20242. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20243. if (!this.diffuseTexture.isReady()) {
  20244. return false;
  20245. }
  20246. else {
  20247. needUVs = true;
  20248. this._defines.DIFFUSE = true;
  20249. }
  20250. }
  20251. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20252. if (!this.ambientTexture.isReady()) {
  20253. return false;
  20254. }
  20255. else {
  20256. needUVs = true;
  20257. this._defines.AMBIENT = true;
  20258. }
  20259. }
  20260. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20261. if (!this.opacityTexture.isReady()) {
  20262. return false;
  20263. }
  20264. else {
  20265. needUVs = true;
  20266. this._defines.OPACITY = true;
  20267. if (this.opacityTexture.getAlphaFromRGB) {
  20268. this._defines.OPACITYRGB = true;
  20269. }
  20270. }
  20271. }
  20272. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20273. if (!this.reflectionTexture.isReady()) {
  20274. return false;
  20275. }
  20276. else {
  20277. needNormals = true;
  20278. this._defines.REFLECTION = true;
  20279. if (this.roughness > 0) {
  20280. this._defines.ROUGHNESS = true;
  20281. }
  20282. if (this.useReflectionOverAlpha) {
  20283. this._defines.REFLECTIONOVERALPHA = true;
  20284. }
  20285. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20286. this._defines.INVERTCUBICMAP = true;
  20287. }
  20288. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20289. switch (this.reflectionTexture.coordinatesMode) {
  20290. case BABYLON.Texture.CUBIC_MODE:
  20291. case BABYLON.Texture.INVCUBIC_MODE:
  20292. this._defines.REFLECTIONMAP_CUBIC = true;
  20293. break;
  20294. case BABYLON.Texture.EXPLICIT_MODE:
  20295. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20296. break;
  20297. case BABYLON.Texture.PLANAR_MODE:
  20298. this._defines.REFLECTIONMAP_PLANAR = true;
  20299. break;
  20300. case BABYLON.Texture.PROJECTION_MODE:
  20301. this._defines.REFLECTIONMAP_PROJECTION = true;
  20302. break;
  20303. case BABYLON.Texture.SKYBOX_MODE:
  20304. this._defines.REFLECTIONMAP_SKYBOX = true;
  20305. break;
  20306. case BABYLON.Texture.SPHERICAL_MODE:
  20307. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20308. break;
  20309. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20310. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20311. break;
  20312. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20313. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20314. break;
  20315. }
  20316. }
  20317. }
  20318. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20319. if (!this.emissiveTexture.isReady()) {
  20320. return false;
  20321. }
  20322. else {
  20323. needUVs = true;
  20324. this._defines.EMISSIVE = true;
  20325. }
  20326. }
  20327. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20328. if (!this.lightmapTexture.isReady()) {
  20329. return false;
  20330. }
  20331. else {
  20332. needUVs = true;
  20333. this._defines.LIGHTMAP = true;
  20334. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20335. }
  20336. }
  20337. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20338. if (!this.specularTexture.isReady()) {
  20339. return false;
  20340. }
  20341. else {
  20342. needUVs = true;
  20343. this._defines.SPECULAR = true;
  20344. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20345. }
  20346. }
  20347. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20348. if (!this.bumpTexture.isReady()) {
  20349. return false;
  20350. }
  20351. else {
  20352. needUVs = true;
  20353. this._defines.BUMP = true;
  20354. if (this.useParallax) {
  20355. this._defines.PARALLAX = true;
  20356. if (this.useParallaxOcclusion) {
  20357. this._defines.PARALLAXOCCLUSION = true;
  20358. }
  20359. }
  20360. }
  20361. }
  20362. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20363. if (!this.refractionTexture.isReady()) {
  20364. return false;
  20365. }
  20366. else {
  20367. needUVs = true;
  20368. this._defines.REFRACTION = true;
  20369. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20370. }
  20371. }
  20372. }
  20373. // Effect
  20374. if (scene.clipPlane) {
  20375. this._defines.CLIPPLANE = true;
  20376. }
  20377. if (engine.getAlphaTesting()) {
  20378. this._defines.ALPHATEST = true;
  20379. }
  20380. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20381. this._defines.ALPHAFROMDIFFUSE = true;
  20382. }
  20383. if (this.useEmissiveAsIllumination) {
  20384. this._defines.EMISSIVEASILLUMINATION = true;
  20385. }
  20386. if (this.linkEmissiveWithDiffuse) {
  20387. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20388. }
  20389. if (this.useLogarithmicDepth) {
  20390. this._defines.LOGARITHMICDEPTH = true;
  20391. }
  20392. // Point size
  20393. if (this.pointsCloud || scene.forcePointsCloud) {
  20394. this._defines.POINTSIZE = true;
  20395. }
  20396. // Fog
  20397. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20398. this._defines.FOG = true;
  20399. }
  20400. if (scene.lightsEnabled && !this.disableLighting) {
  20401. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20402. }
  20403. if (StandardMaterial.FresnelEnabled) {
  20404. // Fresnel
  20405. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20406. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20407. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20408. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20409. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20410. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20411. this._defines.DIFFUSEFRESNEL = true;
  20412. }
  20413. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20414. this._defines.OPACITYFRESNEL = true;
  20415. }
  20416. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20417. this._defines.REFLECTIONFRESNEL = true;
  20418. if (this.useReflectionFresnelFromSpecular) {
  20419. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20420. }
  20421. }
  20422. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20423. this._defines.REFRACTIONFRESNEL = true;
  20424. }
  20425. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20426. this._defines.EMISSIVEFRESNEL = true;
  20427. }
  20428. needNormals = true;
  20429. this._defines.FRESNEL = true;
  20430. }
  20431. }
  20432. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20433. this._defines.SPECULAROVERALPHA = true;
  20434. }
  20435. // Attribs
  20436. if (mesh) {
  20437. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20438. this._defines.NORMAL = true;
  20439. }
  20440. if (needUVs) {
  20441. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20442. this._defines.UV1 = true;
  20443. }
  20444. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20445. this._defines.UV2 = true;
  20446. }
  20447. }
  20448. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20449. this._defines.VERTEXCOLOR = true;
  20450. if (mesh.hasVertexAlpha) {
  20451. this._defines.VERTEXALPHA = true;
  20452. }
  20453. }
  20454. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20455. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20456. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20457. }
  20458. // Instances
  20459. if (useInstances) {
  20460. this._defines.INSTANCES = true;
  20461. }
  20462. }
  20463. // Get correct effect
  20464. if (!this._defines.isEqual(this._cachedDefines)) {
  20465. this._defines.cloneTo(this._cachedDefines);
  20466. scene.resetCachedMaterial();
  20467. // Fallbacks
  20468. var fallbacks = new BABYLON.EffectFallbacks();
  20469. if (this._defines.REFLECTION) {
  20470. fallbacks.addFallback(0, "REFLECTION");
  20471. }
  20472. if (this._defines.SPECULAR) {
  20473. fallbacks.addFallback(0, "SPECULAR");
  20474. }
  20475. if (this._defines.BUMP) {
  20476. fallbacks.addFallback(0, "BUMP");
  20477. }
  20478. if (this._defines.PARALLAX) {
  20479. fallbacks.addFallback(1, "PARALLAX");
  20480. }
  20481. if (this._defines.PARALLAXOCCLUSION) {
  20482. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20483. }
  20484. if (this._defines.SPECULAROVERALPHA) {
  20485. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20486. }
  20487. if (this._defines.FOG) {
  20488. fallbacks.addFallback(1, "FOG");
  20489. }
  20490. if (this._defines.POINTSIZE) {
  20491. fallbacks.addFallback(0, "POINTSIZE");
  20492. }
  20493. if (this._defines.LOGARITHMICDEPTH) {
  20494. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20495. }
  20496. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20497. if (this._defines.SPECULARTERM) {
  20498. fallbacks.addFallback(0, "SPECULARTERM");
  20499. }
  20500. if (this._defines.DIFFUSEFRESNEL) {
  20501. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20502. }
  20503. if (this._defines.OPACITYFRESNEL) {
  20504. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20505. }
  20506. if (this._defines.REFLECTIONFRESNEL) {
  20507. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20508. }
  20509. if (this._defines.EMISSIVEFRESNEL) {
  20510. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20511. }
  20512. if (this._defines.FRESNEL) {
  20513. fallbacks.addFallback(4, "FRESNEL");
  20514. }
  20515. //Attributes
  20516. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20517. if (this._defines.NORMAL) {
  20518. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20519. }
  20520. if (this._defines.UV1) {
  20521. attribs.push(BABYLON.VertexBuffer.UVKind);
  20522. }
  20523. if (this._defines.UV2) {
  20524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20525. }
  20526. if (this._defines.VERTEXCOLOR) {
  20527. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20528. }
  20529. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20530. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20531. // Legacy browser patch
  20532. var shaderName = "default";
  20533. if (!scene.getEngine().getCaps().standardDerivatives) {
  20534. shaderName = "legacydefault";
  20535. }
  20536. var join = this._defines.toString();
  20537. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20538. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20539. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20540. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20541. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20542. "vFogInfos", "vFogColor", "pointSize",
  20543. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20544. "mBones",
  20545. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20546. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20547. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20548. "logarithmicDepthConstant"
  20549. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20550. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20551. ], join, fallbacks, this.onCompiled, this.onError);
  20552. }
  20553. if (!this._effect.isReady()) {
  20554. return false;
  20555. }
  20556. this._renderId = scene.getRenderId();
  20557. this._wasPreviouslyReady = true;
  20558. if (mesh) {
  20559. if (!mesh._materialDefines) {
  20560. mesh._materialDefines = new StandardMaterialDefines();
  20561. }
  20562. this._defines.cloneTo(mesh._materialDefines);
  20563. }
  20564. return true;
  20565. };
  20566. StandardMaterial.prototype.unbind = function () {
  20567. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20568. this._effect.setTexture("reflection2DSampler", null);
  20569. }
  20570. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20571. this._effect.setTexture("refraction2DSampler", null);
  20572. }
  20573. _super.prototype.unbind.call(this);
  20574. };
  20575. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20576. this._effect.setMatrix("world", world);
  20577. };
  20578. StandardMaterial.prototype.bind = function (world, mesh) {
  20579. var scene = this.getScene();
  20580. // Matrices
  20581. this.bindOnlyWorldMatrix(world);
  20582. // Bones
  20583. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20584. if (scene.getCachedMaterial() !== this) {
  20585. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20586. if (StandardMaterial.FresnelEnabled) {
  20587. // Fresnel
  20588. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20589. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20590. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20591. }
  20592. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20593. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20594. }
  20595. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20596. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20597. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20598. }
  20599. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20600. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20601. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20602. }
  20603. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20604. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20605. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20606. }
  20607. }
  20608. // Textures
  20609. if (scene.texturesEnabled) {
  20610. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20611. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20612. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20613. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20614. }
  20615. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20616. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20617. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20618. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20619. }
  20620. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20621. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20622. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20623. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20624. }
  20625. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20626. if (this.reflectionTexture.isCube) {
  20627. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20628. }
  20629. else {
  20630. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20631. }
  20632. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20633. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20634. }
  20635. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20636. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20637. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20638. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20639. }
  20640. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20641. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20642. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20643. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20644. }
  20645. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20646. this._effect.setTexture("specularSampler", this.specularTexture);
  20647. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20648. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20649. }
  20650. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20651. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20652. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20653. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20654. }
  20655. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20656. var depth = 1.0;
  20657. if (this.refractionTexture.isCube) {
  20658. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20659. }
  20660. else {
  20661. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20662. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20663. if (this.refractionTexture.depth) {
  20664. depth = this.refractionTexture.depth;
  20665. }
  20666. }
  20667. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20668. }
  20669. }
  20670. // Clip plane
  20671. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20672. // Point size
  20673. if (this.pointsCloud) {
  20674. this._effect.setFloat("pointSize", this.pointSize);
  20675. }
  20676. // Colors
  20677. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20678. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20679. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20680. if (this._defines.SPECULARTERM) {
  20681. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20682. }
  20683. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20684. }
  20685. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20686. // Diffuse
  20687. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20688. // Lights
  20689. if (scene.lightsEnabled && !this.disableLighting) {
  20690. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20691. }
  20692. // View
  20693. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20694. this._effect.setMatrix("view", scene.getViewMatrix());
  20695. }
  20696. // Fog
  20697. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20698. // Log. depth
  20699. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20700. }
  20701. _super.prototype.bind.call(this, world, mesh);
  20702. };
  20703. StandardMaterial.prototype.getAnimatables = function () {
  20704. var results = [];
  20705. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20706. results.push(this.diffuseTexture);
  20707. }
  20708. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20709. results.push(this.ambientTexture);
  20710. }
  20711. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20712. results.push(this.opacityTexture);
  20713. }
  20714. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20715. results.push(this.reflectionTexture);
  20716. }
  20717. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20718. results.push(this.emissiveTexture);
  20719. }
  20720. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20721. results.push(this.specularTexture);
  20722. }
  20723. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20724. results.push(this.bumpTexture);
  20725. }
  20726. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20727. results.push(this.lightmapTexture);
  20728. }
  20729. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20730. results.push(this.refractionTexture);
  20731. }
  20732. return results;
  20733. };
  20734. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20735. if (this.diffuseTexture) {
  20736. this.diffuseTexture.dispose();
  20737. }
  20738. if (this.ambientTexture) {
  20739. this.ambientTexture.dispose();
  20740. }
  20741. if (this.opacityTexture) {
  20742. this.opacityTexture.dispose();
  20743. }
  20744. if (this.reflectionTexture) {
  20745. this.reflectionTexture.dispose();
  20746. }
  20747. if (this.emissiveTexture) {
  20748. this.emissiveTexture.dispose();
  20749. }
  20750. if (this.specularTexture) {
  20751. this.specularTexture.dispose();
  20752. }
  20753. if (this.bumpTexture) {
  20754. this.bumpTexture.dispose();
  20755. }
  20756. if (this.lightmapTexture) {
  20757. this.lightmapTexture.dispose();
  20758. }
  20759. if (this.refractionTexture) {
  20760. this.refractionTexture.dispose();
  20761. }
  20762. _super.prototype.dispose.call(this, forceDisposeEffect);
  20763. };
  20764. StandardMaterial.prototype.clone = function (name) {
  20765. var _this = this;
  20766. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20767. };
  20768. StandardMaterial.prototype.serialize = function () {
  20769. return BABYLON.SerializationHelper.Serialize(this);
  20770. };
  20771. // Statics
  20772. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20773. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20774. };
  20775. // Flags used to enable or disable a type of texture for all Standard Materials
  20776. StandardMaterial.DiffuseTextureEnabled = true;
  20777. StandardMaterial.AmbientTextureEnabled = true;
  20778. StandardMaterial.OpacityTextureEnabled = true;
  20779. StandardMaterial.ReflectionTextureEnabled = true;
  20780. StandardMaterial.EmissiveTextureEnabled = true;
  20781. StandardMaterial.SpecularTextureEnabled = true;
  20782. StandardMaterial.BumpTextureEnabled = true;
  20783. StandardMaterial.FresnelEnabled = true;
  20784. StandardMaterial.LightmapTextureEnabled = true;
  20785. StandardMaterial.RefractionTextureEnabled = true;
  20786. __decorate([
  20787. BABYLON.serializeAsTexture()
  20788. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20789. __decorate([
  20790. BABYLON.serializeAsTexture()
  20791. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20792. __decorate([
  20793. BABYLON.serializeAsTexture()
  20794. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20795. __decorate([
  20796. BABYLON.serializeAsTexture()
  20797. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20798. __decorate([
  20799. BABYLON.serializeAsTexture()
  20800. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20801. __decorate([
  20802. BABYLON.serializeAsTexture()
  20803. ], StandardMaterial.prototype, "specularTexture", void 0);
  20804. __decorate([
  20805. BABYLON.serializeAsTexture()
  20806. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20807. __decorate([
  20808. BABYLON.serializeAsTexture()
  20809. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20810. __decorate([
  20811. BABYLON.serializeAsTexture()
  20812. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20813. __decorate([
  20814. BABYLON.serializeAsColor3("ambient")
  20815. ], StandardMaterial.prototype, "ambientColor", void 0);
  20816. __decorate([
  20817. BABYLON.serializeAsColor3("diffuse")
  20818. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20819. __decorate([
  20820. BABYLON.serializeAsColor3("specular")
  20821. ], StandardMaterial.prototype, "specularColor", void 0);
  20822. __decorate([
  20823. BABYLON.serializeAsColor3("emissive")
  20824. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20825. __decorate([
  20826. BABYLON.serialize()
  20827. ], StandardMaterial.prototype, "specularPower", void 0);
  20828. __decorate([
  20829. BABYLON.serialize()
  20830. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20831. __decorate([
  20832. BABYLON.serialize()
  20833. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20834. __decorate([
  20835. BABYLON.serialize()
  20836. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20837. __decorate([
  20838. BABYLON.serialize()
  20839. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20840. __decorate([
  20841. BABYLON.serialize()
  20842. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20843. __decorate([
  20844. BABYLON.serialize()
  20845. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20846. __decorate([
  20847. BABYLON.serialize()
  20848. ], StandardMaterial.prototype, "disableLighting", void 0);
  20849. __decorate([
  20850. BABYLON.serialize()
  20851. ], StandardMaterial.prototype, "useParallax", void 0);
  20852. __decorate([
  20853. BABYLON.serialize()
  20854. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20855. __decorate([
  20856. BABYLON.serialize()
  20857. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20858. __decorate([
  20859. BABYLON.serialize()
  20860. ], StandardMaterial.prototype, "roughness", void 0);
  20861. __decorate([
  20862. BABYLON.serialize()
  20863. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20864. __decorate([
  20865. BABYLON.serialize()
  20866. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20867. __decorate([
  20868. BABYLON.serialize()
  20869. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20870. __decorate([
  20871. BABYLON.serializeAsFresnelParameters()
  20872. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20873. __decorate([
  20874. BABYLON.serializeAsFresnelParameters()
  20875. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20876. __decorate([
  20877. BABYLON.serializeAsFresnelParameters()
  20878. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20879. __decorate([
  20880. BABYLON.serializeAsFresnelParameters()
  20881. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20882. __decorate([
  20883. BABYLON.serializeAsFresnelParameters()
  20884. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20891. return StandardMaterial;
  20892. })(BABYLON.Material);
  20893. BABYLON.StandardMaterial = StandardMaterial;
  20894. })(BABYLON || (BABYLON = {}));
  20895. var BABYLON;
  20896. (function (BABYLON) {
  20897. var MultiMaterial = (function (_super) {
  20898. __extends(MultiMaterial, _super);
  20899. function MultiMaterial(name, scene) {
  20900. _super.call(this, name, scene, true);
  20901. this.subMaterials = new Array();
  20902. scene.multiMaterials.push(this);
  20903. }
  20904. // Properties
  20905. MultiMaterial.prototype.getSubMaterial = function (index) {
  20906. if (index < 0 || index >= this.subMaterials.length) {
  20907. return this.getScene().defaultMaterial;
  20908. }
  20909. return this.subMaterials[index];
  20910. };
  20911. // Methods
  20912. MultiMaterial.prototype.isReady = function (mesh) {
  20913. for (var index = 0; index < this.subMaterials.length; index++) {
  20914. var subMaterial = this.subMaterials[index];
  20915. if (subMaterial) {
  20916. if (!this.subMaterials[index].isReady(mesh)) {
  20917. return false;
  20918. }
  20919. }
  20920. }
  20921. return true;
  20922. };
  20923. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20924. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20925. for (var index = 0; index < this.subMaterials.length; index++) {
  20926. var subMaterial = null;
  20927. if (cloneChildren) {
  20928. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20929. }
  20930. else {
  20931. subMaterial = this.subMaterials[index];
  20932. }
  20933. newMultiMaterial.subMaterials.push(subMaterial);
  20934. }
  20935. return newMultiMaterial;
  20936. };
  20937. MultiMaterial.prototype.serialize = function () {
  20938. var serializationObject = {};
  20939. serializationObject.name = this.name;
  20940. serializationObject.id = this.id;
  20941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20942. serializationObject.materials = [];
  20943. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20944. var subMat = this.subMaterials[matIndex];
  20945. if (subMat) {
  20946. serializationObject.materials.push(subMat.id);
  20947. }
  20948. else {
  20949. serializationObject.materials.push(null);
  20950. }
  20951. }
  20952. return serializationObject;
  20953. };
  20954. return MultiMaterial;
  20955. })(BABYLON.Material);
  20956. BABYLON.MultiMaterial = MultiMaterial;
  20957. })(BABYLON || (BABYLON = {}));
  20958. var BABYLON;
  20959. (function (BABYLON) {
  20960. var SceneLoader = (function () {
  20961. function SceneLoader() {
  20962. }
  20963. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20964. get: function () {
  20965. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20966. },
  20967. set: function (value) {
  20968. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20974. get: function () {
  20975. return SceneLoader._ShowLoadingScreen;
  20976. },
  20977. set: function (value) {
  20978. SceneLoader._ShowLoadingScreen = value;
  20979. },
  20980. enumerable: true,
  20981. configurable: true
  20982. });
  20983. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20984. var dotPosition = sceneFilename.lastIndexOf(".");
  20985. var queryStringPosition = sceneFilename.indexOf("?");
  20986. if (queryStringPosition === -1) {
  20987. queryStringPosition = sceneFilename.length;
  20988. }
  20989. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20990. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20991. var plugin = this._registeredPlugins[index];
  20992. if (plugin.extensions.indexOf(extension) !== -1) {
  20993. return plugin;
  20994. }
  20995. }
  20996. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20997. };
  20998. // Public functions
  20999. SceneLoader.GetPluginForExtension = function (extension) {
  21000. for (var index = 0; index < this._registeredPlugins.length; index++) {
  21001. var plugin = this._registeredPlugins[index];
  21002. if (plugin.extensions.indexOf(extension) !== -1) {
  21003. return plugin;
  21004. }
  21005. }
  21006. return null;
  21007. };
  21008. SceneLoader.RegisterPlugin = function (plugin) {
  21009. plugin.extensions = plugin.extensions.toLowerCase();
  21010. SceneLoader._registeredPlugins.push(plugin);
  21011. };
  21012. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21013. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21014. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21015. return;
  21016. }
  21017. var loadingToken = {};
  21018. scene._addPendingData(loadingToken);
  21019. var manifestChecked = function (success) {
  21020. scene.database = database;
  21021. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  21022. var importMeshFromData = function (data) {
  21023. var meshes = [];
  21024. var particleSystems = [];
  21025. var skeletons = [];
  21026. try {
  21027. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  21028. if (onerror) {
  21029. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  21030. }
  21031. scene._removePendingData(loadingToken);
  21032. return;
  21033. }
  21034. }
  21035. catch (e) {
  21036. if (onerror) {
  21037. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  21038. }
  21039. scene._removePendingData(loadingToken);
  21040. return;
  21041. }
  21042. if (onsuccess) {
  21043. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  21044. onsuccess(meshes, particleSystems, skeletons);
  21045. scene._removePendingData(loadingToken);
  21046. }
  21047. };
  21048. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21049. // Direct load
  21050. importMeshFromData(sceneFilename.substr(5));
  21051. return;
  21052. }
  21053. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  21054. importMeshFromData(data);
  21055. }, progressCallBack, database);
  21056. };
  21057. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21058. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21059. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21060. }
  21061. else {
  21062. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21063. manifestChecked(true);
  21064. }
  21065. };
  21066. /**
  21067. * Load a scene
  21068. * @param rootUrl a string that defines the root url for scene and resources
  21069. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21070. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21071. */
  21072. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21073. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21074. };
  21075. /**
  21076. * Append a scene
  21077. * @param rootUrl a string that defines the root url for scene and resources
  21078. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21079. * @param scene is the instance of BABYLON.Scene to append to
  21080. */
  21081. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21082. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21083. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21084. return;
  21085. }
  21086. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21087. var database;
  21088. var loadingToken = {};
  21089. scene._addPendingData(loadingToken);
  21090. if (SceneLoader.ShowLoadingScreen) {
  21091. scene.getEngine().displayLoadingUI();
  21092. }
  21093. var loadSceneFromData = function (data) {
  21094. scene.database = database;
  21095. if (!plugin.load(scene, data, rootUrl)) {
  21096. if (onerror) {
  21097. onerror(scene);
  21098. }
  21099. scene._removePendingData(loadingToken);
  21100. scene.getEngine().hideLoadingUI();
  21101. return;
  21102. }
  21103. if (onsuccess) {
  21104. onsuccess(scene);
  21105. }
  21106. scene._removePendingData(loadingToken);
  21107. if (SceneLoader.ShowLoadingScreen) {
  21108. scene.executeWhenReady(function () {
  21109. scene.getEngine().hideLoadingUI();
  21110. });
  21111. }
  21112. };
  21113. var manifestChecked = function (success) {
  21114. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21115. };
  21116. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21117. // Direct load
  21118. loadSceneFromData(sceneFilename.substr(5));
  21119. return;
  21120. }
  21121. if (rootUrl.indexOf("file:") === -1) {
  21122. if (scene.getEngine().enableOfflineSupport) {
  21123. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21124. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21125. }
  21126. else {
  21127. manifestChecked(true);
  21128. }
  21129. }
  21130. else {
  21131. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21132. }
  21133. };
  21134. // Flags
  21135. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21136. SceneLoader._ShowLoadingScreen = true;
  21137. // Members
  21138. SceneLoader._registeredPlugins = new Array();
  21139. return SceneLoader;
  21140. })();
  21141. BABYLON.SceneLoader = SceneLoader;
  21142. ;
  21143. })(BABYLON || (BABYLON = {}));
  21144. var BABYLON;
  21145. (function (BABYLON) {
  21146. var Internals;
  21147. (function (Internals) {
  21148. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21149. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21150. var parsedMaterial = parsedData.materials[index];
  21151. if (parsedMaterial.id === id) {
  21152. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21153. }
  21154. }
  21155. return null;
  21156. };
  21157. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21158. names = (names instanceof Array) ? names : [names];
  21159. for (var i in names) {
  21160. if (mesh.name === names[i]) {
  21161. hierarchyIds.push(mesh.id);
  21162. return true;
  21163. }
  21164. }
  21165. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21166. hierarchyIds.push(mesh.id);
  21167. return true;
  21168. }
  21169. return false;
  21170. };
  21171. BABYLON.SceneLoader.RegisterPlugin({
  21172. extensions: ".babylon",
  21173. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21174. var parsedData = JSON.parse(data);
  21175. var loadedSkeletonsIds = [];
  21176. var loadedMaterialsIds = [];
  21177. var hierarchyIds = [];
  21178. var index;
  21179. var cache;
  21180. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21181. var parsedMesh = parsedData.meshes[index];
  21182. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21183. if (meshesNames instanceof Array) {
  21184. // Remove found mesh name from list.
  21185. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21186. }
  21187. //Geometry?
  21188. if (parsedMesh.geometryId) {
  21189. //does the file contain geometries?
  21190. if (parsedData.geometries) {
  21191. //find the correct geometry and add it to the scene
  21192. var found = false;
  21193. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21194. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21195. return;
  21196. }
  21197. else {
  21198. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21199. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21200. switch (geometryType) {
  21201. case "boxes":
  21202. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21203. break;
  21204. case "spheres":
  21205. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21206. break;
  21207. case "cylinders":
  21208. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21209. break;
  21210. case "toruses":
  21211. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21212. break;
  21213. case "grounds":
  21214. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21215. break;
  21216. case "planes":
  21217. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21218. break;
  21219. case "torusKnots":
  21220. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21221. break;
  21222. case "vertexData":
  21223. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21224. break;
  21225. }
  21226. found = true;
  21227. }
  21228. });
  21229. }
  21230. });
  21231. if (!found) {
  21232. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21233. }
  21234. }
  21235. }
  21236. // Material ?
  21237. if (parsedMesh.materialId) {
  21238. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21239. if (!materialFound && parsedData.multiMaterials) {
  21240. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21241. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21242. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21243. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21244. var subMatId = parsedMultiMaterial.materials[matIndex];
  21245. loadedMaterialsIds.push(subMatId);
  21246. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21247. }
  21248. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21249. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21250. materialFound = true;
  21251. break;
  21252. }
  21253. }
  21254. }
  21255. if (!materialFound) {
  21256. loadedMaterialsIds.push(parsedMesh.materialId);
  21257. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21258. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21259. }
  21260. }
  21261. }
  21262. // Skeleton ?
  21263. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21264. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21265. if (!skeletonAlreadyLoaded) {
  21266. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21267. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21268. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21269. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21270. loadedSkeletonsIds.push(parsedSkeleton.id);
  21271. }
  21272. }
  21273. }
  21274. }
  21275. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21276. meshes.push(mesh);
  21277. }
  21278. }
  21279. // Connecting parents
  21280. var currentMesh;
  21281. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21282. currentMesh = scene.meshes[index];
  21283. if (currentMesh._waitingParentId) {
  21284. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21285. currentMesh._waitingParentId = undefined;
  21286. }
  21287. }
  21288. // freeze and compute world matrix application
  21289. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21290. currentMesh = scene.meshes[index];
  21291. if (currentMesh._waitingFreezeWorldMatrix) {
  21292. currentMesh.freezeWorldMatrix();
  21293. currentMesh._waitingFreezeWorldMatrix = undefined;
  21294. }
  21295. else {
  21296. currentMesh.computeWorldMatrix(true);
  21297. }
  21298. }
  21299. // Particles
  21300. if (parsedData.particleSystems) {
  21301. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21302. var parsedParticleSystem = parsedData.particleSystems[index];
  21303. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21304. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21305. }
  21306. }
  21307. }
  21308. return true;
  21309. },
  21310. load: function (scene, data, rootUrl) {
  21311. var parsedData = JSON.parse(data);
  21312. // Scene
  21313. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21314. scene.autoClear = parsedData.autoClear;
  21315. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21316. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21317. if (parsedData.gravity) {
  21318. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21319. }
  21320. // Fog
  21321. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21322. scene.fogMode = parsedData.fogMode;
  21323. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21324. scene.fogStart = parsedData.fogStart;
  21325. scene.fogEnd = parsedData.fogEnd;
  21326. scene.fogDensity = parsedData.fogDensity;
  21327. }
  21328. //Physics
  21329. if (parsedData.physicsEnabled) {
  21330. var physicsPlugin;
  21331. if (parsedData.physicsEngine === "cannon") {
  21332. physicsPlugin = new BABYLON.CannonJSPlugin();
  21333. }
  21334. else if (parsedData.physicsEngine === "oimo") {
  21335. physicsPlugin = new BABYLON.OimoJSPlugin();
  21336. }
  21337. //else - default engine, which is currently oimo
  21338. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21339. scene.enablePhysics(physicsGravity, physicsPlugin);
  21340. }
  21341. //collisions, if defined. otherwise, default is true
  21342. if (parsedData.collisionsEnabled != undefined) {
  21343. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21344. }
  21345. scene.workerCollisions = !!parsedData.workerCollisions;
  21346. var index;
  21347. var cache;
  21348. // Lights
  21349. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21350. var parsedLight = parsedData.lights[index];
  21351. BABYLON.Light.Parse(parsedLight, scene);
  21352. }
  21353. // Animations
  21354. if (parsedData.animations) {
  21355. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21356. var parsedAnimation = parsedData.animations[index];
  21357. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21358. }
  21359. }
  21360. // Materials
  21361. if (parsedData.materials) {
  21362. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21363. var parsedMaterial = parsedData.materials[index];
  21364. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21365. }
  21366. }
  21367. if (parsedData.multiMaterials) {
  21368. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21369. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21370. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21371. }
  21372. }
  21373. // Skeletons
  21374. if (parsedData.skeletons) {
  21375. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21376. var parsedSkeleton = parsedData.skeletons[index];
  21377. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21378. }
  21379. }
  21380. // Geometries
  21381. var geometries = parsedData.geometries;
  21382. if (geometries) {
  21383. // Boxes
  21384. var boxes = geometries.boxes;
  21385. if (boxes) {
  21386. for (index = 0, cache = boxes.length; index < cache; index++) {
  21387. var parsedBox = boxes[index];
  21388. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21389. }
  21390. }
  21391. // Spheres
  21392. var spheres = geometries.spheres;
  21393. if (spheres) {
  21394. for (index = 0, cache = spheres.length; index < cache; index++) {
  21395. var parsedSphere = spheres[index];
  21396. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21397. }
  21398. }
  21399. // Cylinders
  21400. var cylinders = geometries.cylinders;
  21401. if (cylinders) {
  21402. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21403. var parsedCylinder = cylinders[index];
  21404. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21405. }
  21406. }
  21407. // Toruses
  21408. var toruses = geometries.toruses;
  21409. if (toruses) {
  21410. for (index = 0, cache = toruses.length; index < cache; index++) {
  21411. var parsedTorus = toruses[index];
  21412. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21413. }
  21414. }
  21415. // Grounds
  21416. var grounds = geometries.grounds;
  21417. if (grounds) {
  21418. for (index = 0, cache = grounds.length; index < cache; index++) {
  21419. var parsedGround = grounds[index];
  21420. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21421. }
  21422. }
  21423. // Planes
  21424. var planes = geometries.planes;
  21425. if (planes) {
  21426. for (index = 0, cache = planes.length; index < cache; index++) {
  21427. var parsedPlane = planes[index];
  21428. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21429. }
  21430. }
  21431. // TorusKnots
  21432. var torusKnots = geometries.torusKnots;
  21433. if (torusKnots) {
  21434. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21435. var parsedTorusKnot = torusKnots[index];
  21436. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21437. }
  21438. }
  21439. // VertexData
  21440. var vertexData = geometries.vertexData;
  21441. if (vertexData) {
  21442. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21443. var parsedVertexData = vertexData[index];
  21444. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21445. }
  21446. }
  21447. }
  21448. // Meshes
  21449. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21450. var parsedMesh = parsedData.meshes[index];
  21451. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21452. }
  21453. // Cameras
  21454. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21455. var parsedCamera = parsedData.cameras[index];
  21456. BABYLON.Camera.Parse(parsedCamera, scene);
  21457. }
  21458. if (parsedData.activeCameraID) {
  21459. scene.setActiveCameraByID(parsedData.activeCameraID);
  21460. }
  21461. // Browsing all the graph to connect the dots
  21462. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21463. var camera = scene.cameras[index];
  21464. if (camera._waitingParentId) {
  21465. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21466. camera._waitingParentId = undefined;
  21467. }
  21468. }
  21469. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21470. var light = scene.lights[index];
  21471. if (light._waitingParentId) {
  21472. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21473. light._waitingParentId = undefined;
  21474. }
  21475. }
  21476. // Sounds
  21477. var loadedSounds = [];
  21478. var loadedSound;
  21479. if (BABYLON.AudioEngine && parsedData.sounds) {
  21480. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21481. var parsedSound = parsedData.sounds[index];
  21482. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21483. if (!parsedSound.url)
  21484. parsedSound.url = parsedSound.name;
  21485. if (!loadedSounds[parsedSound.url]) {
  21486. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21487. loadedSounds[parsedSound.url] = loadedSound;
  21488. }
  21489. else {
  21490. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21491. }
  21492. }
  21493. else {
  21494. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21495. }
  21496. }
  21497. }
  21498. loadedSounds = [];
  21499. // Connect parents & children and parse actions
  21500. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21501. var mesh = scene.meshes[index];
  21502. if (mesh._waitingParentId) {
  21503. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21504. mesh._waitingParentId = undefined;
  21505. }
  21506. if (mesh._waitingActions) {
  21507. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21508. mesh._waitingActions = undefined;
  21509. }
  21510. }
  21511. // freeze world matrix application
  21512. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21513. var currentMesh = scene.meshes[index];
  21514. if (currentMesh._waitingFreezeWorldMatrix) {
  21515. currentMesh.freezeWorldMatrix();
  21516. currentMesh._waitingFreezeWorldMatrix = undefined;
  21517. }
  21518. else {
  21519. currentMesh.computeWorldMatrix(true);
  21520. }
  21521. }
  21522. // Particles Systems
  21523. if (parsedData.particleSystems) {
  21524. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21525. var parsedParticleSystem = parsedData.particleSystems[index];
  21526. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21527. }
  21528. }
  21529. // Lens flares
  21530. if (parsedData.lensFlareSystems) {
  21531. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21532. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21533. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21534. }
  21535. }
  21536. // Shadows
  21537. if (parsedData.shadowGenerators) {
  21538. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21539. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21540. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21541. }
  21542. }
  21543. // Actions (scene)
  21544. if (parsedData.actions) {
  21545. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21546. }
  21547. // Finish
  21548. return true;
  21549. }
  21550. });
  21551. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21552. })(BABYLON || (BABYLON = {}));
  21553. var BABYLON;
  21554. (function (BABYLON) {
  21555. var SpriteManager = (function () {
  21556. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21558. this.name = name;
  21559. this.cellSize = cellSize;
  21560. this.sprites = new Array();
  21561. this.renderingGroupId = 0;
  21562. this.layerMask = 0x0FFFFFFF;
  21563. this.fogEnabled = true;
  21564. this.isPickable = false;
  21565. this._vertexDeclaration = [4, 4, 4, 4];
  21566. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21567. this._capacity = capacity;
  21568. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21569. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21570. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21571. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21572. this._scene = scene;
  21573. this._scene.spriteManagers.push(this);
  21574. // VBO
  21575. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21576. var indices = [];
  21577. var index = 0;
  21578. for (var count = 0; count < capacity; count++) {
  21579. indices.push(index);
  21580. indices.push(index + 1);
  21581. indices.push(index + 2);
  21582. indices.push(index);
  21583. indices.push(index + 2);
  21584. indices.push(index + 3);
  21585. index += 4;
  21586. }
  21587. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21588. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21589. // Effects
  21590. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21591. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21592. }
  21593. Object.defineProperty(SpriteManager.prototype, "texture", {
  21594. get: function () {
  21595. return this._spriteTexture;
  21596. },
  21597. set: function (value) {
  21598. this._spriteTexture = value;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21604. var arrayOffset = index * 16;
  21605. if (offsetX === 0)
  21606. offsetX = this._epsilon;
  21607. else if (offsetX === 1)
  21608. offsetX = 1 - this._epsilon;
  21609. if (offsetY === 0)
  21610. offsetY = this._epsilon;
  21611. else if (offsetY === 1)
  21612. offsetY = 1 - this._epsilon;
  21613. this._vertices[arrayOffset] = sprite.position.x;
  21614. this._vertices[arrayOffset + 1] = sprite.position.y;
  21615. this._vertices[arrayOffset + 2] = sprite.position.z;
  21616. this._vertices[arrayOffset + 3] = sprite.angle;
  21617. this._vertices[arrayOffset + 4] = sprite.width;
  21618. this._vertices[arrayOffset + 5] = sprite.height;
  21619. this._vertices[arrayOffset + 6] = offsetX;
  21620. this._vertices[arrayOffset + 7] = offsetY;
  21621. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21622. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21623. var offset = (sprite.cellIndex / rowSize) >> 0;
  21624. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21625. this._vertices[arrayOffset + 11] = offset;
  21626. // Color
  21627. this._vertices[arrayOffset + 12] = sprite.color.r;
  21628. this._vertices[arrayOffset + 13] = sprite.color.g;
  21629. this._vertices[arrayOffset + 14] = sprite.color.b;
  21630. this._vertices[arrayOffset + 15] = sprite.color.a;
  21631. };
  21632. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21633. var count = Math.min(this._capacity, this.sprites.length);
  21634. var min = BABYLON.Vector3.Zero();
  21635. var max = BABYLON.Vector3.Zero();
  21636. var distance = Number.MAX_VALUE;
  21637. var currentSprite;
  21638. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21639. var cameraView = camera.getViewMatrix();
  21640. for (var index = 0; index < count; index++) {
  21641. var sprite = this.sprites[index];
  21642. if (!sprite) {
  21643. continue;
  21644. }
  21645. if (predicate) {
  21646. if (!predicate(sprite)) {
  21647. continue;
  21648. }
  21649. }
  21650. else if (!sprite.isPickable) {
  21651. continue;
  21652. }
  21653. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21654. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21655. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21656. if (ray.intersectsBoxMinMax(min, max)) {
  21657. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21658. if (distance > currentDistance) {
  21659. distance = currentDistance;
  21660. currentSprite = sprite;
  21661. if (fastCheck) {
  21662. break;
  21663. }
  21664. }
  21665. }
  21666. }
  21667. if (currentSprite) {
  21668. var result = new BABYLON.PickingInfo();
  21669. result.hit = true;
  21670. result.pickedSprite = currentSprite;
  21671. result.distance = distance;
  21672. return result;
  21673. }
  21674. return null;
  21675. };
  21676. SpriteManager.prototype.render = function () {
  21677. // Check
  21678. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21679. return;
  21680. var engine = this._scene.getEngine();
  21681. var baseSize = this._spriteTexture.getBaseSize();
  21682. // Sprites
  21683. var deltaTime = engine.getDeltaTime();
  21684. var max = Math.min(this._capacity, this.sprites.length);
  21685. var rowSize = baseSize.width / this.cellSize;
  21686. var offset = 0;
  21687. for (var index = 0; index < max; index++) {
  21688. var sprite = this.sprites[index];
  21689. if (!sprite) {
  21690. continue;
  21691. }
  21692. sprite._animate(deltaTime);
  21693. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21694. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21695. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21696. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21697. }
  21698. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21699. // Render
  21700. var effect = this._effectBase;
  21701. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21702. effect = this._effectFog;
  21703. }
  21704. engine.enableEffect(effect);
  21705. var viewMatrix = this._scene.getViewMatrix();
  21706. effect.setTexture("diffuseSampler", this._spriteTexture);
  21707. effect.setMatrix("view", viewMatrix);
  21708. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21709. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21710. // Fog
  21711. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21712. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21713. effect.setColor3("vFogColor", this._scene.fogColor);
  21714. }
  21715. // VBOs
  21716. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21717. // Draw order
  21718. engine.setDepthFunctionToLessOrEqual();
  21719. effect.setBool("alphaTest", true);
  21720. engine.setColorWrite(false);
  21721. engine.draw(true, 0, max * 6);
  21722. engine.setColorWrite(true);
  21723. effect.setBool("alphaTest", false);
  21724. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21725. engine.draw(true, 0, max * 6);
  21726. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21727. };
  21728. SpriteManager.prototype.dispose = function () {
  21729. if (this._vertexBuffer) {
  21730. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21731. this._vertexBuffer = null;
  21732. }
  21733. if (this._indexBuffer) {
  21734. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21735. this._indexBuffer = null;
  21736. }
  21737. if (this._spriteTexture) {
  21738. this._spriteTexture.dispose();
  21739. this._spriteTexture = null;
  21740. }
  21741. // Remove from scene
  21742. var index = this._scene.spriteManagers.indexOf(this);
  21743. this._scene.spriteManagers.splice(index, 1);
  21744. // Callback
  21745. if (this.onDispose) {
  21746. this.onDispose();
  21747. }
  21748. };
  21749. return SpriteManager;
  21750. })();
  21751. BABYLON.SpriteManager = SpriteManager;
  21752. })(BABYLON || (BABYLON = {}));
  21753. var BABYLON;
  21754. (function (BABYLON) {
  21755. var Sprite = (function () {
  21756. function Sprite(name, manager) {
  21757. this.name = name;
  21758. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21759. this.width = 1.0;
  21760. this.height = 1.0;
  21761. this.angle = 0;
  21762. this.cellIndex = 0;
  21763. this.invertU = 0;
  21764. this.invertV = 0;
  21765. this.animations = new Array();
  21766. this.isPickable = false;
  21767. this._animationStarted = false;
  21768. this._loopAnimation = false;
  21769. this._fromIndex = 0;
  21770. this._toIndex = 0;
  21771. this._delay = 0;
  21772. this._direction = 1;
  21773. this._frameCount = 0;
  21774. this._time = 0;
  21775. this._manager = manager;
  21776. this._manager.sprites.push(this);
  21777. this.position = BABYLON.Vector3.Zero();
  21778. }
  21779. Object.defineProperty(Sprite.prototype, "size", {
  21780. get: function () {
  21781. return this.width;
  21782. },
  21783. set: function (value) {
  21784. this.width = value;
  21785. this.height = value;
  21786. },
  21787. enumerable: true,
  21788. configurable: true
  21789. });
  21790. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21791. this._fromIndex = from;
  21792. this._toIndex = to;
  21793. this._loopAnimation = loop;
  21794. this._delay = delay;
  21795. this._animationStarted = true;
  21796. this._direction = from < to ? 1 : -1;
  21797. this.cellIndex = from;
  21798. this._time = 0;
  21799. };
  21800. Sprite.prototype.stopAnimation = function () {
  21801. this._animationStarted = false;
  21802. };
  21803. Sprite.prototype._animate = function (deltaTime) {
  21804. if (!this._animationStarted)
  21805. return;
  21806. this._time += deltaTime;
  21807. if (this._time > this._delay) {
  21808. this._time = this._time % this._delay;
  21809. this.cellIndex += this._direction;
  21810. if (this.cellIndex == this._toIndex) {
  21811. if (this._loopAnimation) {
  21812. this.cellIndex = this._fromIndex;
  21813. }
  21814. else {
  21815. this._animationStarted = false;
  21816. if (this.disposeWhenFinishedAnimating) {
  21817. this.dispose();
  21818. }
  21819. }
  21820. }
  21821. }
  21822. };
  21823. Sprite.prototype.dispose = function () {
  21824. for (var i = 0; i < this._manager.sprites.length; i++) {
  21825. if (this._manager.sprites[i] == this) {
  21826. this._manager.sprites.splice(i, 1);
  21827. }
  21828. }
  21829. };
  21830. return Sprite;
  21831. })();
  21832. BABYLON.Sprite = Sprite;
  21833. })(BABYLON || (BABYLON = {}));
  21834. var BABYLON;
  21835. (function (BABYLON) {
  21836. var Layer = (function () {
  21837. function Layer(name, imgUrl, scene, isBackground, color) {
  21838. this.name = name;
  21839. this.scale = new BABYLON.Vector2(1, 1);
  21840. this.offset = new BABYLON.Vector2(0, 0);
  21841. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21842. this._vertexDeclaration = [2];
  21843. this._vertexStrideSize = 2 * 4;
  21844. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21845. this.isBackground = isBackground === undefined ? true : isBackground;
  21846. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21847. this._scene = scene;
  21848. this._scene.layers.push(this);
  21849. // VBO
  21850. var vertices = [];
  21851. vertices.push(1, 1);
  21852. vertices.push(-1, 1);
  21853. vertices.push(-1, -1);
  21854. vertices.push(1, -1);
  21855. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21856. // Indices
  21857. var indices = [];
  21858. indices.push(0);
  21859. indices.push(1);
  21860. indices.push(2);
  21861. indices.push(0);
  21862. indices.push(2);
  21863. indices.push(3);
  21864. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21865. // Effects
  21866. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21867. }
  21868. Layer.prototype.render = function () {
  21869. // Check
  21870. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21871. return;
  21872. var engine = this._scene.getEngine();
  21873. // Render
  21874. engine.enableEffect(this._effect);
  21875. engine.setState(false);
  21876. // Texture
  21877. this._effect.setTexture("textureSampler", this.texture);
  21878. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21879. // Color
  21880. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21881. // Scale / offset
  21882. this._effect.setVector2("offset", this.offset);
  21883. this._effect.setVector2("scale", this.scale);
  21884. // VBOs
  21885. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21886. // Draw order
  21887. engine.setAlphaMode(this.alphaBlendingMode);
  21888. engine.draw(true, 0, 6);
  21889. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21890. };
  21891. Layer.prototype.dispose = function () {
  21892. if (this._vertexBuffer) {
  21893. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21894. this._vertexBuffer = null;
  21895. }
  21896. if (this._indexBuffer) {
  21897. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21898. this._indexBuffer = null;
  21899. }
  21900. if (this.texture) {
  21901. this.texture.dispose();
  21902. this.texture = null;
  21903. }
  21904. // Remove from scene
  21905. var index = this._scene.layers.indexOf(this);
  21906. this._scene.layers.splice(index, 1);
  21907. // Callback
  21908. if (this.onDispose) {
  21909. this.onDispose();
  21910. }
  21911. };
  21912. return Layer;
  21913. })();
  21914. BABYLON.Layer = Layer;
  21915. })(BABYLON || (BABYLON = {}));
  21916. var BABYLON;
  21917. (function (BABYLON) {
  21918. var Particle = (function () {
  21919. function Particle() {
  21920. this.position = BABYLON.Vector3.Zero();
  21921. this.direction = BABYLON.Vector3.Zero();
  21922. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21923. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21924. this.lifeTime = 1.0;
  21925. this.age = 0;
  21926. this.size = 0;
  21927. this.angle = 0;
  21928. this.angularSpeed = 0;
  21929. }
  21930. Particle.prototype.copyTo = function (other) {
  21931. other.position.copyFrom(this.position);
  21932. other.direction.copyFrom(this.direction);
  21933. other.color.copyFrom(this.color);
  21934. other.colorStep.copyFrom(this.colorStep);
  21935. other.lifeTime = this.lifeTime;
  21936. other.age = this.age;
  21937. other.size = this.size;
  21938. other.angle = this.angle;
  21939. other.angularSpeed = this.angularSpeed;
  21940. };
  21941. return Particle;
  21942. })();
  21943. BABYLON.Particle = Particle;
  21944. })(BABYLON || (BABYLON = {}));
  21945. var BABYLON;
  21946. (function (BABYLON) {
  21947. var randomNumber = function (min, max) {
  21948. if (min === max) {
  21949. return (min);
  21950. }
  21951. var random = Math.random();
  21952. return ((random * (max - min)) + min);
  21953. };
  21954. var ParticleSystem = (function () {
  21955. function ParticleSystem(name, capacity, scene, customEffect) {
  21956. var _this = this;
  21957. this.name = name;
  21958. // Members
  21959. this.animations = [];
  21960. this.renderingGroupId = 0;
  21961. this.emitter = null;
  21962. this.emitRate = 10;
  21963. this.manualEmitCount = -1;
  21964. this.updateSpeed = 0.01;
  21965. this.targetStopDuration = 0;
  21966. this.disposeOnStop = false;
  21967. this.minEmitPower = 1;
  21968. this.maxEmitPower = 1;
  21969. this.minLifeTime = 1;
  21970. this.maxLifeTime = 1;
  21971. this.minSize = 1;
  21972. this.maxSize = 1;
  21973. this.minAngularSpeed = 0;
  21974. this.maxAngularSpeed = 0;
  21975. this.layerMask = 0x0FFFFFFF;
  21976. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21977. this.forceDepthWrite = false;
  21978. this.gravity = BABYLON.Vector3.Zero();
  21979. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21980. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21981. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21982. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21983. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21984. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21985. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21986. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21987. this.particles = new Array();
  21988. this._vertexDeclaration = [3, 4, 4];
  21989. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21990. this._stockParticles = new Array();
  21991. this._newPartsExcess = 0;
  21992. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21993. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21994. this._scaledDirection = BABYLON.Vector3.Zero();
  21995. this._scaledGravity = BABYLON.Vector3.Zero();
  21996. this._currentRenderId = -1;
  21997. this._started = false;
  21998. this._stopped = false;
  21999. this._actualFrame = 0;
  22000. this.id = name;
  22001. this._capacity = capacity;
  22002. this._scene = scene;
  22003. this._customEffect = customEffect;
  22004. scene.particleSystems.push(this);
  22005. // VBO
  22006. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  22007. var indices = [];
  22008. var index = 0;
  22009. for (var count = 0; count < capacity; count++) {
  22010. indices.push(index);
  22011. indices.push(index + 1);
  22012. indices.push(index + 2);
  22013. indices.push(index);
  22014. indices.push(index + 2);
  22015. indices.push(index + 3);
  22016. index += 4;
  22017. }
  22018. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22019. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22020. // Default behaviors
  22021. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  22022. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  22023. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  22024. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  22025. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  22026. };
  22027. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  22028. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  22029. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  22030. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  22031. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  22032. };
  22033. this.updateFunction = function (particles) {
  22034. for (var index = 0; index < particles.length; index++) {
  22035. var particle = particles[index];
  22036. particle.age += _this._scaledUpdateSpeed;
  22037. if (particle.age >= particle.lifeTime) {
  22038. _this.recycleParticle(particle);
  22039. index--;
  22040. continue;
  22041. }
  22042. else {
  22043. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22044. particle.color.addInPlace(_this._scaledColorStep);
  22045. if (particle.color.a < 0)
  22046. particle.color.a = 0;
  22047. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22048. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22049. particle.position.addInPlace(_this._scaledDirection);
  22050. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22051. particle.direction.addInPlace(_this._scaledGravity);
  22052. }
  22053. }
  22054. };
  22055. }
  22056. ParticleSystem.prototype.recycleParticle = function (particle) {
  22057. var lastParticle = this.particles.pop();
  22058. if (lastParticle !== particle) {
  22059. lastParticle.copyTo(particle);
  22060. this._stockParticles.push(lastParticle);
  22061. }
  22062. };
  22063. ParticleSystem.prototype.getCapacity = function () {
  22064. return this._capacity;
  22065. };
  22066. ParticleSystem.prototype.isAlive = function () {
  22067. return this._alive;
  22068. };
  22069. ParticleSystem.prototype.isStarted = function () {
  22070. return this._started;
  22071. };
  22072. ParticleSystem.prototype.start = function () {
  22073. this._started = true;
  22074. this._stopped = false;
  22075. this._actualFrame = 0;
  22076. };
  22077. ParticleSystem.prototype.stop = function () {
  22078. this._stopped = true;
  22079. };
  22080. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22081. var offset = index * 11;
  22082. this._vertices[offset] = particle.position.x;
  22083. this._vertices[offset + 1] = particle.position.y;
  22084. this._vertices[offset + 2] = particle.position.z;
  22085. this._vertices[offset + 3] = particle.color.r;
  22086. this._vertices[offset + 4] = particle.color.g;
  22087. this._vertices[offset + 5] = particle.color.b;
  22088. this._vertices[offset + 6] = particle.color.a;
  22089. this._vertices[offset + 7] = particle.angle;
  22090. this._vertices[offset + 8] = particle.size;
  22091. this._vertices[offset + 9] = offsetX;
  22092. this._vertices[offset + 10] = offsetY;
  22093. };
  22094. ParticleSystem.prototype._update = function (newParticles) {
  22095. // Update current
  22096. this._alive = this.particles.length > 0;
  22097. this.updateFunction(this.particles);
  22098. // Add new ones
  22099. var worldMatrix;
  22100. if (this.emitter.position) {
  22101. worldMatrix = this.emitter.getWorldMatrix();
  22102. }
  22103. else {
  22104. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22105. }
  22106. var particle;
  22107. for (var index = 0; index < newParticles; index++) {
  22108. if (this.particles.length === this._capacity) {
  22109. break;
  22110. }
  22111. if (this._stockParticles.length !== 0) {
  22112. particle = this._stockParticles.pop();
  22113. particle.age = 0;
  22114. }
  22115. else {
  22116. particle = new BABYLON.Particle();
  22117. }
  22118. this.particles.push(particle);
  22119. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22120. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22121. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22122. particle.size = randomNumber(this.minSize, this.maxSize);
  22123. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22124. this.startPositionFunction(worldMatrix, particle.position, particle);
  22125. var step = randomNumber(0, 1.0);
  22126. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22127. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22128. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22129. }
  22130. };
  22131. ParticleSystem.prototype._getEffect = function () {
  22132. if (this._customEffect) {
  22133. return this._customEffect;
  22134. }
  22135. ;
  22136. var defines = [];
  22137. if (this._scene.clipPlane) {
  22138. defines.push("#define CLIPPLANE");
  22139. }
  22140. // Effect
  22141. var join = defines.join("\n");
  22142. if (this._cachedDefines !== join) {
  22143. this._cachedDefines = join;
  22144. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22145. }
  22146. return this._effect;
  22147. };
  22148. ParticleSystem.prototype.animate = function () {
  22149. if (!this._started)
  22150. return;
  22151. var effect = this._getEffect();
  22152. // Check
  22153. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22154. return;
  22155. if (this._currentRenderId === this._scene.getRenderId()) {
  22156. return;
  22157. }
  22158. this._currentRenderId = this._scene.getRenderId();
  22159. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22160. // determine the number of particles we need to create
  22161. var newParticles;
  22162. if (this.manualEmitCount > -1) {
  22163. newParticles = this.manualEmitCount;
  22164. this._newPartsExcess = 0;
  22165. this.manualEmitCount = 0;
  22166. }
  22167. else {
  22168. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22169. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22170. }
  22171. if (this._newPartsExcess > 1.0) {
  22172. newParticles += this._newPartsExcess >> 0;
  22173. this._newPartsExcess -= this._newPartsExcess >> 0;
  22174. }
  22175. this._alive = false;
  22176. if (!this._stopped) {
  22177. this._actualFrame += this._scaledUpdateSpeed;
  22178. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22179. this.stop();
  22180. }
  22181. else {
  22182. newParticles = 0;
  22183. }
  22184. this._update(newParticles);
  22185. // Stopped?
  22186. if (this._stopped) {
  22187. if (!this._alive) {
  22188. this._started = false;
  22189. if (this.disposeOnStop) {
  22190. this._scene._toBeDisposed.push(this);
  22191. }
  22192. }
  22193. }
  22194. // Update VBO
  22195. var offset = 0;
  22196. for (var index = 0; index < this.particles.length; index++) {
  22197. var particle = this.particles[index];
  22198. this._appendParticleVertex(offset++, particle, 0, 0);
  22199. this._appendParticleVertex(offset++, particle, 1, 0);
  22200. this._appendParticleVertex(offset++, particle, 1, 1);
  22201. this._appendParticleVertex(offset++, particle, 0, 1);
  22202. }
  22203. var engine = this._scene.getEngine();
  22204. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22205. };
  22206. ParticleSystem.prototype.render = function () {
  22207. var effect = this._getEffect();
  22208. // Check
  22209. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22210. return 0;
  22211. var engine = this._scene.getEngine();
  22212. // Render
  22213. engine.enableEffect(effect);
  22214. engine.setState(false);
  22215. var viewMatrix = this._scene.getViewMatrix();
  22216. effect.setTexture("diffuseSampler", this.particleTexture);
  22217. effect.setMatrix("view", viewMatrix);
  22218. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22219. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22220. if (this._scene.clipPlane) {
  22221. var clipPlane = this._scene.clipPlane;
  22222. var invView = viewMatrix.clone();
  22223. invView.invert();
  22224. effect.setMatrix("invView", invView);
  22225. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22226. }
  22227. // VBOs
  22228. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22229. // Draw order
  22230. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22231. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22232. }
  22233. else {
  22234. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22235. }
  22236. if (this.forceDepthWrite) {
  22237. engine.setDepthWrite(true);
  22238. }
  22239. engine.draw(true, 0, this.particles.length * 6);
  22240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22241. return this.particles.length;
  22242. };
  22243. ParticleSystem.prototype.dispose = function () {
  22244. if (this._vertexBuffer) {
  22245. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22246. this._vertexBuffer = null;
  22247. }
  22248. if (this._indexBuffer) {
  22249. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22250. this._indexBuffer = null;
  22251. }
  22252. if (this.particleTexture) {
  22253. this.particleTexture.dispose();
  22254. this.particleTexture = null;
  22255. }
  22256. // Remove from scene
  22257. var index = this._scene.particleSystems.indexOf(this);
  22258. this._scene.particleSystems.splice(index, 1);
  22259. // Callback
  22260. if (this.onDispose) {
  22261. this.onDispose();
  22262. }
  22263. };
  22264. // Clone
  22265. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22266. var result = new ParticleSystem(name, this._capacity, this._scene);
  22267. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22268. if (newEmitter === undefined) {
  22269. newEmitter = this.emitter;
  22270. }
  22271. result.emitter = newEmitter;
  22272. if (this.particleTexture) {
  22273. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22274. }
  22275. result.start();
  22276. return result;
  22277. };
  22278. ParticleSystem.prototype.serialize = function () {
  22279. var serializationObject = {};
  22280. serializationObject.name = this.name;
  22281. serializationObject.id = this.id;
  22282. // Emitter
  22283. if (this.emitter.position) {
  22284. serializationObject.emitterId = this.emitter.id;
  22285. }
  22286. else {
  22287. serializationObject.emitter = this.emitter.asArray();
  22288. }
  22289. serializationObject.capacity = this.getCapacity();
  22290. if (this.particleTexture) {
  22291. serializationObject.textureName = this.particleTexture.name;
  22292. }
  22293. // Animations
  22294. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22295. // Particle system
  22296. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22297. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22298. serializationObject.minSize = this.minSize;
  22299. serializationObject.maxSize = this.maxSize;
  22300. serializationObject.minEmitPower = this.minEmitPower;
  22301. serializationObject.maxEmitPower = this.maxEmitPower;
  22302. serializationObject.minLifeTime = this.minLifeTime;
  22303. serializationObject.maxLifeTime = this.maxLifeTime;
  22304. serializationObject.emitRate = this.emitRate;
  22305. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22306. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22307. serializationObject.gravity = this.gravity.asArray();
  22308. serializationObject.direction1 = this.direction1.asArray();
  22309. serializationObject.direction2 = this.direction2.asArray();
  22310. serializationObject.color1 = this.color1.asArray();
  22311. serializationObject.color2 = this.color2.asArray();
  22312. serializationObject.colorDead = this.colorDead.asArray();
  22313. serializationObject.updateSpeed = this.updateSpeed;
  22314. serializationObject.targetStopDuration = this.targetStopDuration;
  22315. serializationObject.textureMask = this.textureMask.asArray();
  22316. serializationObject.blendMode = this.blendMode;
  22317. return serializationObject;
  22318. };
  22319. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22320. var name = parsedParticleSystem.name;
  22321. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22322. if (parsedParticleSystem.id) {
  22323. particleSystem.id = parsedParticleSystem.id;
  22324. }
  22325. // Texture
  22326. if (parsedParticleSystem.textureName) {
  22327. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22328. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22329. }
  22330. // Emitter
  22331. if (parsedParticleSystem.emitterId) {
  22332. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22333. }
  22334. else {
  22335. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22336. }
  22337. // Animations
  22338. if (parsedParticleSystem.animations) {
  22339. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22340. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22341. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22342. }
  22343. }
  22344. // Particle system
  22345. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22346. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22347. particleSystem.minSize = parsedParticleSystem.minSize;
  22348. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22349. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22350. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22351. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22352. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22353. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22354. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22355. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22356. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22357. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22358. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22359. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22360. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22361. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22362. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22363. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22364. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22365. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22366. particleSystem.start();
  22367. return particleSystem;
  22368. };
  22369. // Statics
  22370. ParticleSystem.BLENDMODE_ONEONE = 0;
  22371. ParticleSystem.BLENDMODE_STANDARD = 1;
  22372. return ParticleSystem;
  22373. })();
  22374. BABYLON.ParticleSystem = ParticleSystem;
  22375. })(BABYLON || (BABYLON = {}));
  22376. var BABYLON;
  22377. (function (BABYLON) {
  22378. var AnimationRange = (function () {
  22379. function AnimationRange(name, from, to) {
  22380. this.name = name;
  22381. this.from = from;
  22382. this.to = to;
  22383. }
  22384. return AnimationRange;
  22385. })();
  22386. BABYLON.AnimationRange = AnimationRange;
  22387. /**
  22388. * Composed of a frame, and an action function
  22389. */
  22390. var AnimationEvent = (function () {
  22391. function AnimationEvent(frame, action, onlyOnce) {
  22392. this.frame = frame;
  22393. this.action = action;
  22394. this.onlyOnce = onlyOnce;
  22395. this.isDone = false;
  22396. }
  22397. return AnimationEvent;
  22398. })();
  22399. BABYLON.AnimationEvent = AnimationEvent;
  22400. var Animation = (function () {
  22401. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  22402. this.name = name;
  22403. this.targetProperty = targetProperty;
  22404. this.framePerSecond = framePerSecond;
  22405. this.dataType = dataType;
  22406. this.loopMode = loopMode;
  22407. this.enableBlending = enableBlending;
  22408. this._offsetsCache = {};
  22409. this._highLimitsCache = {};
  22410. this._stopped = false;
  22411. this._blendingFactor = 0;
  22412. // The set of event that will be linked to this animation
  22413. this._events = new Array();
  22414. this.allowMatricesInterpolation = false;
  22415. this.blendingSpeed = 0.01;
  22416. this._ranges = {};
  22417. this.targetPropertyPath = targetProperty.split(".");
  22418. this.dataType = dataType;
  22419. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22420. }
  22421. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22422. var dataType = undefined;
  22423. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22424. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22425. }
  22426. else if (from instanceof BABYLON.Quaternion) {
  22427. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22428. }
  22429. else if (from instanceof BABYLON.Vector3) {
  22430. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22431. }
  22432. else if (from instanceof BABYLON.Vector2) {
  22433. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22434. }
  22435. else if (from instanceof BABYLON.Color3) {
  22436. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22437. }
  22438. if (dataType == undefined) {
  22439. return null;
  22440. }
  22441. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22442. var keys = [];
  22443. keys.push({ frame: 0, value: from });
  22444. keys.push({ frame: totalFrame, value: to });
  22445. animation.setKeys(keys);
  22446. if (easingFunction !== undefined) {
  22447. animation.setEasingFunction(easingFunction);
  22448. }
  22449. return animation;
  22450. };
  22451. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22452. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22453. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22454. };
  22455. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22456. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22457. node.animations.push(animation);
  22458. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22459. };
  22460. // Methods
  22461. /**
  22462. * Add an event to this animation.
  22463. */
  22464. Animation.prototype.addEvent = function (event) {
  22465. this._events.push(event);
  22466. };
  22467. /**
  22468. * Remove all events found at the given frame
  22469. * @param frame
  22470. */
  22471. Animation.prototype.removeEvents = function (frame) {
  22472. for (var index = 0; index < this._events.length; index++) {
  22473. if (this._events[index].frame === frame) {
  22474. this._events.splice(index, 1);
  22475. index--;
  22476. }
  22477. }
  22478. };
  22479. Animation.prototype.createRange = function (name, from, to) {
  22480. // check name not already in use; could happen for bones after serialized
  22481. if (!this._ranges[name]) {
  22482. this._ranges[name] = new AnimationRange(name, from, to);
  22483. }
  22484. };
  22485. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22486. if (deleteFrames === void 0) { deleteFrames = true; }
  22487. if (this._ranges[name]) {
  22488. if (deleteFrames) {
  22489. var from = this._ranges[name].from;
  22490. var to = this._ranges[name].to;
  22491. // this loop MUST go high to low for multiple splices to work
  22492. for (var key = this._keys.length - 1; key >= 0; key--) {
  22493. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22494. this._keys.splice(key, 1);
  22495. }
  22496. }
  22497. }
  22498. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22499. }
  22500. };
  22501. Animation.prototype.getRange = function (name) {
  22502. return this._ranges[name];
  22503. };
  22504. Animation.prototype.reset = function () {
  22505. this._offsetsCache = {};
  22506. this._highLimitsCache = {};
  22507. this.currentFrame = 0;
  22508. this._blendingFactor = 0;
  22509. this._originalBlendValue = null;
  22510. };
  22511. Animation.prototype.isStopped = function () {
  22512. return this._stopped;
  22513. };
  22514. Animation.prototype.getKeys = function () {
  22515. return this._keys;
  22516. };
  22517. Animation.prototype.getHighestFrame = function () {
  22518. var ret = 0;
  22519. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22520. if (ret < this._keys[key].frame) {
  22521. ret = this._keys[key].frame;
  22522. }
  22523. }
  22524. return ret;
  22525. };
  22526. Animation.prototype.getEasingFunction = function () {
  22527. return this._easingFunction;
  22528. };
  22529. Animation.prototype.setEasingFunction = function (easingFunction) {
  22530. this._easingFunction = easingFunction;
  22531. };
  22532. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22533. return startValue + (endValue - startValue) * gradient;
  22534. };
  22535. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22536. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22537. };
  22538. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22539. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22540. };
  22541. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22542. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22543. };
  22544. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22545. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22546. };
  22547. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22548. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22549. };
  22550. Animation.prototype.clone = function () {
  22551. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22552. if (this._keys) {
  22553. clone.setKeys(this._keys);
  22554. }
  22555. return clone;
  22556. };
  22557. Animation.prototype.setKeys = function (values) {
  22558. this._keys = values.slice(0);
  22559. this._offsetsCache = {};
  22560. this._highLimitsCache = {};
  22561. };
  22562. Animation.prototype._getKeyValue = function (value) {
  22563. if (typeof value === "function") {
  22564. return value();
  22565. }
  22566. return value;
  22567. };
  22568. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22569. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22570. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22571. }
  22572. this.currentFrame = currentFrame;
  22573. // Try to get a hash to find the right key
  22574. 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));
  22575. if (this._keys[startKey].frame >= currentFrame) {
  22576. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22577. startKey--;
  22578. }
  22579. }
  22580. for (var key = startKey; key < this._keys.length; key++) {
  22581. if (this._keys[key + 1].frame >= currentFrame) {
  22582. var startValue = this._getKeyValue(this._keys[key].value);
  22583. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22584. // gradient : percent of currentFrame between the frame inf and the frame sup
  22585. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22586. // check for easingFunction and correction of gradient
  22587. if (this._easingFunction != null) {
  22588. gradient = this._easingFunction.ease(gradient);
  22589. }
  22590. switch (this.dataType) {
  22591. // Float
  22592. case Animation.ANIMATIONTYPE_FLOAT:
  22593. switch (loopMode) {
  22594. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22595. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22596. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22597. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22598. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22599. }
  22600. break;
  22601. // Quaternion
  22602. case Animation.ANIMATIONTYPE_QUATERNION:
  22603. var quaternion = null;
  22604. switch (loopMode) {
  22605. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22606. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22607. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22608. break;
  22609. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22610. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22611. break;
  22612. }
  22613. return quaternion;
  22614. // Vector3
  22615. case Animation.ANIMATIONTYPE_VECTOR3:
  22616. switch (loopMode) {
  22617. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22618. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22619. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22620. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22621. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22622. }
  22623. // Vector2
  22624. case Animation.ANIMATIONTYPE_VECTOR2:
  22625. switch (loopMode) {
  22626. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22627. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22628. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22629. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22630. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22631. }
  22632. // Color3
  22633. case Animation.ANIMATIONTYPE_COLOR3:
  22634. switch (loopMode) {
  22635. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22636. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22637. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22638. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22639. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22640. }
  22641. // Matrix
  22642. case Animation.ANIMATIONTYPE_MATRIX:
  22643. switch (loopMode) {
  22644. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22645. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22646. if (this.allowMatricesInterpolation) {
  22647. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22648. }
  22649. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22650. return startValue;
  22651. }
  22652. default:
  22653. break;
  22654. }
  22655. break;
  22656. }
  22657. }
  22658. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22659. };
  22660. Animation.prototype.setValue = function (currentValue, blend) {
  22661. if (blend === void 0) { blend = false; }
  22662. // Set value
  22663. var path;
  22664. var destination;
  22665. if (this.targetPropertyPath.length > 1) {
  22666. var property = this._target[this.targetPropertyPath[0]];
  22667. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22668. property = property[this.targetPropertyPath[index]];
  22669. }
  22670. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  22671. destination = property;
  22672. }
  22673. else {
  22674. path = this.targetPropertyPath[0];
  22675. destination = this._target;
  22676. }
  22677. // Blending
  22678. if (this.enableBlending && this._blendingFactor <= 1.0) {
  22679. if (!this._originalBlendValue) {
  22680. this._originalBlendValue = destination[path];
  22681. }
  22682. if (this._originalBlendValue.prototype) {
  22683. if (this._originalBlendValue.prototype.Lerp) {
  22684. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  22685. }
  22686. else {
  22687. destination[path] = currentValue;
  22688. }
  22689. }
  22690. else {
  22691. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  22692. }
  22693. this._blendingFactor += this.blendingSpeed;
  22694. }
  22695. else {
  22696. destination[path] = currentValue;
  22697. }
  22698. if (this._target.markAsDirty) {
  22699. this._target.markAsDirty(this.targetProperty);
  22700. }
  22701. };
  22702. Animation.prototype.goToFrame = function (frame) {
  22703. if (frame < this._keys[0].frame) {
  22704. frame = this._keys[0].frame;
  22705. }
  22706. else if (frame > this._keys[this._keys.length - 1].frame) {
  22707. frame = this._keys[this._keys.length - 1].frame;
  22708. }
  22709. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22710. this.setValue(currentValue);
  22711. };
  22712. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  22713. if (blend === void 0) { blend = false; }
  22714. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22715. this._stopped = true;
  22716. return false;
  22717. }
  22718. var returnValue = true;
  22719. // Adding a start key at frame 0 if missing
  22720. if (this._keys[0].frame !== 0) {
  22721. var newKey = { frame: 0, value: this._keys[0].value };
  22722. this._keys.splice(0, 0, newKey);
  22723. }
  22724. // Check limits
  22725. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22726. from = this._keys[0].frame;
  22727. }
  22728. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22729. to = this._keys[this._keys.length - 1].frame;
  22730. }
  22731. // Compute ratio
  22732. var range = to - from;
  22733. var offsetValue;
  22734. // ratio represents the frame delta between from and to
  22735. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22736. var highLimitValue = 0;
  22737. if (ratio > range && !loop) {
  22738. returnValue = false;
  22739. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22740. }
  22741. else {
  22742. // Get max value if required
  22743. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22744. var keyOffset = to.toString() + from.toString();
  22745. if (!this._offsetsCache[keyOffset]) {
  22746. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22747. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22748. switch (this.dataType) {
  22749. // Float
  22750. case Animation.ANIMATIONTYPE_FLOAT:
  22751. this._offsetsCache[keyOffset] = toValue - fromValue;
  22752. break;
  22753. // Quaternion
  22754. case Animation.ANIMATIONTYPE_QUATERNION:
  22755. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22756. break;
  22757. // Vector3
  22758. case Animation.ANIMATIONTYPE_VECTOR3:
  22759. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22760. // Vector2
  22761. case Animation.ANIMATIONTYPE_VECTOR2:
  22762. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22763. // Color3
  22764. case Animation.ANIMATIONTYPE_COLOR3:
  22765. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22766. default:
  22767. break;
  22768. }
  22769. this._highLimitsCache[keyOffset] = toValue;
  22770. }
  22771. highLimitValue = this._highLimitsCache[keyOffset];
  22772. offsetValue = this._offsetsCache[keyOffset];
  22773. }
  22774. }
  22775. if (offsetValue === undefined) {
  22776. switch (this.dataType) {
  22777. // Float
  22778. case Animation.ANIMATIONTYPE_FLOAT:
  22779. offsetValue = 0;
  22780. break;
  22781. // Quaternion
  22782. case Animation.ANIMATIONTYPE_QUATERNION:
  22783. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22784. break;
  22785. // Vector3
  22786. case Animation.ANIMATIONTYPE_VECTOR3:
  22787. offsetValue = BABYLON.Vector3.Zero();
  22788. break;
  22789. // Vector2
  22790. case Animation.ANIMATIONTYPE_VECTOR2:
  22791. offsetValue = BABYLON.Vector2.Zero();
  22792. break;
  22793. // Color3
  22794. case Animation.ANIMATIONTYPE_COLOR3:
  22795. offsetValue = BABYLON.Color3.Black();
  22796. }
  22797. }
  22798. // Compute value
  22799. var repeatCount = (ratio / range) >> 0;
  22800. var currentFrame = returnValue ? from + ratio % range : to;
  22801. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22802. // Set value
  22803. this.setValue(currentValue);
  22804. // Check events
  22805. for (var index = 0; index < this._events.length; index++) {
  22806. if (currentFrame >= this._events[index].frame) {
  22807. var event = this._events[index];
  22808. if (!event.isDone) {
  22809. // If event should be done only once, remove it.
  22810. if (event.onlyOnce) {
  22811. this._events.splice(index, 1);
  22812. index--;
  22813. }
  22814. event.isDone = true;
  22815. event.action();
  22816. } // Don't do anything if the event has already be done.
  22817. }
  22818. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22819. // reset event, the animation is looping
  22820. this._events[index].isDone = false;
  22821. }
  22822. }
  22823. if (!returnValue) {
  22824. this._stopped = true;
  22825. }
  22826. return returnValue;
  22827. };
  22828. Animation.prototype.serialize = function () {
  22829. var serializationObject = {};
  22830. serializationObject.name = this.name;
  22831. serializationObject.property = this.targetProperty;
  22832. serializationObject.framePerSecond = this.framePerSecond;
  22833. serializationObject.dataType = this.dataType;
  22834. serializationObject.loopBehavior = this.loopMode;
  22835. var dataType = this.dataType;
  22836. serializationObject.keys = [];
  22837. var keys = this.getKeys();
  22838. for (var index = 0; index < keys.length; index++) {
  22839. var animationKey = keys[index];
  22840. var key = {};
  22841. key.frame = animationKey.frame;
  22842. switch (dataType) {
  22843. case Animation.ANIMATIONTYPE_FLOAT:
  22844. key.values = [animationKey.value];
  22845. break;
  22846. case Animation.ANIMATIONTYPE_QUATERNION:
  22847. case Animation.ANIMATIONTYPE_MATRIX:
  22848. case Animation.ANIMATIONTYPE_VECTOR3:
  22849. case Animation.ANIMATIONTYPE_COLOR3:
  22850. key.values = animationKey.value.asArray();
  22851. break;
  22852. }
  22853. serializationObject.keys.push(key);
  22854. }
  22855. serializationObject.ranges = [];
  22856. for (var name in this._ranges) {
  22857. var range = {};
  22858. range.name = name;
  22859. range.from = this._ranges[name].from;
  22860. range.to = this._ranges[name].to;
  22861. serializationObject.ranges.push(range);
  22862. }
  22863. return serializationObject;
  22864. };
  22865. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22866. get: function () {
  22867. return Animation._ANIMATIONTYPE_FLOAT;
  22868. },
  22869. enumerable: true,
  22870. configurable: true
  22871. });
  22872. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22873. get: function () {
  22874. return Animation._ANIMATIONTYPE_VECTOR3;
  22875. },
  22876. enumerable: true,
  22877. configurable: true
  22878. });
  22879. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22880. get: function () {
  22881. return Animation._ANIMATIONTYPE_VECTOR2;
  22882. },
  22883. enumerable: true,
  22884. configurable: true
  22885. });
  22886. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22887. get: function () {
  22888. return Animation._ANIMATIONTYPE_QUATERNION;
  22889. },
  22890. enumerable: true,
  22891. configurable: true
  22892. });
  22893. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22894. get: function () {
  22895. return Animation._ANIMATIONTYPE_MATRIX;
  22896. },
  22897. enumerable: true,
  22898. configurable: true
  22899. });
  22900. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22901. get: function () {
  22902. return Animation._ANIMATIONTYPE_COLOR3;
  22903. },
  22904. enumerable: true,
  22905. configurable: true
  22906. });
  22907. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22908. get: function () {
  22909. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22910. },
  22911. enumerable: true,
  22912. configurable: true
  22913. });
  22914. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22915. get: function () {
  22916. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22917. },
  22918. enumerable: true,
  22919. configurable: true
  22920. });
  22921. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22922. get: function () {
  22923. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22924. },
  22925. enumerable: true,
  22926. configurable: true
  22927. });
  22928. Animation.Parse = function (parsedAnimation) {
  22929. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22930. var dataType = parsedAnimation.dataType;
  22931. var keys = [];
  22932. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22933. var key = parsedAnimation.keys[index];
  22934. var data;
  22935. switch (dataType) {
  22936. case Animation.ANIMATIONTYPE_FLOAT:
  22937. data = key.values[0];
  22938. break;
  22939. case Animation.ANIMATIONTYPE_QUATERNION:
  22940. data = BABYLON.Quaternion.FromArray(key.values);
  22941. break;
  22942. case Animation.ANIMATIONTYPE_MATRIX:
  22943. data = BABYLON.Matrix.FromArray(key.values);
  22944. break;
  22945. case Animation.ANIMATIONTYPE_COLOR3:
  22946. data = BABYLON.Color3.FromArray(key.values);
  22947. break;
  22948. case Animation.ANIMATIONTYPE_VECTOR3:
  22949. default:
  22950. data = BABYLON.Vector3.FromArray(key.values);
  22951. break;
  22952. }
  22953. keys.push({
  22954. frame: key.frame,
  22955. value: data
  22956. });
  22957. }
  22958. animation.setKeys(keys);
  22959. if (parsedAnimation.ranges) {
  22960. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22961. data = parsedAnimation.ranges[index];
  22962. animation.createRange(data.name, data.from, data.to);
  22963. }
  22964. }
  22965. return animation;
  22966. };
  22967. Animation.AppendSerializedAnimations = function (source, destination) {
  22968. if (source.animations) {
  22969. destination.animations = [];
  22970. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22971. var animation = source.animations[animationIndex];
  22972. destination.animations.push(animation.serialize());
  22973. }
  22974. }
  22975. };
  22976. // Statics
  22977. Animation._ANIMATIONTYPE_FLOAT = 0;
  22978. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22979. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22980. Animation._ANIMATIONTYPE_MATRIX = 3;
  22981. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22982. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22983. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22984. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22985. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22986. return Animation;
  22987. })();
  22988. BABYLON.Animation = Animation;
  22989. })(BABYLON || (BABYLON = {}));
  22990. var BABYLON;
  22991. (function (BABYLON) {
  22992. var Animatable = (function () {
  22993. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22994. if (fromFrame === void 0) { fromFrame = 0; }
  22995. if (toFrame === void 0) { toFrame = 100; }
  22996. if (loopAnimation === void 0) { loopAnimation = false; }
  22997. if (speedRatio === void 0) { speedRatio = 1.0; }
  22998. this.target = target;
  22999. this.fromFrame = fromFrame;
  23000. this.toFrame = toFrame;
  23001. this.loopAnimation = loopAnimation;
  23002. this.speedRatio = speedRatio;
  23003. this.onAnimationEnd = onAnimationEnd;
  23004. this._animations = new Array();
  23005. this._paused = false;
  23006. this.animationStarted = false;
  23007. if (animations) {
  23008. this.appendAnimations(target, animations);
  23009. }
  23010. this._scene = scene;
  23011. scene._activeAnimatables.push(this);
  23012. }
  23013. // Methods
  23014. Animatable.prototype.getAnimations = function () {
  23015. return this._animations;
  23016. };
  23017. Animatable.prototype.appendAnimations = function (target, animations) {
  23018. for (var index = 0; index < animations.length; index++) {
  23019. var animation = animations[index];
  23020. animation._target = target;
  23021. this._animations.push(animation);
  23022. }
  23023. };
  23024. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  23025. var animations = this._animations;
  23026. for (var index = 0; index < animations.length; index++) {
  23027. if (animations[index].targetProperty === property) {
  23028. return animations[index];
  23029. }
  23030. }
  23031. return null;
  23032. };
  23033. Animatable.prototype.reset = function () {
  23034. var animations = this._animations;
  23035. for (var index = 0; index < animations.length; index++) {
  23036. animations[index].reset();
  23037. }
  23038. this._localDelayOffset = null;
  23039. this._pausedDelay = null;
  23040. };
  23041. Animatable.prototype.enableBlending = function (blendingSpeed) {
  23042. var animations = this._animations;
  23043. for (var index = 0; index < animations.length; index++) {
  23044. animations[index].enableBlending = true;
  23045. animations[index].blendingSpeed = blendingSpeed;
  23046. }
  23047. };
  23048. Animatable.prototype.disableBlending = function () {
  23049. var animations = this._animations;
  23050. for (var index = 0; index < animations.length; index++) {
  23051. animations[index].enableBlending = false;
  23052. }
  23053. };
  23054. Animatable.prototype.goToFrame = function (frame) {
  23055. var animations = this._animations;
  23056. for (var index = 0; index < animations.length; index++) {
  23057. animations[index].goToFrame(frame);
  23058. }
  23059. };
  23060. Animatable.prototype.pause = function () {
  23061. if (this._paused) {
  23062. return;
  23063. }
  23064. this._paused = true;
  23065. };
  23066. Animatable.prototype.restart = function () {
  23067. this._paused = false;
  23068. };
  23069. Animatable.prototype.stop = function () {
  23070. var index = this._scene._activeAnimatables.indexOf(this);
  23071. if (index > -1) {
  23072. this._scene._activeAnimatables.splice(index, 1);
  23073. var animations = this._animations;
  23074. for (var index = 0; index < animations.length; index++) {
  23075. animations[index].reset();
  23076. }
  23077. if (this.onAnimationEnd) {
  23078. this.onAnimationEnd();
  23079. }
  23080. }
  23081. };
  23082. Animatable.prototype._animate = function (delay) {
  23083. if (this._paused) {
  23084. this.animationStarted = false;
  23085. if (!this._pausedDelay) {
  23086. this._pausedDelay = delay;
  23087. }
  23088. return true;
  23089. }
  23090. if (!this._localDelayOffset) {
  23091. this._localDelayOffset = delay;
  23092. }
  23093. else if (this._pausedDelay) {
  23094. this._localDelayOffset += delay - this._pausedDelay;
  23095. this._pausedDelay = null;
  23096. }
  23097. // Animating
  23098. var running = false;
  23099. var animations = this._animations;
  23100. var index;
  23101. for (index = 0; index < animations.length; index++) {
  23102. var animation = animations[index];
  23103. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  23104. running = running || isRunning;
  23105. }
  23106. this.animationStarted = running;
  23107. if (!running) {
  23108. // Remove from active animatables
  23109. index = this._scene._activeAnimatables.indexOf(this);
  23110. this._scene._activeAnimatables.splice(index, 1);
  23111. }
  23112. if (!running && this.onAnimationEnd) {
  23113. this.onAnimationEnd();
  23114. this.onAnimationEnd = null;
  23115. }
  23116. return running;
  23117. };
  23118. return Animatable;
  23119. })();
  23120. BABYLON.Animatable = Animatable;
  23121. })(BABYLON || (BABYLON = {}));
  23122. var BABYLON;
  23123. (function (BABYLON) {
  23124. var EasingFunction = (function () {
  23125. function EasingFunction() {
  23126. // Properties
  23127. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23128. }
  23129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23130. get: function () {
  23131. return EasingFunction._EASINGMODE_EASEIN;
  23132. },
  23133. enumerable: true,
  23134. configurable: true
  23135. });
  23136. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23137. get: function () {
  23138. return EasingFunction._EASINGMODE_EASEOUT;
  23139. },
  23140. enumerable: true,
  23141. configurable: true
  23142. });
  23143. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23144. get: function () {
  23145. return EasingFunction._EASINGMODE_EASEINOUT;
  23146. },
  23147. enumerable: true,
  23148. configurable: true
  23149. });
  23150. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23151. var n = Math.min(Math.max(easingMode, 0), 2);
  23152. this._easingMode = n;
  23153. };
  23154. EasingFunction.prototype.getEasingMode = function () {
  23155. return this._easingMode;
  23156. };
  23157. EasingFunction.prototype.easeInCore = function (gradient) {
  23158. throw new Error('You must implement this method');
  23159. };
  23160. EasingFunction.prototype.ease = function (gradient) {
  23161. switch (this._easingMode) {
  23162. case EasingFunction.EASINGMODE_EASEIN:
  23163. return this.easeInCore(gradient);
  23164. case EasingFunction.EASINGMODE_EASEOUT:
  23165. return (1 - this.easeInCore(1 - gradient));
  23166. }
  23167. if (gradient >= 0.5) {
  23168. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23169. }
  23170. return (this.easeInCore(gradient * 2) * 0.5);
  23171. };
  23172. //Statics
  23173. EasingFunction._EASINGMODE_EASEIN = 0;
  23174. EasingFunction._EASINGMODE_EASEOUT = 1;
  23175. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23176. return EasingFunction;
  23177. })();
  23178. BABYLON.EasingFunction = EasingFunction;
  23179. var CircleEase = (function (_super) {
  23180. __extends(CircleEase, _super);
  23181. function CircleEase() {
  23182. _super.apply(this, arguments);
  23183. }
  23184. CircleEase.prototype.easeInCore = function (gradient) {
  23185. gradient = Math.max(0, Math.min(1, gradient));
  23186. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23187. };
  23188. return CircleEase;
  23189. })(EasingFunction);
  23190. BABYLON.CircleEase = CircleEase;
  23191. var BackEase = (function (_super) {
  23192. __extends(BackEase, _super);
  23193. function BackEase(amplitude) {
  23194. if (amplitude === void 0) { amplitude = 1; }
  23195. _super.call(this);
  23196. this.amplitude = amplitude;
  23197. }
  23198. BackEase.prototype.easeInCore = function (gradient) {
  23199. var num = Math.max(0, this.amplitude);
  23200. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23201. };
  23202. return BackEase;
  23203. })(EasingFunction);
  23204. BABYLON.BackEase = BackEase;
  23205. var BounceEase = (function (_super) {
  23206. __extends(BounceEase, _super);
  23207. function BounceEase(bounces, bounciness) {
  23208. if (bounces === void 0) { bounces = 3; }
  23209. if (bounciness === void 0) { bounciness = 2; }
  23210. _super.call(this);
  23211. this.bounces = bounces;
  23212. this.bounciness = bounciness;
  23213. }
  23214. BounceEase.prototype.easeInCore = function (gradient) {
  23215. var y = Math.max(0.0, this.bounces);
  23216. var bounciness = this.bounciness;
  23217. if (bounciness <= 1.0) {
  23218. bounciness = 1.001;
  23219. }
  23220. var num9 = Math.pow(bounciness, y);
  23221. var num5 = 1.0 - bounciness;
  23222. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23223. var num15 = gradient * num4;
  23224. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23225. var num3 = Math.floor(num65);
  23226. var num13 = num3 + 1.0;
  23227. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23228. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23229. var num7 = (num8 + num12) * 0.5;
  23230. var num6 = gradient - num7;
  23231. var num2 = num7 - num8;
  23232. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23233. };
  23234. return BounceEase;
  23235. })(EasingFunction);
  23236. BABYLON.BounceEase = BounceEase;
  23237. var CubicEase = (function (_super) {
  23238. __extends(CubicEase, _super);
  23239. function CubicEase() {
  23240. _super.apply(this, arguments);
  23241. }
  23242. CubicEase.prototype.easeInCore = function (gradient) {
  23243. return (gradient * gradient * gradient);
  23244. };
  23245. return CubicEase;
  23246. })(EasingFunction);
  23247. BABYLON.CubicEase = CubicEase;
  23248. var ElasticEase = (function (_super) {
  23249. __extends(ElasticEase, _super);
  23250. function ElasticEase(oscillations, springiness) {
  23251. if (oscillations === void 0) { oscillations = 3; }
  23252. if (springiness === void 0) { springiness = 3; }
  23253. _super.call(this);
  23254. this.oscillations = oscillations;
  23255. this.springiness = springiness;
  23256. }
  23257. ElasticEase.prototype.easeInCore = function (gradient) {
  23258. var num2;
  23259. var num3 = Math.max(0.0, this.oscillations);
  23260. var num = Math.max(0.0, this.springiness);
  23261. if (num == 0) {
  23262. num2 = gradient;
  23263. }
  23264. else {
  23265. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23266. }
  23267. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23268. };
  23269. return ElasticEase;
  23270. })(EasingFunction);
  23271. BABYLON.ElasticEase = ElasticEase;
  23272. var ExponentialEase = (function (_super) {
  23273. __extends(ExponentialEase, _super);
  23274. function ExponentialEase(exponent) {
  23275. if (exponent === void 0) { exponent = 2; }
  23276. _super.call(this);
  23277. this.exponent = exponent;
  23278. }
  23279. ExponentialEase.prototype.easeInCore = function (gradient) {
  23280. if (this.exponent <= 0) {
  23281. return gradient;
  23282. }
  23283. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23284. };
  23285. return ExponentialEase;
  23286. })(EasingFunction);
  23287. BABYLON.ExponentialEase = ExponentialEase;
  23288. var PowerEase = (function (_super) {
  23289. __extends(PowerEase, _super);
  23290. function PowerEase(power) {
  23291. if (power === void 0) { power = 2; }
  23292. _super.call(this);
  23293. this.power = power;
  23294. }
  23295. PowerEase.prototype.easeInCore = function (gradient) {
  23296. var y = Math.max(0.0, this.power);
  23297. return Math.pow(gradient, y);
  23298. };
  23299. return PowerEase;
  23300. })(EasingFunction);
  23301. BABYLON.PowerEase = PowerEase;
  23302. var QuadraticEase = (function (_super) {
  23303. __extends(QuadraticEase, _super);
  23304. function QuadraticEase() {
  23305. _super.apply(this, arguments);
  23306. }
  23307. QuadraticEase.prototype.easeInCore = function (gradient) {
  23308. return (gradient * gradient);
  23309. };
  23310. return QuadraticEase;
  23311. })(EasingFunction);
  23312. BABYLON.QuadraticEase = QuadraticEase;
  23313. var QuarticEase = (function (_super) {
  23314. __extends(QuarticEase, _super);
  23315. function QuarticEase() {
  23316. _super.apply(this, arguments);
  23317. }
  23318. QuarticEase.prototype.easeInCore = function (gradient) {
  23319. return (gradient * gradient * gradient * gradient);
  23320. };
  23321. return QuarticEase;
  23322. })(EasingFunction);
  23323. BABYLON.QuarticEase = QuarticEase;
  23324. var QuinticEase = (function (_super) {
  23325. __extends(QuinticEase, _super);
  23326. function QuinticEase() {
  23327. _super.apply(this, arguments);
  23328. }
  23329. QuinticEase.prototype.easeInCore = function (gradient) {
  23330. return (gradient * gradient * gradient * gradient * gradient);
  23331. };
  23332. return QuinticEase;
  23333. })(EasingFunction);
  23334. BABYLON.QuinticEase = QuinticEase;
  23335. var SineEase = (function (_super) {
  23336. __extends(SineEase, _super);
  23337. function SineEase() {
  23338. _super.apply(this, arguments);
  23339. }
  23340. SineEase.prototype.easeInCore = function (gradient) {
  23341. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23342. };
  23343. return SineEase;
  23344. })(EasingFunction);
  23345. BABYLON.SineEase = SineEase;
  23346. var BezierCurveEase = (function (_super) {
  23347. __extends(BezierCurveEase, _super);
  23348. function BezierCurveEase(x1, y1, x2, y2) {
  23349. if (x1 === void 0) { x1 = 0; }
  23350. if (y1 === void 0) { y1 = 0; }
  23351. if (x2 === void 0) { x2 = 1; }
  23352. if (y2 === void 0) { y2 = 1; }
  23353. _super.call(this);
  23354. this.x1 = x1;
  23355. this.y1 = y1;
  23356. this.x2 = x2;
  23357. this.y2 = y2;
  23358. }
  23359. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23360. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23361. };
  23362. return BezierCurveEase;
  23363. })(EasingFunction);
  23364. BABYLON.BezierCurveEase = BezierCurveEase;
  23365. })(BABYLON || (BABYLON = {}));
  23366. var BABYLON;
  23367. (function (BABYLON) {
  23368. var Bone = (function (_super) {
  23369. __extends(Bone, _super);
  23370. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23371. _super.call(this, name, skeleton.getScene());
  23372. this.name = name;
  23373. this.children = new Array();
  23374. this.animations = new Array();
  23375. this._worldTransform = new BABYLON.Matrix();
  23376. this._absoluteTransform = new BABYLON.Matrix();
  23377. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23378. this._skeleton = skeleton;
  23379. this._matrix = matrix;
  23380. this._baseMatrix = matrix;
  23381. this._restPose = restPose ? restPose : matrix.clone();
  23382. skeleton.bones.push(this);
  23383. if (parentBone) {
  23384. this._parent = parentBone;
  23385. parentBone.children.push(this);
  23386. }
  23387. else {
  23388. this._parent = null;
  23389. }
  23390. this._updateDifferenceMatrix();
  23391. }
  23392. // Members
  23393. Bone.prototype.getParent = function () {
  23394. return this._parent;
  23395. };
  23396. Bone.prototype.getLocalMatrix = function () {
  23397. return this._matrix;
  23398. };
  23399. Bone.prototype.getBaseMatrix = function () {
  23400. return this._baseMatrix;
  23401. };
  23402. Bone.prototype.getRestPose = function () {
  23403. return this._restPose;
  23404. };
  23405. Bone.prototype.returnToRest = function () {
  23406. this.updateMatrix(this._restPose.clone());
  23407. };
  23408. Bone.prototype.getWorldMatrix = function () {
  23409. return this._worldTransform;
  23410. };
  23411. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23412. return this._invertedAbsoluteTransform;
  23413. };
  23414. Bone.prototype.getAbsoluteTransform = function () {
  23415. return this._absoluteTransform;
  23416. };
  23417. // Methods
  23418. Bone.prototype.updateMatrix = function (matrix) {
  23419. this._baseMatrix = matrix.clone();
  23420. this._matrix = matrix.clone();
  23421. this._skeleton._markAsDirty();
  23422. this._updateDifferenceMatrix();
  23423. };
  23424. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23425. if (!rootMatrix) {
  23426. rootMatrix = this._baseMatrix;
  23427. }
  23428. if (this._parent) {
  23429. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23430. }
  23431. else {
  23432. this._absoluteTransform.copyFrom(rootMatrix);
  23433. }
  23434. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23435. for (var index = 0; index < this.children.length; index++) {
  23436. this.children[index]._updateDifferenceMatrix();
  23437. }
  23438. };
  23439. Bone.prototype.markAsDirty = function () {
  23440. this._currentRenderId++;
  23441. this._skeleton._markAsDirty();
  23442. };
  23443. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23444. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23445. // all animation may be coming from a library skeleton, so may need to create animation
  23446. if (this.animations.length === 0) {
  23447. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23448. }
  23449. // get animation info / verify there is such a range from the source bone
  23450. var sourceRange = source.animations[0].getRange(rangeName);
  23451. if (!sourceRange) {
  23452. return false;
  23453. }
  23454. var from = sourceRange.from;
  23455. var to = sourceRange.to;
  23456. var sourceKeys = source.animations[0].getKeys();
  23457. // rescaling prep
  23458. var sourceBoneLength = source.length;
  23459. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23460. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23461. var destKeys = this.animations[0].getKeys();
  23462. // loop vars declaration / initialization
  23463. var orig;
  23464. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23465. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23466. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23467. var mat;
  23468. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23469. orig = sourceKeys[key];
  23470. if (orig.frame >= from && orig.frame <= to) {
  23471. if (scalingReqd) {
  23472. orig.value.decompose(origScale, origRotation, origTranslation);
  23473. origTranslation.scaleInPlace(ratio);
  23474. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23475. }
  23476. else {
  23477. mat = orig.value;
  23478. }
  23479. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23480. }
  23481. }
  23482. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23483. return true;
  23484. };
  23485. return Bone;
  23486. })(BABYLON.Node);
  23487. BABYLON.Bone = Bone;
  23488. })(BABYLON || (BABYLON = {}));
  23489. var BABYLON;
  23490. (function (BABYLON) {
  23491. var Skeleton = (function () {
  23492. function Skeleton(name, id, scene) {
  23493. this.name = name;
  23494. this.id = id;
  23495. this.bones = new Array();
  23496. this.needInitialSkinMatrix = false;
  23497. this._isDirty = true;
  23498. this._meshesWithPoseMatrix = new Array();
  23499. this._identity = BABYLON.Matrix.Identity();
  23500. this._ranges = {};
  23501. this.bones = [];
  23502. this._scene = scene;
  23503. scene.skeletons.push(this);
  23504. this.prepare();
  23505. //make sure it will recalculate the matrix next time prepare is called.
  23506. this._isDirty = true;
  23507. }
  23508. // Members
  23509. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23510. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23511. return mesh._bonesTransformMatrices;
  23512. }
  23513. return this._transformMatrices;
  23514. };
  23515. Skeleton.prototype.getScene = function () {
  23516. return this._scene;
  23517. };
  23518. // Methods
  23519. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23520. // check name not already in use
  23521. if (!this._ranges[name]) {
  23522. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23523. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23524. if (this.bones[i].animations[0]) {
  23525. this.bones[i].animations[0].createRange(name, from, to);
  23526. }
  23527. }
  23528. }
  23529. };
  23530. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23531. if (deleteFrames === void 0) { deleteFrames = true; }
  23532. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23533. if (this.bones[i].animations[0]) {
  23534. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23535. }
  23536. }
  23537. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23538. };
  23539. Skeleton.prototype.getAnimationRange = function (name) {
  23540. return this._ranges[name];
  23541. };
  23542. /**
  23543. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23544. */
  23545. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23546. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23547. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23548. return false;
  23549. }
  23550. var ret = true;
  23551. var frameOffset = this._getHighestAnimationFrame() + 1;
  23552. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23553. var boneDict = {};
  23554. var sourceBones = source.bones;
  23555. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23556. boneDict[sourceBones[i].name] = sourceBones[i];
  23557. }
  23558. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23559. var boneName = this.bones[i].name;
  23560. var sourceBone = boneDict[boneName];
  23561. if (sourceBone) {
  23562. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23563. }
  23564. else {
  23565. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23566. ret = false;
  23567. }
  23568. }
  23569. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23570. var range = source.getAnimationRange(name);
  23571. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23572. return ret;
  23573. };
  23574. Skeleton.prototype.returnToRest = function () {
  23575. for (var index = 0; index < this.bones.length; index++) {
  23576. this.bones[index].returnToRest();
  23577. }
  23578. };
  23579. Skeleton.prototype._getHighestAnimationFrame = function () {
  23580. var ret = 0;
  23581. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23582. if (this.bones[i].animations[0]) {
  23583. var highest = this.bones[i].animations[0].getHighestFrame();
  23584. if (ret < highest) {
  23585. ret = highest;
  23586. }
  23587. }
  23588. }
  23589. return ret;
  23590. };
  23591. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23592. var range = this.getAnimationRange(name);
  23593. if (!range) {
  23594. return null;
  23595. }
  23596. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23597. };
  23598. Skeleton.prototype._markAsDirty = function () {
  23599. this._isDirty = true;
  23600. };
  23601. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23602. this._meshesWithPoseMatrix.push(mesh);
  23603. };
  23604. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23605. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23606. if (index > -1) {
  23607. this._meshesWithPoseMatrix.splice(index, 1);
  23608. }
  23609. };
  23610. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23611. for (var index = 0; index < this.bones.length; index++) {
  23612. var bone = this.bones[index];
  23613. var parentBone = bone.getParent();
  23614. if (parentBone) {
  23615. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23616. }
  23617. else {
  23618. if (initialSkinMatrix) {
  23619. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23620. }
  23621. else {
  23622. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23623. }
  23624. }
  23625. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23626. }
  23627. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23628. };
  23629. Skeleton.prototype.prepare = function () {
  23630. if (!this._isDirty) {
  23631. return;
  23632. }
  23633. if (this.needInitialSkinMatrix) {
  23634. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23635. var mesh = this._meshesWithPoseMatrix[index];
  23636. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23637. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23638. }
  23639. var poseMatrix = mesh.getPoseMatrix();
  23640. // Prepare bones
  23641. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23642. var bone = this.bones[boneIndex];
  23643. if (!bone.getParent()) {
  23644. var matrix = bone.getBaseMatrix();
  23645. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23646. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23647. }
  23648. }
  23649. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23650. }
  23651. }
  23652. else {
  23653. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23654. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23655. }
  23656. this._computeTransformMatrices(this._transformMatrices, null);
  23657. }
  23658. this._isDirty = false;
  23659. this._scene._activeBones += this.bones.length;
  23660. };
  23661. Skeleton.prototype.getAnimatables = function () {
  23662. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23663. this._animatables = [];
  23664. for (var index = 0; index < this.bones.length; index++) {
  23665. this._animatables.push(this.bones[index]);
  23666. }
  23667. }
  23668. return this._animatables;
  23669. };
  23670. Skeleton.prototype.clone = function (name, id) {
  23671. var result = new Skeleton(name, id || name, this._scene);
  23672. for (var index = 0; index < this.bones.length; index++) {
  23673. var source = this.bones[index];
  23674. var parentBone = null;
  23675. if (source.getParent()) {
  23676. var parentIndex = this.bones.indexOf(source.getParent());
  23677. parentBone = result.bones[parentIndex];
  23678. }
  23679. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23680. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23681. }
  23682. return result;
  23683. };
  23684. Skeleton.prototype.dispose = function () {
  23685. this._meshesWithPoseMatrix = [];
  23686. // Animations
  23687. this.getScene().stopAnimation(this);
  23688. // Remove from scene
  23689. this.getScene().removeSkeleton(this);
  23690. };
  23691. Skeleton.prototype.serialize = function () {
  23692. var serializationObject = {};
  23693. serializationObject.name = this.name;
  23694. serializationObject.id = this.id;
  23695. serializationObject.bones = [];
  23696. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23697. for (var index = 0; index < this.bones.length; index++) {
  23698. var bone = this.bones[index];
  23699. var serializedBone = {
  23700. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23701. name: bone.name,
  23702. matrix: bone.getLocalMatrix().toArray(),
  23703. rest: bone.getRestPose().toArray()
  23704. };
  23705. serializationObject.bones.push(serializedBone);
  23706. if (bone.length) {
  23707. serializedBone.length = bone.length;
  23708. }
  23709. if (bone.animations && bone.animations.length > 0) {
  23710. serializedBone.animation = bone.animations[0].serialize();
  23711. }
  23712. serializationObject.ranges = [];
  23713. for (var name in this._ranges) {
  23714. var range = {};
  23715. range.name = name;
  23716. range.from = this._ranges[name].from;
  23717. range.to = this._ranges[name].to;
  23718. serializationObject.ranges.push(range);
  23719. }
  23720. }
  23721. return serializationObject;
  23722. };
  23723. Skeleton.Parse = function (parsedSkeleton, scene) {
  23724. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23725. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23726. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23727. var parsedBone = parsedSkeleton.bones[index];
  23728. var parentBone = null;
  23729. if (parsedBone.parentBoneIndex > -1) {
  23730. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23731. }
  23732. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23733. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23734. if (parsedBone.length) {
  23735. bone.length = parsedBone.length;
  23736. }
  23737. if (parsedBone.animation) {
  23738. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23739. }
  23740. }
  23741. // placed after bones, so createAnimationRange can cascade down
  23742. if (parsedSkeleton.ranges) {
  23743. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23744. var data = parsedSkeleton.ranges[index];
  23745. skeleton.createAnimationRange(data.name, data.from, data.to);
  23746. }
  23747. }
  23748. return skeleton;
  23749. };
  23750. return Skeleton;
  23751. })();
  23752. BABYLON.Skeleton = Skeleton;
  23753. })(BABYLON || (BABYLON = {}));
  23754. var BABYLON;
  23755. (function (BABYLON) {
  23756. var PostProcess = (function () {
  23757. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23760. this.name = name;
  23761. this.width = -1;
  23762. this.height = -1;
  23763. this._reusable = false;
  23764. this._textures = new BABYLON.SmartArray(2);
  23765. this._currentRenderTextureInd = 0;
  23766. if (camera != null) {
  23767. this._camera = camera;
  23768. this._scene = camera.getScene();
  23769. camera.attachPostProcess(this);
  23770. this._engine = this._scene.getEngine();
  23771. }
  23772. else {
  23773. this._engine = engine;
  23774. }
  23775. this._renderRatio = ratio;
  23776. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23777. this._reusable = reusable || false;
  23778. this._textureType = textureType;
  23779. this._samplers = samplers || [];
  23780. this._samplers.push("textureSampler");
  23781. this._fragmentUrl = fragmentUrl;
  23782. this._parameters = parameters || [];
  23783. this.updateEffect(defines);
  23784. }
  23785. PostProcess.prototype.updateEffect = function (defines) {
  23786. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23787. };
  23788. PostProcess.prototype.isReusable = function () {
  23789. return this._reusable;
  23790. };
  23791. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23792. camera = camera || this._camera;
  23793. var scene = camera.getScene();
  23794. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23795. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23796. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23797. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23798. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23799. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23800. if (this._textures.length > 0) {
  23801. for (var i = 0; i < this._textures.length; i++) {
  23802. this._engine._releaseTexture(this._textures.data[i]);
  23803. }
  23804. this._textures.reset();
  23805. }
  23806. this.width = desiredWidth;
  23807. this.height = desiredHeight;
  23808. 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 }));
  23809. if (this._reusable) {
  23810. 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 }));
  23811. }
  23812. if (this.onSizeChanged) {
  23813. this.onSizeChanged();
  23814. }
  23815. }
  23816. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23817. if (this.onActivate) {
  23818. this.onActivate(camera);
  23819. }
  23820. // Clear
  23821. if (this.clearColor) {
  23822. this._engine.clear(this.clearColor, true, true);
  23823. }
  23824. else {
  23825. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23826. }
  23827. if (this._reusable) {
  23828. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23829. }
  23830. };
  23831. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23832. get: function () {
  23833. return this._effect.isSupported;
  23834. },
  23835. enumerable: true,
  23836. configurable: true
  23837. });
  23838. PostProcess.prototype.apply = function () {
  23839. // Check
  23840. if (!this._effect.isReady())
  23841. return null;
  23842. // States
  23843. this._engine.enableEffect(this._effect);
  23844. this._engine.setState(false);
  23845. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23846. this._engine.setDepthBuffer(false);
  23847. this._engine.setDepthWrite(false);
  23848. // Texture
  23849. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23850. // Parameters
  23851. if (this.onApply) {
  23852. this.onApply(this._effect);
  23853. }
  23854. return this._effect;
  23855. };
  23856. PostProcess.prototype.dispose = function (camera) {
  23857. camera = camera || this._camera;
  23858. if (this._textures.length > 0) {
  23859. for (var i = 0; i < this._textures.length; i++) {
  23860. this._engine._releaseTexture(this._textures.data[i]);
  23861. }
  23862. this._textures.reset();
  23863. }
  23864. if (!camera) {
  23865. return;
  23866. }
  23867. camera.detachPostProcess(this);
  23868. var index = camera._postProcesses.indexOf(this);
  23869. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23870. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23871. }
  23872. };
  23873. return PostProcess;
  23874. })();
  23875. BABYLON.PostProcess = PostProcess;
  23876. })(BABYLON || (BABYLON = {}));
  23877. var BABYLON;
  23878. (function (BABYLON) {
  23879. var PostProcessManager = (function () {
  23880. function PostProcessManager(scene) {
  23881. this._vertexDeclaration = [2];
  23882. this._vertexStrideSize = 2 * 4;
  23883. this._scene = scene;
  23884. }
  23885. PostProcessManager.prototype._prepareBuffers = function () {
  23886. if (this._vertexBuffer) {
  23887. return;
  23888. }
  23889. // VBO
  23890. var vertices = [];
  23891. vertices.push(1, 1);
  23892. vertices.push(-1, 1);
  23893. vertices.push(-1, -1);
  23894. vertices.push(1, -1);
  23895. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23896. // Indices
  23897. var indices = [];
  23898. indices.push(0);
  23899. indices.push(1);
  23900. indices.push(2);
  23901. indices.push(0);
  23902. indices.push(2);
  23903. indices.push(3);
  23904. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23905. };
  23906. // Methods
  23907. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23908. var postProcesses = this._scene.activeCamera._postProcesses;
  23909. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23910. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23911. return false;
  23912. }
  23913. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23914. return true;
  23915. };
  23916. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23917. var engine = this._scene.getEngine();
  23918. for (var index = 0; index < postProcesses.length; index++) {
  23919. if (index < postProcesses.length - 1) {
  23920. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23921. }
  23922. else {
  23923. if (targetTexture) {
  23924. engine.bindFramebuffer(targetTexture);
  23925. }
  23926. else {
  23927. engine.restoreDefaultFramebuffer();
  23928. }
  23929. }
  23930. var pp = postProcesses[index];
  23931. var effect = pp.apply();
  23932. if (effect) {
  23933. if (pp.onBeforeRender) {
  23934. pp.onBeforeRender(effect);
  23935. }
  23936. // VBOs
  23937. this._prepareBuffers();
  23938. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23939. // Draw order
  23940. engine.draw(true, 0, 6);
  23941. if (pp.onAfterRender) {
  23942. pp.onAfterRender(effect);
  23943. }
  23944. }
  23945. }
  23946. // Restore depth buffer
  23947. engine.setDepthBuffer(true);
  23948. engine.setDepthWrite(true);
  23949. };
  23950. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23951. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23952. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23953. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23954. return;
  23955. }
  23956. var engine = this._scene.getEngine();
  23957. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23958. if (index < postProcessesTakenIndices.length - 1) {
  23959. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23960. }
  23961. else {
  23962. if (targetTexture) {
  23963. engine.bindFramebuffer(targetTexture, faceIndex);
  23964. }
  23965. else {
  23966. engine.restoreDefaultFramebuffer();
  23967. }
  23968. }
  23969. if (doNotPresent) {
  23970. break;
  23971. }
  23972. var pp = postProcesses[postProcessesTakenIndices[index]];
  23973. var effect = pp.apply();
  23974. if (effect) {
  23975. if (pp.onBeforeRender) {
  23976. pp.onBeforeRender(effect);
  23977. }
  23978. // VBOs
  23979. this._prepareBuffers();
  23980. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23981. // Draw order
  23982. engine.draw(true, 0, 6);
  23983. if (pp.onAfterRender) {
  23984. pp.onAfterRender(effect);
  23985. }
  23986. }
  23987. }
  23988. // Restore depth buffer
  23989. engine.setDepthBuffer(true);
  23990. engine.setDepthWrite(true);
  23991. };
  23992. PostProcessManager.prototype.dispose = function () {
  23993. if (this._vertexBuffer) {
  23994. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23995. this._vertexBuffer = null;
  23996. }
  23997. if (this._indexBuffer) {
  23998. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23999. this._indexBuffer = null;
  24000. }
  24001. };
  24002. return PostProcessManager;
  24003. })();
  24004. BABYLON.PostProcessManager = PostProcessManager;
  24005. })(BABYLON || (BABYLON = {}));
  24006. var BABYLON;
  24007. (function (BABYLON) {
  24008. var PassPostProcess = (function (_super) {
  24009. __extends(PassPostProcess, _super);
  24010. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24011. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  24012. }
  24013. return PassPostProcess;
  24014. })(BABYLON.PostProcess);
  24015. BABYLON.PassPostProcess = PassPostProcess;
  24016. })(BABYLON || (BABYLON = {}));
  24017. var BABYLON;
  24018. (function (BABYLON) {
  24019. var PhysicsJoint = (function () {
  24020. function PhysicsJoint(type, jointData) {
  24021. this.type = type;
  24022. this.jointData = jointData;
  24023. jointData.nativeParams = jointData.nativeParams || {};
  24024. }
  24025. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  24026. get: function () {
  24027. return this._physicsJoint;
  24028. },
  24029. set: function (newJoint) {
  24030. if (this._physicsJoint) {
  24031. }
  24032. this._physicsJoint = newJoint;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. //TODO check if the native joints are the same
  24038. //Joint Types
  24039. PhysicsJoint.DistanceJoint = 0;
  24040. PhysicsJoint.HingeJoint = 1;
  24041. PhysicsJoint.BallAndSocketJoint = 2;
  24042. PhysicsJoint.WheelJoint = 3;
  24043. PhysicsJoint.SliderJoint = 4;
  24044. //OIMO
  24045. PhysicsJoint.PrismaticJoint = 5;
  24046. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  24047. PhysicsJoint.UniversalJoint = 6;
  24048. PhysicsJoint.Hinge2Joint = 7;
  24049. //Cannon
  24050. //Similar to a Ball-Joint. Different in params
  24051. //TODO check!!
  24052. PhysicsJoint.PointToPointJoint = 8;
  24053. //Cannon only at the moment
  24054. PhysicsJoint.SpringJoint = 9;
  24055. return PhysicsJoint;
  24056. })();
  24057. BABYLON.PhysicsJoint = PhysicsJoint;
  24058. })(BABYLON || (BABYLON = {}));
  24059. var BABYLON;
  24060. (function (BABYLON) {
  24061. var PhysicsImpostor = (function () {
  24062. function PhysicsImpostor(_mesh, type, _options) {
  24063. var _this = this;
  24064. if (_options === void 0) { _options = { mass: 0 }; }
  24065. this._mesh = _mesh;
  24066. this.type = type;
  24067. this._options = _options;
  24068. this._bodyUpdateRequired = false;
  24069. this._onBeforePhysicsStepCallbacks = new Array();
  24070. this._onAfterPhysicsStepCallbacks = new Array();
  24071. this._onPhysicsCollideCallbacks = [];
  24072. this._deltaPosition = BABYLON.Vector3.Zero();
  24073. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  24074. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  24075. /**
  24076. * this function is executed by the physics engine.
  24077. */
  24078. this.beforeStep = function () {
  24079. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  24080. //conjugate deltaRotation
  24081. if (_this._deltaRotationConjugated) {
  24082. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  24083. }
  24084. else {
  24085. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  24086. }
  24087. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  24088. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  24089. func(_this);
  24090. });
  24091. };
  24092. /**
  24093. * this function is executed by the physics engine.
  24094. */
  24095. this.afterStep = function () {
  24096. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  24097. func(_this);
  24098. });
  24099. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  24100. _this.mesh.position.addInPlace(_this._deltaPosition);
  24101. if (_this._deltaRotation) {
  24102. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  24103. }
  24104. };
  24105. //event and body object due to cannon's event-based architecture.
  24106. this.onCollide = function (e) {
  24107. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  24108. if (otherImpostor) {
  24109. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  24110. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  24111. }).forEach(function (obj) {
  24112. obj.callback(_this, otherImpostor);
  24113. });
  24114. }
  24115. };
  24116. //default options params
  24117. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24118. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24119. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24120. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24121. this._joints = [];
  24122. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24123. if (!this._mesh.parent) {
  24124. this._init();
  24125. }
  24126. }
  24127. /**
  24128. * This function will completly initialize this impostor.
  24129. * It will create a new body - but only if this mesh has no parent.
  24130. * If it has, this impostor will not be used other than to define the impostor
  24131. * of the child mesh.
  24132. */
  24133. PhysicsImpostor.prototype._init = function () {
  24134. this._physicsEngine.removeImpostor(this);
  24135. this.physicsBody = null;
  24136. this._parent = this._parent || this._getPhysicsParent();
  24137. if (!this.parent) {
  24138. this._physicsEngine.addImpostor(this);
  24139. }
  24140. };
  24141. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24142. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24143. var parentMesh = this.mesh.parent;
  24144. return parentMesh.getPhysicsImpostor();
  24145. }
  24146. return;
  24147. };
  24148. /**
  24149. * Should a new body be generated.
  24150. */
  24151. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24152. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24153. };
  24154. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24155. this.forceUpdate();
  24156. };
  24157. /**
  24158. * Force a regeneration of this or the parent's impostor's body.
  24159. * Use under cautious - This will remove all joints already implemented.
  24160. */
  24161. PhysicsImpostor.prototype.forceUpdate = function () {
  24162. this._init();
  24163. if (this.parent) {
  24164. this.parent.forceUpdate();
  24165. }
  24166. };
  24167. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24168. get: function () {
  24169. return this._mesh;
  24170. },
  24171. enumerable: true,
  24172. configurable: true
  24173. });
  24174. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24175. /**
  24176. * Gets the body that holds this impostor. Either its own, or its parent.
  24177. */
  24178. get: function () {
  24179. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24180. },
  24181. /**
  24182. * Set the physics body. Used mainly by the physics engine/plugin
  24183. */
  24184. set: function (physicsBody) {
  24185. if (this._physicsBody) {
  24186. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24187. }
  24188. this._physicsBody = physicsBody;
  24189. this.resetUpdateFlags();
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24195. get: function () {
  24196. return this._parent;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24202. this._bodyUpdateRequired = false;
  24203. };
  24204. /**
  24205. * Get a specific parametes from the options parameter.
  24206. */
  24207. PhysicsImpostor.prototype.getParam = function (paramName) {
  24208. return this._options[paramName];
  24209. };
  24210. /**
  24211. * Sets a specific parameter in the options given to the physics plugin
  24212. */
  24213. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24214. this._options[paramName] = value;
  24215. this._bodyUpdateRequired = true;
  24216. };
  24217. /**
  24218. * Set the body's velocity.
  24219. */
  24220. PhysicsImpostor.prototype.setVelocity = function (velocity) {
  24221. this._physicsEngine.getPhysicsPlugin().setVelocity(this, velocity);
  24222. };
  24223. /**
  24224. * Execute a function with the physics plugin native code.
  24225. * Provide a function the will have two variables - the world object and the physics body object.
  24226. */
  24227. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24228. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24229. };
  24230. /**
  24231. * Register a function that will be executed before the physics world is stepping forward.
  24232. */
  24233. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24234. this._onBeforePhysicsStepCallbacks.push(func);
  24235. };
  24236. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24237. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24238. if (index > -1) {
  24239. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24240. }
  24241. else {
  24242. BABYLON.Tools.Warn("Function to remove was not found");
  24243. }
  24244. };
  24245. /**
  24246. * Register a function that will be executed after the physics step
  24247. */
  24248. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24249. this._onAfterPhysicsStepCallbacks.push(func);
  24250. };
  24251. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24252. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24253. if (index > -1) {
  24254. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24255. }
  24256. else {
  24257. BABYLON.Tools.Warn("Function to remove was not found");
  24258. }
  24259. };
  24260. /**
  24261. * register a function that will be executed when this impostor collides against a different body.
  24262. */
  24263. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24264. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24265. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  24266. };
  24267. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24268. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24269. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  24270. if (index > -1) {
  24271. this._onPhysicsCollideCallbacks.splice(index, 1);
  24272. }
  24273. else {
  24274. BABYLON.Tools.Warn("Function to remove was not found");
  24275. }
  24276. };
  24277. /**
  24278. * Apply a force
  24279. */
  24280. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24281. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24282. };
  24283. /**
  24284. * Apply an impulse
  24285. */
  24286. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24287. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24288. };
  24289. /**
  24290. * A help function to create a joint.
  24291. */
  24292. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24293. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24294. this.addJoint(otherImpostor, joint);
  24295. };
  24296. /**
  24297. * Add a joint to this impostor with a different impostor.
  24298. */
  24299. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24300. this._joints.push({
  24301. otherImpostor: otherImpostor,
  24302. joint: joint
  24303. });
  24304. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24305. };
  24306. /**
  24307. * Will keep this body still, in a sleep mode.
  24308. */
  24309. PhysicsImpostor.prototype.sleep = function () {
  24310. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  24311. };
  24312. /**
  24313. * Wake the body up.
  24314. */
  24315. PhysicsImpostor.prototype.wakeUp = function () {
  24316. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  24317. };
  24318. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24319. if (disposeChildren === void 0) { disposeChildren = true; }
  24320. this.physicsBody = null;
  24321. if (this.parent) {
  24322. this.parent.forceUpdate();
  24323. }
  24324. else {
  24325. this.mesh.getChildMeshes().forEach(function (mesh) {
  24326. if (mesh.physicsImpostor) {
  24327. if (disposeChildren) {
  24328. mesh.physicsImpostor.dispose();
  24329. mesh.physicsImpostor = null;
  24330. }
  24331. }
  24332. });
  24333. }
  24334. };
  24335. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24336. this._deltaPosition.copyFrom(position);
  24337. };
  24338. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24339. if (!this._deltaRotation) {
  24340. this._deltaRotation = new BABYLON.Quaternion();
  24341. }
  24342. this._deltaRotation.copyFrom(rotation);
  24343. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  24344. };
  24345. //Impostor types
  24346. PhysicsImpostor.NoImpostor = 0;
  24347. PhysicsImpostor.SphereImpostor = 1;
  24348. PhysicsImpostor.BoxImpostor = 2;
  24349. PhysicsImpostor.PlaneImpostor = 3;
  24350. PhysicsImpostor.MeshImpostor = 4;
  24351. PhysicsImpostor.CapsuleImpostor = 5;
  24352. PhysicsImpostor.ConeImpostor = 6;
  24353. PhysicsImpostor.CylinderImpostor = 7;
  24354. PhysicsImpostor.ConvexHullImpostor = 8;
  24355. PhysicsImpostor.HeightmapImpostor = 9;
  24356. return PhysicsImpostor;
  24357. })();
  24358. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24359. })(BABYLON || (BABYLON = {}));
  24360. var BABYLON;
  24361. (function (BABYLON) {
  24362. var PhysicsEngine = (function () {
  24363. function PhysicsEngine(gravity, _physicsPlugin) {
  24364. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24365. this._physicsPlugin = _physicsPlugin;
  24366. //new methods and parameters
  24367. this._impostors = [];
  24368. this._joints = [];
  24369. if (!this._physicsPlugin.isSupported()) {
  24370. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24371. + "Please make sure it is included.");
  24372. }
  24373. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24374. this.setGravity(gravity);
  24375. }
  24376. PhysicsEngine.prototype.setGravity = function (gravity) {
  24377. this.gravity = gravity;
  24378. this._physicsPlugin.setGravity(this.gravity);
  24379. };
  24380. PhysicsEngine.prototype.dispose = function () {
  24381. this._impostors.forEach(function (impostor) {
  24382. impostor.dispose();
  24383. });
  24384. this._physicsPlugin.dispose();
  24385. };
  24386. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24387. return this._physicsPlugin.name;
  24388. };
  24389. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24390. this._impostors.push(impostor);
  24391. //if no parent, generate the body
  24392. if (!impostor.parent) {
  24393. this._physicsPlugin.generatePhysicsBody(impostor);
  24394. }
  24395. };
  24396. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24397. var index = this._impostors.indexOf(impostor);
  24398. if (index > -1) {
  24399. var removed = this._impostors.splice(index, 1);
  24400. //Is it needed?
  24401. if (removed.length) {
  24402. //this will also remove it from the world.
  24403. removed[0].physicsBody = null;
  24404. }
  24405. }
  24406. };
  24407. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24408. var impostorJoint = {
  24409. mainImpostor: mainImpostor,
  24410. connectedImpostor: connectedImpostor,
  24411. joint: joint
  24412. };
  24413. this._joints.push(impostorJoint);
  24414. this._physicsPlugin.generateJoint(impostorJoint);
  24415. };
  24416. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24417. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24418. return (impostorJoint.connectedImpostor === connectedImpostor
  24419. && impostorJoint.joint === joint
  24420. && impostorJoint.mainImpostor === mainImpostor);
  24421. });
  24422. if (matchingJoints.length) {
  24423. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24424. }
  24425. };
  24426. /**
  24427. * Called by the scene. no need to call it.
  24428. */
  24429. PhysicsEngine.prototype._step = function (delta) {
  24430. var _this = this;
  24431. //check if any mesh has no body / requires an update
  24432. this._impostors.forEach(function (impostor) {
  24433. if (impostor.isBodyInitRequired()) {
  24434. _this._physicsPlugin.generatePhysicsBody(impostor);
  24435. }
  24436. });
  24437. if (delta > 0.1) {
  24438. delta = 0.1;
  24439. }
  24440. else if (delta <= 0) {
  24441. delta = 1.0 / 60.0;
  24442. }
  24443. this._physicsPlugin.executeStep(delta, this._impostors);
  24444. };
  24445. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24446. return this._physicsPlugin;
  24447. };
  24448. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24449. for (var i = 0; i < this._impostors.length; ++i) {
  24450. if (this._impostors[i].physicsBody === body) {
  24451. return this._impostors[i];
  24452. }
  24453. }
  24454. };
  24455. // Statics, Legacy support.
  24456. /**
  24457. * @Deprecated
  24458. *
  24459. */
  24460. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24461. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24462. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24463. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24464. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24465. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24466. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24467. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24468. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24469. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24470. PhysicsEngine.Epsilon = 0.001;
  24471. return PhysicsEngine;
  24472. })();
  24473. BABYLON.PhysicsEngine = PhysicsEngine;
  24474. })(BABYLON || (BABYLON = {}));
  24475. var BABYLON;
  24476. (function (BABYLON) {
  24477. var VertexData = (function () {
  24478. function VertexData() {
  24479. }
  24480. VertexData.prototype.set = function (data, kind) {
  24481. switch (kind) {
  24482. case BABYLON.VertexBuffer.PositionKind:
  24483. this.positions = data;
  24484. break;
  24485. case BABYLON.VertexBuffer.NormalKind:
  24486. this.normals = data;
  24487. break;
  24488. case BABYLON.VertexBuffer.UVKind:
  24489. this.uvs = data;
  24490. break;
  24491. case BABYLON.VertexBuffer.UV2Kind:
  24492. this.uvs2 = data;
  24493. break;
  24494. case BABYLON.VertexBuffer.UV3Kind:
  24495. this.uvs3 = data;
  24496. break;
  24497. case BABYLON.VertexBuffer.UV4Kind:
  24498. this.uvs4 = data;
  24499. break;
  24500. case BABYLON.VertexBuffer.UV5Kind:
  24501. this.uvs5 = data;
  24502. break;
  24503. case BABYLON.VertexBuffer.UV6Kind:
  24504. this.uvs6 = data;
  24505. break;
  24506. case BABYLON.VertexBuffer.ColorKind:
  24507. this.colors = data;
  24508. break;
  24509. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24510. this.matricesIndices = data;
  24511. break;
  24512. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24513. this.matricesWeights = data;
  24514. break;
  24515. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24516. this.matricesIndicesExtra = data;
  24517. break;
  24518. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24519. this.matricesWeightsExtra = data;
  24520. break;
  24521. }
  24522. };
  24523. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24524. this._applyTo(mesh, updatable);
  24525. };
  24526. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24527. this._applyTo(geometry, updatable);
  24528. };
  24529. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24530. this._update(mesh);
  24531. };
  24532. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24533. this._update(geometry);
  24534. };
  24535. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24536. if (this.positions) {
  24537. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24538. }
  24539. if (this.normals) {
  24540. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24541. }
  24542. if (this.uvs) {
  24543. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24544. }
  24545. if (this.uvs2) {
  24546. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24547. }
  24548. if (this.uvs3) {
  24549. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24550. }
  24551. if (this.uvs4) {
  24552. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24553. }
  24554. if (this.uvs5) {
  24555. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24556. }
  24557. if (this.uvs6) {
  24558. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24559. }
  24560. if (this.colors) {
  24561. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24562. }
  24563. if (this.matricesIndices) {
  24564. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24565. }
  24566. if (this.matricesWeights) {
  24567. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24568. }
  24569. if (this.matricesIndicesExtra) {
  24570. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24571. }
  24572. if (this.matricesWeightsExtra) {
  24573. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24574. }
  24575. if (this.indices) {
  24576. meshOrGeometry.setIndices(this.indices);
  24577. }
  24578. };
  24579. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24580. if (this.positions) {
  24581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24582. }
  24583. if (this.normals) {
  24584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24585. }
  24586. if (this.uvs) {
  24587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24588. }
  24589. if (this.uvs2) {
  24590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24591. }
  24592. if (this.uvs3) {
  24593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24594. }
  24595. if (this.uvs4) {
  24596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24597. }
  24598. if (this.uvs5) {
  24599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24600. }
  24601. if (this.uvs6) {
  24602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24603. }
  24604. if (this.colors) {
  24605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24606. }
  24607. if (this.matricesIndices) {
  24608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24609. }
  24610. if (this.matricesWeights) {
  24611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24612. }
  24613. if (this.matricesIndicesExtra) {
  24614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24615. }
  24616. if (this.matricesWeightsExtra) {
  24617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24618. }
  24619. if (this.indices) {
  24620. meshOrGeometry.setIndices(this.indices);
  24621. }
  24622. };
  24623. VertexData.prototype.transform = function (matrix) {
  24624. var transformed = BABYLON.Vector3.Zero();
  24625. var index;
  24626. if (this.positions) {
  24627. var position = BABYLON.Vector3.Zero();
  24628. for (index = 0; index < this.positions.length; index += 3) {
  24629. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24630. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24631. this.positions[index] = transformed.x;
  24632. this.positions[index + 1] = transformed.y;
  24633. this.positions[index + 2] = transformed.z;
  24634. }
  24635. }
  24636. if (this.normals) {
  24637. var normal = BABYLON.Vector3.Zero();
  24638. for (index = 0; index < this.normals.length; index += 3) {
  24639. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24640. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24641. this.normals[index] = transformed.x;
  24642. this.normals[index + 1] = transformed.y;
  24643. this.normals[index + 2] = transformed.z;
  24644. }
  24645. }
  24646. };
  24647. VertexData.prototype.merge = function (other) {
  24648. if (other.indices) {
  24649. if (!this.indices) {
  24650. this.indices = [];
  24651. }
  24652. var offset = this.positions ? this.positions.length / 3 : 0;
  24653. for (var index = 0; index < other.indices.length; index++) {
  24654. //TODO check type - if Int32Array!
  24655. this.indices.push(other.indices[index] + offset);
  24656. }
  24657. }
  24658. this.positions = this._mergeElement(this.positions, other.positions);
  24659. this.normals = this._mergeElement(this.normals, other.normals);
  24660. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24661. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24662. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24663. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24664. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24665. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24666. this.colors = this._mergeElement(this.colors, other.colors);
  24667. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24668. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24669. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24670. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24671. };
  24672. VertexData.prototype._mergeElement = function (source, other) {
  24673. if (!other)
  24674. return source;
  24675. if (!source)
  24676. return other;
  24677. var len = other.length + source.length;
  24678. var isSrcTypedArray = source instanceof Float32Array;
  24679. var isOthTypedArray = other instanceof Float32Array;
  24680. // use non-loop method when the source is Float32Array
  24681. if (isSrcTypedArray) {
  24682. var ret32 = new Float32Array(len);
  24683. ret32.set(source);
  24684. ret32.set(other, source.length);
  24685. return ret32;
  24686. }
  24687. else if (!isOthTypedArray) {
  24688. return source.concat(other);
  24689. }
  24690. else {
  24691. var ret = source.slice(0); // copy source to a separate array
  24692. for (var i = 0, len = other.length; i < len; i++) {
  24693. ret.push(other[i]);
  24694. }
  24695. return ret;
  24696. }
  24697. };
  24698. VertexData.prototype.serialize = function () {
  24699. var serializationObject = this.serialize();
  24700. if (this.positions) {
  24701. serializationObject.positions = this.positions;
  24702. }
  24703. if (this.normals) {
  24704. serializationObject.normals = this.normals;
  24705. }
  24706. if (this.uvs) {
  24707. serializationObject.uvs = this.uvs;
  24708. }
  24709. if (this.uvs2) {
  24710. serializationObject.uvs2 = this.uvs2;
  24711. }
  24712. if (this.uvs3) {
  24713. serializationObject.uvs3 = this.uvs3;
  24714. }
  24715. if (this.uvs4) {
  24716. serializationObject.uvs4 = this.uvs4;
  24717. }
  24718. if (this.uvs5) {
  24719. serializationObject.uvs5 = this.uvs5;
  24720. }
  24721. if (this.uvs6) {
  24722. serializationObject.uvs6 = this.uvs6;
  24723. }
  24724. if (this.colors) {
  24725. serializationObject.colors = this.colors;
  24726. }
  24727. if (this.matricesIndices) {
  24728. serializationObject.matricesIndices = this.matricesIndices;
  24729. serializationObject.matricesIndices._isExpanded = true;
  24730. }
  24731. if (this.matricesWeights) {
  24732. serializationObject.matricesWeights = this.matricesWeights;
  24733. }
  24734. if (this.matricesIndicesExtra) {
  24735. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24736. serializationObject.matricesIndicesExtra._isExpanded = true;
  24737. }
  24738. if (this.matricesWeightsExtra) {
  24739. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24740. }
  24741. serializationObject.indices = this.indices;
  24742. return serializationObject;
  24743. };
  24744. // Statics
  24745. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24746. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24747. };
  24748. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24749. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24750. };
  24751. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24752. var result = new VertexData();
  24753. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24754. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24755. }
  24756. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24757. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24758. }
  24759. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24760. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24761. }
  24762. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24763. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24764. }
  24765. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24766. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24767. }
  24768. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24769. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24770. }
  24771. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24772. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24773. }
  24774. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24775. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24776. }
  24777. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24778. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24779. }
  24780. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24781. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24782. }
  24783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24784. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24785. }
  24786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24787. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24788. }
  24789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24790. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24791. }
  24792. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24793. return result;
  24794. };
  24795. VertexData.CreateRibbon = function (options) {
  24796. var pathArray = options.pathArray;
  24797. var closeArray = options.closeArray || false;
  24798. var closePath = options.closePath || false;
  24799. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24800. var offset = options.offset || defaultOffset;
  24801. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24802. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24803. var positions = [];
  24804. var indices = [];
  24805. var normals = [];
  24806. var uvs = [];
  24807. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24808. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24809. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24810. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24811. var minlg; // minimal length among all paths from pathArray
  24812. var lg = []; // array of path lengths : nb of vertex per path
  24813. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24814. var p; // path iterator
  24815. var i; // point iterator
  24816. var j; // point iterator
  24817. // if single path in pathArray
  24818. if (pathArray.length < 2) {
  24819. var ar1 = [];
  24820. var ar2 = [];
  24821. for (i = 0; i < pathArray[0].length - offset; i++) {
  24822. ar1.push(pathArray[0][i]);
  24823. ar2.push(pathArray[0][i + offset]);
  24824. }
  24825. pathArray = [ar1, ar2];
  24826. }
  24827. // positions and horizontal distances (u)
  24828. var idc = 0;
  24829. var closePathCorr = (closePath) ? 1 : 0;
  24830. var path;
  24831. var l;
  24832. minlg = pathArray[0].length;
  24833. var vectlg;
  24834. var dist;
  24835. for (p = 0; p < pathArray.length; p++) {
  24836. uTotalDistance[p] = 0;
  24837. us[p] = [0];
  24838. path = pathArray[p];
  24839. l = path.length;
  24840. minlg = (minlg < l) ? minlg : l;
  24841. j = 0;
  24842. while (j < l) {
  24843. positions.push(path[j].x, path[j].y, path[j].z);
  24844. if (j > 0) {
  24845. vectlg = path[j].subtract(path[j - 1]).length();
  24846. dist = vectlg + uTotalDistance[p];
  24847. us[p].push(dist);
  24848. uTotalDistance[p] = dist;
  24849. }
  24850. j++;
  24851. }
  24852. if (closePath) {
  24853. j--;
  24854. positions.push(path[0].x, path[0].y, path[0].z);
  24855. vectlg = path[j].subtract(path[0]).length();
  24856. dist = vectlg + uTotalDistance[p];
  24857. us[p].push(dist);
  24858. uTotalDistance[p] = dist;
  24859. }
  24860. lg[p] = l + closePathCorr;
  24861. idx[p] = idc;
  24862. idc += (l + closePathCorr);
  24863. }
  24864. // vertical distances (v)
  24865. var path1;
  24866. var path2;
  24867. var vertex1;
  24868. var vertex2;
  24869. for (i = 0; i < minlg + closePathCorr; i++) {
  24870. vTotalDistance[i] = 0;
  24871. vs[i] = [0];
  24872. for (p = 0; p < pathArray.length - 1; p++) {
  24873. path1 = pathArray[p];
  24874. path2 = pathArray[p + 1];
  24875. if (i === minlg) {
  24876. vertex1 = path1[0];
  24877. vertex2 = path2[0];
  24878. }
  24879. else {
  24880. vertex1 = path1[i];
  24881. vertex2 = path2[i];
  24882. }
  24883. vectlg = vertex2.subtract(vertex1).length();
  24884. dist = vectlg + vTotalDistance[i];
  24885. vs[i].push(dist);
  24886. vTotalDistance[i] = dist;
  24887. }
  24888. if (closeArray) {
  24889. path1 = pathArray[p];
  24890. path2 = pathArray[0];
  24891. if (i === minlg) {
  24892. vertex2 = path2[0];
  24893. }
  24894. vectlg = vertex2.subtract(vertex1).length();
  24895. dist = vectlg + vTotalDistance[i];
  24896. vTotalDistance[i] = dist;
  24897. }
  24898. }
  24899. // uvs
  24900. var u;
  24901. var v;
  24902. for (p = 0; p < pathArray.length; p++) {
  24903. for (i = 0; i < minlg + closePathCorr; i++) {
  24904. u = us[p][i] / uTotalDistance[p];
  24905. v = vs[i][p] / vTotalDistance[i];
  24906. uvs.push(u, v);
  24907. }
  24908. }
  24909. // indices
  24910. p = 0; // path index
  24911. var pi = 0; // positions array index
  24912. var l1 = lg[p] - 1; // path1 length
  24913. var l2 = lg[p + 1] - 1; // path2 length
  24914. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24915. var shft = idx[1] - idx[0]; // shift
  24916. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24917. while (pi <= min && p < path1nb) {
  24918. // 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
  24919. indices.push(pi, pi + shft, pi + 1);
  24920. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24921. pi += 1;
  24922. if (pi === min) {
  24923. p++;
  24924. if (p === lg.length - 1) {
  24925. shft = idx[0] - idx[p];
  24926. l1 = lg[p] - 1;
  24927. l2 = lg[0] - 1;
  24928. }
  24929. else {
  24930. shft = idx[p + 1] - idx[p];
  24931. l1 = lg[p] - 1;
  24932. l2 = lg[p + 1] - 1;
  24933. }
  24934. pi = idx[p];
  24935. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24936. }
  24937. }
  24938. // normals
  24939. VertexData.ComputeNormals(positions, indices, normals);
  24940. if (closePath) {
  24941. var indexFirst = 0;
  24942. var indexLast = 0;
  24943. for (p = 0; p < pathArray.length; p++) {
  24944. indexFirst = idx[p] * 3;
  24945. if (p + 1 < pathArray.length) {
  24946. indexLast = (idx[p + 1] - 1) * 3;
  24947. }
  24948. else {
  24949. indexLast = normals.length - 3;
  24950. }
  24951. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24952. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24953. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24954. normals[indexLast] = normals[indexFirst];
  24955. normals[indexLast + 1] = normals[indexFirst + 1];
  24956. normals[indexLast + 2] = normals[indexFirst + 2];
  24957. }
  24958. }
  24959. // sides
  24960. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24961. // Result
  24962. var vertexData = new VertexData();
  24963. vertexData.indices = indices;
  24964. vertexData.positions = positions;
  24965. vertexData.normals = normals;
  24966. vertexData.uvs = uvs;
  24967. if (closePath) {
  24968. vertexData._idx = idx;
  24969. }
  24970. return vertexData;
  24971. };
  24972. VertexData.CreateBox = function (options) {
  24973. var normalsSource = [
  24974. new BABYLON.Vector3(0, 0, 1),
  24975. new BABYLON.Vector3(0, 0, -1),
  24976. new BABYLON.Vector3(1, 0, 0),
  24977. new BABYLON.Vector3(-1, 0, 0),
  24978. new BABYLON.Vector3(0, 1, 0),
  24979. new BABYLON.Vector3(0, -1, 0)
  24980. ];
  24981. var indices = [];
  24982. var positions = [];
  24983. var normals = [];
  24984. var uvs = [];
  24985. var width = options.width || options.size || 1;
  24986. var height = options.height || options.size || 1;
  24987. var depth = options.depth || options.size || 1;
  24988. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24989. var faceUV = options.faceUV || new Array(6);
  24990. var faceColors = options.faceColors;
  24991. var colors = [];
  24992. // default face colors and UV if undefined
  24993. for (var f = 0; f < 6; f++) {
  24994. if (faceUV[f] === undefined) {
  24995. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24996. }
  24997. if (faceColors && faceColors[f] === undefined) {
  24998. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24999. }
  25000. }
  25001. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25002. // Create each face in turn.
  25003. for (var index = 0; index < normalsSource.length; index++) {
  25004. var normal = normalsSource[index];
  25005. // Get two vectors perpendicular to the face normal and to each other.
  25006. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25007. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25008. // Six indices (two triangles) per face.
  25009. var verticesLength = positions.length / 3;
  25010. indices.push(verticesLength);
  25011. indices.push(verticesLength + 1);
  25012. indices.push(verticesLength + 2);
  25013. indices.push(verticesLength);
  25014. indices.push(verticesLength + 2);
  25015. indices.push(verticesLength + 3);
  25016. // Four vertices per face.
  25017. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25018. positions.push(vertex.x, vertex.y, vertex.z);
  25019. normals.push(normal.x, normal.y, normal.z);
  25020. uvs.push(faceUV[index].z, faceUV[index].w);
  25021. if (faceColors) {
  25022. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25023. }
  25024. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25025. positions.push(vertex.x, vertex.y, vertex.z);
  25026. normals.push(normal.x, normal.y, normal.z);
  25027. uvs.push(faceUV[index].x, faceUV[index].w);
  25028. if (faceColors) {
  25029. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25030. }
  25031. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25032. positions.push(vertex.x, vertex.y, vertex.z);
  25033. normals.push(normal.x, normal.y, normal.z);
  25034. uvs.push(faceUV[index].x, faceUV[index].y);
  25035. if (faceColors) {
  25036. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25037. }
  25038. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25039. positions.push(vertex.x, vertex.y, vertex.z);
  25040. normals.push(normal.x, normal.y, normal.z);
  25041. uvs.push(faceUV[index].z, faceUV[index].y);
  25042. if (faceColors) {
  25043. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25044. }
  25045. }
  25046. // sides
  25047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25048. // Result
  25049. var vertexData = new VertexData();
  25050. vertexData.indices = indices;
  25051. vertexData.positions = positions;
  25052. vertexData.normals = normals;
  25053. vertexData.uvs = uvs;
  25054. if (faceColors) {
  25055. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25056. vertexData.colors = totalColors;
  25057. }
  25058. return vertexData;
  25059. };
  25060. VertexData.CreateSphere = function (options) {
  25061. var segments = options.segments || 32;
  25062. var diameterX = options.diameterX || options.diameter || 1;
  25063. var diameterY = options.diameterY || options.diameter || 1;
  25064. var diameterZ = options.diameterZ || options.diameter || 1;
  25065. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25066. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25068. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25069. var totalZRotationSteps = 2 + segments;
  25070. var totalYRotationSteps = 2 * totalZRotationSteps;
  25071. var indices = [];
  25072. var positions = [];
  25073. var normals = [];
  25074. var uvs = [];
  25075. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25076. var normalizedZ = zRotationStep / totalZRotationSteps;
  25077. var angleZ = normalizedZ * Math.PI * slice;
  25078. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25079. var normalizedY = yRotationStep / totalYRotationSteps;
  25080. var angleY = normalizedY * Math.PI * 2 * arc;
  25081. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25082. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25083. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25084. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25085. var vertex = complete.multiply(radius);
  25086. var normal = complete.divide(radius).normalize();
  25087. positions.push(vertex.x, vertex.y, vertex.z);
  25088. normals.push(normal.x, normal.y, normal.z);
  25089. uvs.push(normalizedY, normalizedZ);
  25090. }
  25091. if (zRotationStep > 0) {
  25092. var verticesCount = positions.length / 3;
  25093. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25094. indices.push((firstIndex));
  25095. indices.push((firstIndex + 1));
  25096. indices.push(firstIndex + totalYRotationSteps + 1);
  25097. indices.push((firstIndex + totalYRotationSteps + 1));
  25098. indices.push((firstIndex + 1));
  25099. indices.push((firstIndex + totalYRotationSteps + 2));
  25100. }
  25101. }
  25102. }
  25103. // Sides
  25104. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25105. // Result
  25106. var vertexData = new VertexData();
  25107. vertexData.indices = indices;
  25108. vertexData.positions = positions;
  25109. vertexData.normals = normals;
  25110. vertexData.uvs = uvs;
  25111. return vertexData;
  25112. };
  25113. // Cylinder and cone
  25114. VertexData.CreateCylinder = function (options) {
  25115. var height = options.height || 2;
  25116. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25117. var diameterBottom = options.diameterBottom || options.diameter || 1;
  25118. var tessellation = options.tessellation || 24;
  25119. var subdivisions = options.subdivisions || 1;
  25120. var hasRings = options.hasRings;
  25121. var enclose = options.enclose;
  25122. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25123. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25124. var faceUV = options.faceUV || new Array(3);
  25125. var faceColors = options.faceColors;
  25126. // default face colors and UV if undefined
  25127. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25128. var ringNb = (hasRings) ? subdivisions : 1;
  25129. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25130. var f;
  25131. for (f = 0; f < surfaceNb; f++) {
  25132. if (faceColors && faceColors[f] === undefined) {
  25133. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25134. }
  25135. }
  25136. for (f = 0; f < surfaceNb; f++) {
  25137. if (faceUV && faceUV[f] === undefined) {
  25138. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25139. }
  25140. }
  25141. var indices = [];
  25142. var positions = [];
  25143. var normals = [];
  25144. var uvs = [];
  25145. var colors = [];
  25146. var angle_step = Math.PI * 2 * arc / tessellation;
  25147. var angle;
  25148. var h;
  25149. var radius;
  25150. var tan = (diameterBottom - diameterTop) / 2 / height;
  25151. var ringVertex = BABYLON.Vector3.Zero();
  25152. var ringNormal = BABYLON.Vector3.Zero();
  25153. var ringFirstVertex = BABYLON.Vector3.Zero();
  25154. var ringFirstNormal = BABYLON.Vector3.Zero();
  25155. var quadNormal = BABYLON.Vector3.Zero();
  25156. var Y = BABYLON.Axis.Y;
  25157. // positions, normals, uvs
  25158. var i;
  25159. var j;
  25160. var r;
  25161. var ringIdx = 1;
  25162. var s = 1; // surface index
  25163. var cs = 0;
  25164. var v = 0;
  25165. for (i = 0; i <= subdivisions; i++) {
  25166. h = i / subdivisions;
  25167. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25168. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25169. for (r = 0; r < ringIdx; r++) {
  25170. if (hasRings) {
  25171. s += r;
  25172. }
  25173. if (enclose) {
  25174. s += 2 * r;
  25175. }
  25176. for (j = 0; j <= tessellation; j++) {
  25177. angle = j * angle_step;
  25178. // position
  25179. ringVertex.x = Math.cos(-angle) * radius;
  25180. ringVertex.y = -height / 2 + h * height;
  25181. ringVertex.z = Math.sin(-angle) * radius;
  25182. // normal
  25183. if (diameterTop === 0 && i === subdivisions) {
  25184. // if no top cap, reuse former normals
  25185. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25186. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25187. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25188. }
  25189. else {
  25190. ringNormal.x = ringVertex.x;
  25191. ringNormal.z = ringVertex.z;
  25192. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25193. ringNormal.normalize();
  25194. }
  25195. // keep first ring vertex values for enclose
  25196. if (j === 0) {
  25197. ringFirstVertex.copyFrom(ringVertex);
  25198. ringFirstNormal.copyFrom(ringNormal);
  25199. }
  25200. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25201. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25202. if (hasRings) {
  25203. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25204. }
  25205. else {
  25206. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25207. }
  25208. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25209. if (faceColors) {
  25210. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25211. }
  25212. }
  25213. // if enclose, add four vertices and their dedicated normals
  25214. if (arc !== 1 && enclose) {
  25215. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25216. positions.push(0, ringVertex.y, 0);
  25217. positions.push(0, ringVertex.y, 0);
  25218. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25219. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25220. quadNormal.normalize();
  25221. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25222. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25223. quadNormal.normalize();
  25224. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25225. if (hasRings) {
  25226. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25227. }
  25228. else {
  25229. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25230. }
  25231. uvs.push(faceUV[s + 1].x, v);
  25232. uvs.push(faceUV[s + 1].z, v);
  25233. if (hasRings) {
  25234. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25235. }
  25236. else {
  25237. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25238. }
  25239. uvs.push(faceUV[s + 2].x, v);
  25240. uvs.push(faceUV[s + 2].z, v);
  25241. if (faceColors) {
  25242. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25243. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25244. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25245. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25246. }
  25247. }
  25248. if (cs !== s) {
  25249. cs = s;
  25250. }
  25251. }
  25252. }
  25253. // indices
  25254. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25255. var s;
  25256. i = 0;
  25257. for (s = 0; s < subdivisions; s++) {
  25258. for (j = 0; j < tessellation; j++) {
  25259. var i0 = i * (e + 1) + j;
  25260. var i1 = (i + 1) * (e + 1) + j;
  25261. var i2 = i * (e + 1) + (j + 1);
  25262. var i3 = (i + 1) * (e + 1) + (j + 1);
  25263. indices.push(i0, i1, i2);
  25264. indices.push(i3, i2, i1);
  25265. }
  25266. if (arc !== 1 && enclose) {
  25267. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25268. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25269. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25270. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25271. }
  25272. i = (hasRings) ? (i + 2) : (i + 1);
  25273. }
  25274. // Caps
  25275. var createCylinderCap = function (isTop) {
  25276. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25277. if (radius === 0) {
  25278. return;
  25279. }
  25280. // Cap positions, normals & uvs
  25281. var angle;
  25282. var circleVector;
  25283. var i;
  25284. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25285. var c;
  25286. if (faceColors) {
  25287. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25288. }
  25289. // cap center
  25290. var vbase = positions.length / 3;
  25291. var offset = isTop ? height / 2 : -height / 2;
  25292. var center = new BABYLON.Vector3(0, offset, 0);
  25293. positions.push(center.x, center.y, center.z);
  25294. normals.push(0, isTop ? 1 : -1, 0);
  25295. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25296. if (faceColors) {
  25297. colors.push(c.r, c.g, c.b, c.a);
  25298. }
  25299. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25300. for (i = 0; i <= tessellation; i++) {
  25301. angle = Math.PI * 2 * i * arc / tessellation;
  25302. var cos = Math.cos(-angle);
  25303. var sin = Math.sin(-angle);
  25304. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25305. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25306. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25307. normals.push(0, isTop ? 1 : -1, 0);
  25308. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25309. if (faceColors) {
  25310. colors.push(c.r, c.g, c.b, c.a);
  25311. }
  25312. }
  25313. // Cap indices
  25314. for (i = 0; i < tessellation; i++) {
  25315. if (!isTop) {
  25316. indices.push(vbase);
  25317. indices.push(vbase + (i + 1));
  25318. indices.push(vbase + (i + 2));
  25319. }
  25320. else {
  25321. indices.push(vbase);
  25322. indices.push(vbase + (i + 2));
  25323. indices.push(vbase + (i + 1));
  25324. }
  25325. }
  25326. };
  25327. // add caps to geometry
  25328. createCylinderCap(false);
  25329. createCylinderCap(true);
  25330. // Sides
  25331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25332. var vertexData = new VertexData();
  25333. vertexData.indices = indices;
  25334. vertexData.positions = positions;
  25335. vertexData.normals = normals;
  25336. vertexData.uvs = uvs;
  25337. if (faceColors) {
  25338. vertexData.colors = colors;
  25339. }
  25340. return vertexData;
  25341. };
  25342. VertexData.CreateTorus = function (options) {
  25343. var indices = [];
  25344. var positions = [];
  25345. var normals = [];
  25346. var uvs = [];
  25347. var diameter = options.diameter || 1;
  25348. var thickness = options.thickness || 0.5;
  25349. var tessellation = options.tessellation || 16;
  25350. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25351. var stride = tessellation + 1;
  25352. for (var i = 0; i <= tessellation; i++) {
  25353. var u = i / tessellation;
  25354. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25355. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25356. for (var j = 0; j <= tessellation; j++) {
  25357. var v = 1 - j / tessellation;
  25358. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25359. var dx = Math.cos(innerAngle);
  25360. var dy = Math.sin(innerAngle);
  25361. // Create a vertex.
  25362. var normal = new BABYLON.Vector3(dx, dy, 0);
  25363. var position = normal.scale(thickness / 2);
  25364. var textureCoordinate = new BABYLON.Vector2(u, v);
  25365. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25366. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25367. positions.push(position.x, position.y, position.z);
  25368. normals.push(normal.x, normal.y, normal.z);
  25369. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25370. // And create indices for two triangles.
  25371. var nextI = (i + 1) % stride;
  25372. var nextJ = (j + 1) % stride;
  25373. indices.push(i * stride + j);
  25374. indices.push(i * stride + nextJ);
  25375. indices.push(nextI * stride + j);
  25376. indices.push(i * stride + nextJ);
  25377. indices.push(nextI * stride + nextJ);
  25378. indices.push(nextI * stride + j);
  25379. }
  25380. }
  25381. // Sides
  25382. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25383. // Result
  25384. var vertexData = new VertexData();
  25385. vertexData.indices = indices;
  25386. vertexData.positions = positions;
  25387. vertexData.normals = normals;
  25388. vertexData.uvs = uvs;
  25389. return vertexData;
  25390. };
  25391. VertexData.CreateLineSystem = function (options) {
  25392. var indices = [];
  25393. var positions = [];
  25394. var lines = options.lines;
  25395. var idx = 0;
  25396. for (var l = 0; l < lines.length; l++) {
  25397. var points = lines[l];
  25398. for (var index = 0; index < points.length; index++) {
  25399. positions.push(points[index].x, points[index].y, points[index].z);
  25400. if (index > 0) {
  25401. indices.push(idx - 1);
  25402. indices.push(idx);
  25403. }
  25404. idx++;
  25405. }
  25406. }
  25407. var vertexData = new VertexData();
  25408. vertexData.indices = indices;
  25409. vertexData.positions = positions;
  25410. return vertexData;
  25411. };
  25412. VertexData.CreateDashedLines = function (options) {
  25413. var dashSize = options.dashSize || 3;
  25414. var gapSize = options.gapSize || 1;
  25415. var dashNb = options.dashNb || 200;
  25416. var points = options.points;
  25417. var positions = new Array();
  25418. var indices = new Array();
  25419. var curvect = BABYLON.Vector3.Zero();
  25420. var lg = 0;
  25421. var nb = 0;
  25422. var shft = 0;
  25423. var dashshft = 0;
  25424. var curshft = 0;
  25425. var idx = 0;
  25426. var i = 0;
  25427. for (i = 0; i < points.length - 1; i++) {
  25428. points[i + 1].subtractToRef(points[i], curvect);
  25429. lg += curvect.length();
  25430. }
  25431. shft = lg / dashNb;
  25432. dashshft = dashSize * shft / (dashSize + gapSize);
  25433. for (i = 0; i < points.length - 1; i++) {
  25434. points[i + 1].subtractToRef(points[i], curvect);
  25435. nb = Math.floor(curvect.length() / shft);
  25436. curvect.normalize();
  25437. for (var j = 0; j < nb; j++) {
  25438. curshft = shft * j;
  25439. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25440. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25441. indices.push(idx, idx + 1);
  25442. idx += 2;
  25443. }
  25444. }
  25445. // Result
  25446. var vertexData = new VertexData();
  25447. vertexData.positions = positions;
  25448. vertexData.indices = indices;
  25449. return vertexData;
  25450. };
  25451. VertexData.CreateGround = function (options) {
  25452. var indices = [];
  25453. var positions = [];
  25454. var normals = [];
  25455. var uvs = [];
  25456. var row, col;
  25457. var width = options.width || 1;
  25458. var height = options.height || 1;
  25459. var subdivisions = options.subdivisions || 1;
  25460. for (row = 0; row <= subdivisions; row++) {
  25461. for (col = 0; col <= subdivisions; col++) {
  25462. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25463. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25464. positions.push(position.x, position.y, position.z);
  25465. normals.push(normal.x, normal.y, normal.z);
  25466. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25467. }
  25468. }
  25469. for (row = 0; row < subdivisions; row++) {
  25470. for (col = 0; col < subdivisions; col++) {
  25471. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25472. indices.push(col + 1 + row * (subdivisions + 1));
  25473. indices.push(col + row * (subdivisions + 1));
  25474. indices.push(col + (row + 1) * (subdivisions + 1));
  25475. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25476. indices.push(col + row * (subdivisions + 1));
  25477. }
  25478. }
  25479. // Result
  25480. var vertexData = new VertexData();
  25481. vertexData.indices = indices;
  25482. vertexData.positions = positions;
  25483. vertexData.normals = normals;
  25484. vertexData.uvs = uvs;
  25485. return vertexData;
  25486. };
  25487. VertexData.CreateTiledGround = function (options) {
  25488. var xmin = options.xmin;
  25489. var zmin = options.zmin;
  25490. var xmax = options.xmax;
  25491. var zmax = options.zmax;
  25492. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25493. var precision = options.precision || { w: 1, h: 1 };
  25494. var indices = [];
  25495. var positions = [];
  25496. var normals = [];
  25497. var uvs = [];
  25498. var row, col, tileRow, tileCol;
  25499. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25500. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25501. precision.w = (precision.w < 1) ? 1 : precision.w;
  25502. precision.h = (precision.h < 1) ? 1 : precision.h;
  25503. var tileSize = {
  25504. 'w': (xmax - xmin) / subdivisions.w,
  25505. 'h': (zmax - zmin) / subdivisions.h
  25506. };
  25507. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25508. // Indices
  25509. var base = positions.length / 3;
  25510. var rowLength = precision.w + 1;
  25511. for (row = 0; row < precision.h; row++) {
  25512. for (col = 0; col < precision.w; col++) {
  25513. var square = [
  25514. base + col + row * rowLength,
  25515. base + (col + 1) + row * rowLength,
  25516. base + (col + 1) + (row + 1) * rowLength,
  25517. base + col + (row + 1) * rowLength
  25518. ];
  25519. indices.push(square[1]);
  25520. indices.push(square[2]);
  25521. indices.push(square[3]);
  25522. indices.push(square[0]);
  25523. indices.push(square[1]);
  25524. indices.push(square[3]);
  25525. }
  25526. }
  25527. // Position, normals and uvs
  25528. var position = BABYLON.Vector3.Zero();
  25529. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25530. for (row = 0; row <= precision.h; row++) {
  25531. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25532. for (col = 0; col <= precision.w; col++) {
  25533. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25534. position.y = 0;
  25535. positions.push(position.x, position.y, position.z);
  25536. normals.push(normal.x, normal.y, normal.z);
  25537. uvs.push(col / precision.w, row / precision.h);
  25538. }
  25539. }
  25540. }
  25541. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25542. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25543. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25544. }
  25545. }
  25546. // Result
  25547. var vertexData = new VertexData();
  25548. vertexData.indices = indices;
  25549. vertexData.positions = positions;
  25550. vertexData.normals = normals;
  25551. vertexData.uvs = uvs;
  25552. return vertexData;
  25553. };
  25554. VertexData.CreateGroundFromHeightMap = function (options) {
  25555. var indices = [];
  25556. var positions = [];
  25557. var normals = [];
  25558. var uvs = [];
  25559. var row, col;
  25560. // Vertices
  25561. for (row = 0; row <= options.subdivisions; row++) {
  25562. for (col = 0; col <= options.subdivisions; col++) {
  25563. 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));
  25564. // Compute height
  25565. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25566. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25567. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25568. var r = options.buffer[pos] / 255.0;
  25569. var g = options.buffer[pos + 1] / 255.0;
  25570. var b = options.buffer[pos + 2] / 255.0;
  25571. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25572. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25573. // Add vertex
  25574. positions.push(position.x, position.y, position.z);
  25575. normals.push(0, 0, 0);
  25576. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25577. }
  25578. }
  25579. // Indices
  25580. for (row = 0; row < options.subdivisions; row++) {
  25581. for (col = 0; col < options.subdivisions; col++) {
  25582. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25583. indices.push(col + 1 + row * (options.subdivisions + 1));
  25584. indices.push(col + row * (options.subdivisions + 1));
  25585. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25586. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25587. indices.push(col + row * (options.subdivisions + 1));
  25588. }
  25589. }
  25590. // Normals
  25591. VertexData.ComputeNormals(positions, indices, normals);
  25592. // Result
  25593. var vertexData = new VertexData();
  25594. vertexData.indices = indices;
  25595. vertexData.positions = positions;
  25596. vertexData.normals = normals;
  25597. vertexData.uvs = uvs;
  25598. return vertexData;
  25599. };
  25600. VertexData.CreatePlane = function (options) {
  25601. var indices = [];
  25602. var positions = [];
  25603. var normals = [];
  25604. var uvs = [];
  25605. var width = options.width || options.size || 1;
  25606. var height = options.height || options.size || 1;
  25607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25608. // Vertices
  25609. var halfWidth = width / 2.0;
  25610. var halfHeight = height / 2.0;
  25611. positions.push(-halfWidth, -halfHeight, 0);
  25612. normals.push(0, 0, -1.0);
  25613. uvs.push(0.0, 0.0);
  25614. positions.push(halfWidth, -halfHeight, 0);
  25615. normals.push(0, 0, -1.0);
  25616. uvs.push(1.0, 0.0);
  25617. positions.push(halfWidth, halfHeight, 0);
  25618. normals.push(0, 0, -1.0);
  25619. uvs.push(1.0, 1.0);
  25620. positions.push(-halfWidth, halfHeight, 0);
  25621. normals.push(0, 0, -1.0);
  25622. uvs.push(0.0, 1.0);
  25623. // Indices
  25624. indices.push(0);
  25625. indices.push(1);
  25626. indices.push(2);
  25627. indices.push(0);
  25628. indices.push(2);
  25629. indices.push(3);
  25630. // Sides
  25631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25632. // Result
  25633. var vertexData = new VertexData();
  25634. vertexData.indices = indices;
  25635. vertexData.positions = positions;
  25636. vertexData.normals = normals;
  25637. vertexData.uvs = uvs;
  25638. return vertexData;
  25639. };
  25640. VertexData.CreateDisc = function (options) {
  25641. var positions = [];
  25642. var indices = [];
  25643. var normals = [];
  25644. var uvs = [];
  25645. var radius = options.radius || 0.5;
  25646. var tessellation = options.tessellation || 64;
  25647. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25648. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25649. // positions and uvs
  25650. positions.push(0, 0, 0); // disc center first
  25651. uvs.push(0.5, 0.5);
  25652. var theta = Math.PI * 2 * arc;
  25653. var step = theta / tessellation;
  25654. for (var a = 0; a < theta; a += step) {
  25655. var x = Math.cos(a);
  25656. var y = Math.sin(a);
  25657. var u = (x + 1) / 2;
  25658. var v = (1 - y) / 2;
  25659. positions.push(radius * x, radius * y, 0);
  25660. uvs.push(u, v);
  25661. }
  25662. if (arc === 1) {
  25663. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25664. uvs.push(uvs[2], uvs[3]);
  25665. }
  25666. //indices
  25667. var vertexNb = positions.length / 3;
  25668. for (var i = 1; i < vertexNb - 1; i++) {
  25669. indices.push(i + 1, 0, i);
  25670. }
  25671. // result
  25672. VertexData.ComputeNormals(positions, indices, normals);
  25673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25674. var vertexData = new VertexData();
  25675. vertexData.indices = indices;
  25676. vertexData.positions = positions;
  25677. vertexData.normals = normals;
  25678. vertexData.uvs = uvs;
  25679. return vertexData;
  25680. };
  25681. VertexData.CreateIcoSphere = function (options) {
  25682. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25683. var radius = options.radius || 1;
  25684. var flat = (options.flat === undefined) ? true : options.flat;
  25685. var subdivisions = options.subdivisions || 4;
  25686. var radiusX = options.radiusX || radius;
  25687. var radiusY = options.radiusY || radius;
  25688. var radiusZ = options.radiusZ || radius;
  25689. var t = (1 + Math.sqrt(5)) / 2;
  25690. // 12 vertex x,y,z
  25691. var ico_vertices = [
  25692. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25693. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25694. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25695. ];
  25696. // index of 3 vertex makes a face of icopshere
  25697. var ico_indices = [
  25698. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25699. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25700. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25701. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25702. ];
  25703. // vertex for uv have aliased position, not for UV
  25704. var vertices_unalias_id = [
  25705. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25706. // vertex alias
  25707. 0,
  25708. 2,
  25709. 3,
  25710. 3,
  25711. 3,
  25712. 4,
  25713. 7,
  25714. 8,
  25715. 9,
  25716. 9,
  25717. 10,
  25718. 11 // 23: B + 12
  25719. ];
  25720. // uv as integer step (not pixels !)
  25721. var ico_vertexuv = [
  25722. 5, 1, 3, 1, 6, 4, 0, 0,
  25723. 5, 3, 4, 2, 2, 2, 4, 0,
  25724. 2, 0, 1, 1, 6, 0, 6, 2,
  25725. // vertex alias (for same vertex on different faces)
  25726. 0, 4,
  25727. 3, 3,
  25728. 4, 4,
  25729. 3, 1,
  25730. 4, 2,
  25731. 4, 4,
  25732. 0, 2,
  25733. 1, 1,
  25734. 2, 2,
  25735. 3, 3,
  25736. 1, 3,
  25737. 2, 4 // 23: B + 12
  25738. ];
  25739. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25740. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25741. // First island of uv mapping
  25742. // v = 4h 3+ 2
  25743. // v = 3h 9+ 4
  25744. // v = 2h 9+ 5 B
  25745. // v = 1h 9 1 0
  25746. // v = 0h 3 8 7 A
  25747. // u = 0 1 2 3 4 5 6 *a
  25748. // Second island of uv mapping
  25749. // v = 4h 0+ B+ 4+
  25750. // v = 3h A+ 2+
  25751. // v = 2h 7+ 6 3+
  25752. // v = 1h 8+ 3+
  25753. // v = 0h
  25754. // u = 0 1 2 3 4 5 6 *a
  25755. // Face layout on texture UV mapping
  25756. // ============
  25757. // \ 4 /\ 16 / ======
  25758. // \ / \ / /\ 11 /
  25759. // \/ 7 \/ / \ /
  25760. // ======= / 10 \/
  25761. // /\ 17 /\ =======
  25762. // / \ / \ \ 15 /\
  25763. // / 8 \/ 12 \ \ / \
  25764. // ============ \/ 6 \
  25765. // \ 18 /\ ============
  25766. // \ / \ \ 5 /\ 0 /
  25767. // \/ 13 \ \ / \ /
  25768. // ======= \/ 1 \/
  25769. // =============
  25770. // /\ 19 /\ 2 /\
  25771. // / \ / \ / \
  25772. // / 14 \/ 9 \/ 3 \
  25773. // ===================
  25774. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25775. var ustep = 138 / 1024;
  25776. var vstep = 239 / 1024;
  25777. var uoffset = 60 / 1024;
  25778. var voffset = 26 / 1024;
  25779. // Second island should have margin, not to touch the first island
  25780. // avoid any borderline artefact in pixel rounding
  25781. var island_u_offset = -40 / 1024;
  25782. var island_v_offset = +20 / 1024;
  25783. // face is either island 0 or 1 :
  25784. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25785. var island = [
  25786. 0, 0, 0, 0, 1,
  25787. 0, 0, 1, 1, 0,
  25788. 0, 0, 1, 1, 0,
  25789. 0, 1, 1, 1, 0 // 15 - 19
  25790. ];
  25791. var indices = [];
  25792. var positions = [];
  25793. var normals = [];
  25794. var uvs = [];
  25795. var current_indice = 0;
  25796. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25797. var face_vertex_pos = new Array(3);
  25798. var face_vertex_uv = new Array(3);
  25799. var v012;
  25800. for (v012 = 0; v012 < 3; v012++) {
  25801. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25802. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25803. }
  25804. // create all with normals
  25805. for (var face = 0; face < 20; face++) {
  25806. // 3 vertex per face
  25807. for (v012 = 0; v012 < 3; v012++) {
  25808. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25809. var v_id = ico_indices[3 * face + v012];
  25810. // vertex have 3D position (x,y,z)
  25811. 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]);
  25812. // Normalize to get normal, then scale to radius
  25813. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25814. // uv Coordinates from vertex ID
  25815. 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);
  25816. }
  25817. // Subdivide the face (interpolate pos, norm, uv)
  25818. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25819. // - norm is linear interpolation of vertex corner normal
  25820. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25821. // - uv is linear interpolation
  25822. //
  25823. // Topology is as below for sub-divide by 2
  25824. // vertex shown as v0,v1,v2
  25825. // interp index is i1 to progress in range [v0,v1[
  25826. // interp index is i2 to progress in range [v0,v2[
  25827. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25828. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25829. //
  25830. //
  25831. // i2 v2
  25832. // ^ ^
  25833. // / / \
  25834. // / / \
  25835. // / / \
  25836. // / / (0,1) \
  25837. // / #---------\
  25838. // / / \ (0,0)'/ \
  25839. // / / \ / \
  25840. // / / \ / \
  25841. // / / (0,0) \ / (1,0) \
  25842. // / #---------#---------\
  25843. // v0 v1
  25844. //
  25845. // --------------------> i1
  25846. //
  25847. // interp of (i1,i2):
  25848. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25849. // along i1 : lerp(x0,x1, i1/(S-i2))
  25850. //
  25851. // centroid of triangle is needed to get help normal computation
  25852. // (c1,c2) are used for centroid location
  25853. var interp_vertex = function (i1, i2, c1, c2) {
  25854. // vertex is interpolated from
  25855. // - face_vertex_pos[0..2]
  25856. // - face_vertex_uv[0..2]
  25857. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25858. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25859. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25860. pos_interp.normalize();
  25861. var vertex_normal;
  25862. if (flat) {
  25863. // in flat mode, recalculate normal as face centroid normal
  25864. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25865. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25866. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25867. }
  25868. else {
  25869. // in smooth mode, recalculate normal from each single vertex position
  25870. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25871. }
  25872. // Vertex normal need correction due to X,Y,Z radius scaling
  25873. vertex_normal.x /= radiusX;
  25874. vertex_normal.y /= radiusY;
  25875. vertex_normal.z /= radiusZ;
  25876. vertex_normal.normalize();
  25877. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25878. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25879. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25880. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25881. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25882. uvs.push(uv_interp.x, uv_interp.y);
  25883. // push each vertex has member of a face
  25884. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25885. indices.push(current_indice);
  25886. current_indice++;
  25887. };
  25888. for (var i2 = 0; i2 < subdivisions; i2++) {
  25889. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25890. // face : (i1,i2) for /\ :
  25891. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25892. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25893. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25894. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25895. if (i1 + i2 + 1 < subdivisions) {
  25896. // face : (i1,i2)' for \/ :
  25897. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25898. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25899. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25900. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25901. }
  25902. }
  25903. }
  25904. }
  25905. // Sides
  25906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25907. // Result
  25908. var vertexData = new VertexData();
  25909. vertexData.indices = indices;
  25910. vertexData.positions = positions;
  25911. vertexData.normals = normals;
  25912. vertexData.uvs = uvs;
  25913. return vertexData;
  25914. };
  25915. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25916. VertexData.CreatePolyhedron = function (options) {
  25917. // provided polyhedron types :
  25918. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25919. // 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)
  25920. var polyhedra = [];
  25921. 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]] };
  25922. 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]] };
  25923. polyhedra[2] = {
  25924. 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]],
  25925. 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]]
  25926. };
  25927. polyhedra[3] = {
  25928. 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]],
  25929. 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]]
  25930. };
  25931. polyhedra[4] = {
  25932. 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]],
  25933. 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]]
  25934. };
  25935. 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]] };
  25936. 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]] };
  25937. 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]] };
  25938. 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]] };
  25939. 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]] };
  25940. 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]] };
  25941. 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]] };
  25942. 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]] };
  25943. 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]] };
  25944. polyhedra[14] = {
  25945. 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]],
  25946. 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]]
  25947. };
  25948. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25949. var size = options.size;
  25950. var sizeX = options.sizeX || size || 1;
  25951. var sizeY = options.sizeY || size || 1;
  25952. var sizeZ = options.sizeZ || size || 1;
  25953. var data = options.custom || polyhedra[type];
  25954. var nbfaces = data.face.length;
  25955. var faceUV = options.faceUV || new Array(nbfaces);
  25956. var faceColors = options.faceColors;
  25957. var flat = (options.flat === undefined) ? true : options.flat;
  25958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25959. var positions = [];
  25960. var indices = [];
  25961. var normals = [];
  25962. var uvs = [];
  25963. var colors = [];
  25964. var index = 0;
  25965. var faceIdx = 0; // face cursor in the array "indexes"
  25966. var indexes = [];
  25967. var i = 0;
  25968. var f = 0;
  25969. var u, v, ang, x, y, tmp;
  25970. // default face colors and UV if undefined
  25971. if (flat) {
  25972. for (f = 0; f < nbfaces; f++) {
  25973. if (faceColors && faceColors[f] === undefined) {
  25974. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25975. }
  25976. if (faceUV && faceUV[f] === undefined) {
  25977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25978. }
  25979. }
  25980. }
  25981. if (!flat) {
  25982. for (i = 0; i < data.vertex.length; i++) {
  25983. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25984. uvs.push(0, 0);
  25985. }
  25986. for (f = 0; f < nbfaces; f++) {
  25987. for (i = 0; i < data.face[f].length - 2; i++) {
  25988. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25989. }
  25990. }
  25991. }
  25992. else {
  25993. for (f = 0; f < nbfaces; f++) {
  25994. var fl = data.face[f].length; // number of vertices of the current face
  25995. ang = 2 * Math.PI / fl;
  25996. x = 0.5 * Math.tan(ang / 2);
  25997. y = 0.5;
  25998. // positions, uvs, colors
  25999. for (i = 0; i < fl; i++) {
  26000. // positions
  26001. 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);
  26002. indexes.push(index);
  26003. index++;
  26004. // uvs
  26005. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26006. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26007. uvs.push(u, v);
  26008. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26009. y = x * Math.sin(ang) + y * Math.cos(ang);
  26010. x = tmp;
  26011. // colors
  26012. if (faceColors) {
  26013. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26014. }
  26015. }
  26016. // indices from indexes
  26017. for (i = 0; i < fl - 2; i++) {
  26018. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26019. }
  26020. faceIdx += fl;
  26021. }
  26022. }
  26023. VertexData.ComputeNormals(positions, indices, normals);
  26024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26025. var vertexData = new VertexData();
  26026. vertexData.positions = positions;
  26027. vertexData.indices = indices;
  26028. vertexData.normals = normals;
  26029. vertexData.uvs = uvs;
  26030. if (faceColors && flat) {
  26031. vertexData.colors = colors;
  26032. }
  26033. return vertexData;
  26034. };
  26035. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26036. VertexData.CreateTorusKnot = function (options) {
  26037. var indices = [];
  26038. var positions = [];
  26039. var normals = [];
  26040. var uvs = [];
  26041. var radius = options.radius || 2;
  26042. var tube = options.tube || 0.5;
  26043. var radialSegments = options.radialSegments || 32;
  26044. var tubularSegments = options.tubularSegments || 32;
  26045. var p = options.p || 2;
  26046. var q = options.q || 3;
  26047. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26048. // Helper
  26049. var getPos = function (angle) {
  26050. var cu = Math.cos(angle);
  26051. var su = Math.sin(angle);
  26052. var quOverP = q / p * angle;
  26053. var cs = Math.cos(quOverP);
  26054. var tx = radius * (2 + cs) * 0.5 * cu;
  26055. var ty = radius * (2 + cs) * su * 0.5;
  26056. var tz = radius * Math.sin(quOverP) * 0.5;
  26057. return new BABYLON.Vector3(tx, ty, tz);
  26058. };
  26059. // Vertices
  26060. var i;
  26061. var j;
  26062. for (i = 0; i <= radialSegments; i++) {
  26063. var modI = i % radialSegments;
  26064. var u = modI / radialSegments * 2 * p * Math.PI;
  26065. var p1 = getPos(u);
  26066. var p2 = getPos(u + 0.01);
  26067. var tang = p2.subtract(p1);
  26068. var n = p2.add(p1);
  26069. var bitan = BABYLON.Vector3.Cross(tang, n);
  26070. n = BABYLON.Vector3.Cross(bitan, tang);
  26071. bitan.normalize();
  26072. n.normalize();
  26073. for (j = 0; j < tubularSegments; j++) {
  26074. var modJ = j % tubularSegments;
  26075. var v = modJ / tubularSegments * 2 * Math.PI;
  26076. var cx = -tube * Math.cos(v);
  26077. var cy = tube * Math.sin(v);
  26078. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26079. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26080. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26081. uvs.push(i / radialSegments);
  26082. uvs.push(j / tubularSegments);
  26083. }
  26084. }
  26085. for (i = 0; i < radialSegments; i++) {
  26086. for (j = 0; j < tubularSegments; j++) {
  26087. var jNext = (j + 1) % tubularSegments;
  26088. var a = i * tubularSegments + j;
  26089. var b = (i + 1) * tubularSegments + j;
  26090. var c = (i + 1) * tubularSegments + jNext;
  26091. var d = i * tubularSegments + jNext;
  26092. indices.push(d);
  26093. indices.push(b);
  26094. indices.push(a);
  26095. indices.push(d);
  26096. indices.push(c);
  26097. indices.push(b);
  26098. }
  26099. }
  26100. // Normals
  26101. VertexData.ComputeNormals(positions, indices, normals);
  26102. // Sides
  26103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26104. // Result
  26105. var vertexData = new VertexData();
  26106. vertexData.indices = indices;
  26107. vertexData.positions = positions;
  26108. vertexData.normals = normals;
  26109. vertexData.uvs = uvs;
  26110. return vertexData;
  26111. };
  26112. // Tools
  26113. /**
  26114. * @param {any} - positions (number[] or Float32Array)
  26115. * @param {any} - indices (number[] or Uint16Array)
  26116. * @param {any} - normals (number[] or Float32Array)
  26117. */
  26118. VertexData.ComputeNormals = function (positions, indices, normals) {
  26119. var index = 0;
  26120. var p1p2x = 0.0;
  26121. var p1p2y = 0.0;
  26122. var p1p2z = 0.0;
  26123. var p3p2x = 0.0;
  26124. var p3p2y = 0.0;
  26125. var p3p2z = 0.0;
  26126. var faceNormalx = 0.0;
  26127. var faceNormaly = 0.0;
  26128. var faceNormalz = 0.0;
  26129. var length = 0.0;
  26130. var i1 = 0;
  26131. var i2 = 0;
  26132. var i3 = 0;
  26133. for (index = 0; index < positions.length; index++) {
  26134. normals[index] = 0.0;
  26135. }
  26136. // indice triplet = 1 face
  26137. var nbFaces = indices.length / 3;
  26138. for (index = 0; index < nbFaces; index++) {
  26139. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26140. i2 = indices[index * 3 + 1];
  26141. i3 = indices[index * 3 + 2];
  26142. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26143. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26144. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26145. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26146. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26147. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26148. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26149. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26150. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26151. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26152. length = (length === 0) ? 1.0 : length;
  26153. faceNormalx /= length; // normalize this normal
  26154. faceNormaly /= length;
  26155. faceNormalz /= length;
  26156. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26157. normals[i1 * 3 + 1] += faceNormaly;
  26158. normals[i1 * 3 + 2] += faceNormalz;
  26159. normals[i2 * 3] += faceNormalx;
  26160. normals[i2 * 3 + 1] += faceNormaly;
  26161. normals[i2 * 3 + 2] += faceNormalz;
  26162. normals[i3 * 3] += faceNormalx;
  26163. normals[i3 * 3 + 1] += faceNormaly;
  26164. normals[i3 * 3 + 2] += faceNormalz;
  26165. }
  26166. // last normalization of each normal
  26167. for (index = 0; index < normals.length / 3; index++) {
  26168. faceNormalx = normals[index * 3];
  26169. faceNormaly = normals[index * 3 + 1];
  26170. faceNormalz = normals[index * 3 + 2];
  26171. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26172. length = (length === 0) ? 1.0 : length;
  26173. faceNormalx /= length;
  26174. faceNormaly /= length;
  26175. faceNormalz /= length;
  26176. normals[index * 3] = faceNormalx;
  26177. normals[index * 3 + 1] = faceNormaly;
  26178. normals[index * 3 + 2] = faceNormalz;
  26179. }
  26180. };
  26181. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26182. var li = indices.length;
  26183. var ln = normals.length;
  26184. var i;
  26185. var n;
  26186. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26187. switch (sideOrientation) {
  26188. case BABYLON.Mesh.FRONTSIDE:
  26189. // nothing changed
  26190. break;
  26191. case BABYLON.Mesh.BACKSIDE:
  26192. var tmp;
  26193. // indices
  26194. for (i = 0; i < li; i += 3) {
  26195. tmp = indices[i];
  26196. indices[i] = indices[i + 2];
  26197. indices[i + 2] = tmp;
  26198. }
  26199. // normals
  26200. for (n = 0; n < ln; n++) {
  26201. normals[n] = -normals[n];
  26202. }
  26203. break;
  26204. case BABYLON.Mesh.DOUBLESIDE:
  26205. // positions
  26206. var lp = positions.length;
  26207. var l = lp / 3;
  26208. for (var p = 0; p < lp; p++) {
  26209. positions[lp + p] = positions[p];
  26210. }
  26211. // indices
  26212. for (i = 0; i < li; i += 3) {
  26213. indices[i + li] = indices[i + 2] + l;
  26214. indices[i + 1 + li] = indices[i + 1] + l;
  26215. indices[i + 2 + li] = indices[i] + l;
  26216. }
  26217. // normals
  26218. for (n = 0; n < ln; n++) {
  26219. normals[ln + n] = -normals[n];
  26220. }
  26221. // uvs
  26222. var lu = uvs.length;
  26223. for (var u = 0; u < lu; u++) {
  26224. uvs[u + lu] = uvs[u];
  26225. }
  26226. break;
  26227. }
  26228. };
  26229. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26230. var vertexData = new VertexData();
  26231. // positions
  26232. var positions = parsedVertexData.positions;
  26233. if (positions) {
  26234. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26235. }
  26236. // normals
  26237. var normals = parsedVertexData.normals;
  26238. if (normals) {
  26239. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26240. }
  26241. // uvs
  26242. var uvs = parsedVertexData.uvs;
  26243. if (uvs) {
  26244. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26245. }
  26246. // uv2s
  26247. var uv2s = parsedVertexData.uv2s;
  26248. if (uv2s) {
  26249. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26250. }
  26251. // uv3s
  26252. var uv3s = parsedVertexData.uv3s;
  26253. if (uv3s) {
  26254. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26255. }
  26256. // uv4s
  26257. var uv4s = parsedVertexData.uv4s;
  26258. if (uv4s) {
  26259. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26260. }
  26261. // uv5s
  26262. var uv5s = parsedVertexData.uv5s;
  26263. if (uv5s) {
  26264. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26265. }
  26266. // uv6s
  26267. var uv6s = parsedVertexData.uv6s;
  26268. if (uv6s) {
  26269. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26270. }
  26271. // colors
  26272. var colors = parsedVertexData.colors;
  26273. if (colors) {
  26274. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26275. }
  26276. // matricesIndices
  26277. var matricesIndices = parsedVertexData.matricesIndices;
  26278. if (matricesIndices) {
  26279. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26280. }
  26281. // matricesWeights
  26282. var matricesWeights = parsedVertexData.matricesWeights;
  26283. if (matricesWeights) {
  26284. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26285. }
  26286. // indices
  26287. var indices = parsedVertexData.indices;
  26288. if (indices) {
  26289. vertexData.indices = indices;
  26290. }
  26291. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26292. };
  26293. return VertexData;
  26294. })();
  26295. BABYLON.VertexData = VertexData;
  26296. })(BABYLON || (BABYLON = {}));
  26297. var BABYLON;
  26298. (function (BABYLON) {
  26299. var Tags = (function () {
  26300. function Tags() {
  26301. }
  26302. Tags.EnableFor = function (obj) {
  26303. obj._tags = obj._tags || {};
  26304. obj.hasTags = function () {
  26305. return Tags.HasTags(obj);
  26306. };
  26307. obj.addTags = function (tagsString) {
  26308. return Tags.AddTagsTo(obj, tagsString);
  26309. };
  26310. obj.removeTags = function (tagsString) {
  26311. return Tags.RemoveTagsFrom(obj, tagsString);
  26312. };
  26313. obj.matchesTagsQuery = function (tagsQuery) {
  26314. return Tags.MatchesQuery(obj, tagsQuery);
  26315. };
  26316. };
  26317. Tags.DisableFor = function (obj) {
  26318. delete obj._tags;
  26319. delete obj.hasTags;
  26320. delete obj.addTags;
  26321. delete obj.removeTags;
  26322. delete obj.matchesTagsQuery;
  26323. };
  26324. Tags.HasTags = function (obj) {
  26325. if (!obj._tags) {
  26326. return false;
  26327. }
  26328. return !BABYLON.Tools.IsEmpty(obj._tags);
  26329. };
  26330. Tags.GetTags = function (obj, asString) {
  26331. if (asString === void 0) { asString = true; }
  26332. if (!obj._tags) {
  26333. return null;
  26334. }
  26335. if (asString) {
  26336. var tagsArray = [];
  26337. for (var tag in obj._tags) {
  26338. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26339. tagsArray.push(tag);
  26340. }
  26341. }
  26342. return tagsArray.join(" ");
  26343. }
  26344. else {
  26345. return obj._tags;
  26346. }
  26347. };
  26348. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26349. // a tag cannot start with '||', '&&', and '!'
  26350. // it cannot contain whitespaces
  26351. Tags.AddTagsTo = function (obj, tagsString) {
  26352. if (!tagsString) {
  26353. return;
  26354. }
  26355. if (typeof tagsString !== "string") {
  26356. return;
  26357. }
  26358. var tags = tagsString.split(" ");
  26359. for (var t in tags) {
  26360. Tags._AddTagTo(obj, tags[t]);
  26361. }
  26362. };
  26363. Tags._AddTagTo = function (obj, tag) {
  26364. tag = tag.trim();
  26365. if (tag === "" || tag === "true" || tag === "false") {
  26366. return;
  26367. }
  26368. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26369. return;
  26370. }
  26371. Tags.EnableFor(obj);
  26372. obj._tags[tag] = true;
  26373. };
  26374. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26375. if (!Tags.HasTags(obj)) {
  26376. return;
  26377. }
  26378. var tags = tagsString.split(" ");
  26379. for (var t in tags) {
  26380. Tags._RemoveTagFrom(obj, tags[t]);
  26381. }
  26382. };
  26383. Tags._RemoveTagFrom = function (obj, tag) {
  26384. delete obj._tags[tag];
  26385. };
  26386. Tags.MatchesQuery = function (obj, tagsQuery) {
  26387. if (tagsQuery === undefined) {
  26388. return true;
  26389. }
  26390. if (tagsQuery === "") {
  26391. return Tags.HasTags(obj);
  26392. }
  26393. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26394. };
  26395. return Tags;
  26396. })();
  26397. BABYLON.Tags = Tags;
  26398. })(BABYLON || (BABYLON = {}));
  26399. var BABYLON;
  26400. (function (BABYLON) {
  26401. var Internals;
  26402. (function (Internals) {
  26403. var AndOrNotEvaluator = (function () {
  26404. function AndOrNotEvaluator() {
  26405. }
  26406. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26407. if (!query.match(/\([^\(\)]*\)/g)) {
  26408. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26409. }
  26410. else {
  26411. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26412. // remove parenthesis
  26413. r = r.slice(1, r.length - 1);
  26414. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26415. });
  26416. }
  26417. if (query === "true") {
  26418. return true;
  26419. }
  26420. if (query === "false") {
  26421. return false;
  26422. }
  26423. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26424. };
  26425. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26426. evaluateCallback = evaluateCallback || (function (r) {
  26427. return r === "true" ? true : false;
  26428. });
  26429. var result;
  26430. var or = parenthesisContent.split("||");
  26431. for (var i in or) {
  26432. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26433. var and = ori.split("&&");
  26434. if (and.length > 1) {
  26435. for (var j = 0; j < and.length; ++j) {
  26436. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26437. if (andj !== "true" && andj !== "false") {
  26438. if (andj[0] === "!") {
  26439. result = !evaluateCallback(andj.substring(1));
  26440. }
  26441. else {
  26442. result = evaluateCallback(andj);
  26443. }
  26444. }
  26445. else {
  26446. result = andj === "true" ? true : false;
  26447. }
  26448. if (!result) {
  26449. ori = "false";
  26450. break;
  26451. }
  26452. }
  26453. }
  26454. if (result || ori === "true") {
  26455. result = true;
  26456. break;
  26457. }
  26458. // result equals false (or undefined)
  26459. if (ori !== "true" && ori !== "false") {
  26460. if (ori[0] === "!") {
  26461. result = !evaluateCallback(ori.substring(1));
  26462. }
  26463. else {
  26464. result = evaluateCallback(ori);
  26465. }
  26466. }
  26467. else {
  26468. result = ori === "true" ? true : false;
  26469. }
  26470. }
  26471. // the whole parenthesis scope is replaced by 'true' or 'false'
  26472. return result ? "true" : "false";
  26473. };
  26474. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26475. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26476. // remove whitespaces
  26477. r = r.replace(/[\s]/g, function () { return ""; });
  26478. return r.length % 2 ? "!" : "";
  26479. });
  26480. booleanString = booleanString.trim();
  26481. if (booleanString === "!true") {
  26482. booleanString = "false";
  26483. }
  26484. else if (booleanString === "!false") {
  26485. booleanString = "true";
  26486. }
  26487. return booleanString;
  26488. };
  26489. return AndOrNotEvaluator;
  26490. })();
  26491. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26492. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26493. })(BABYLON || (BABYLON = {}));
  26494. var BABYLON;
  26495. (function (BABYLON) {
  26496. var PostProcessRenderPass = (function () {
  26497. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26498. this._enabled = true;
  26499. this._refCount = 0;
  26500. this._name = name;
  26501. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26502. this.setRenderList(renderList);
  26503. this._renderTexture.onBeforeRender = beforeRender;
  26504. this._renderTexture.onAfterRender = afterRender;
  26505. this._scene = scene;
  26506. this._renderList = renderList;
  26507. }
  26508. // private
  26509. PostProcessRenderPass.prototype._incRefCount = function () {
  26510. if (this._refCount === 0) {
  26511. this._scene.customRenderTargets.push(this._renderTexture);
  26512. }
  26513. return ++this._refCount;
  26514. };
  26515. PostProcessRenderPass.prototype._decRefCount = function () {
  26516. this._refCount--;
  26517. if (this._refCount <= 0) {
  26518. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26519. }
  26520. return this._refCount;
  26521. };
  26522. PostProcessRenderPass.prototype._update = function () {
  26523. this.setRenderList(this._renderList);
  26524. };
  26525. // public
  26526. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26527. this._renderTexture.renderList = renderList;
  26528. };
  26529. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26530. return this._renderTexture;
  26531. };
  26532. return PostProcessRenderPass;
  26533. })();
  26534. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26535. })(BABYLON || (BABYLON = {}));
  26536. var BABYLON;
  26537. (function (BABYLON) {
  26538. var PostProcessRenderEffect = (function () {
  26539. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26540. this._engine = engine;
  26541. this._name = name;
  26542. this._singleInstance = singleInstance || true;
  26543. this._getPostProcess = getPostProcess;
  26544. this._cameras = [];
  26545. this._indicesForCamera = [];
  26546. this._postProcesses = {};
  26547. this._renderPasses = {};
  26548. this._renderEffectAsPasses = {};
  26549. }
  26550. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26551. get: function () {
  26552. for (var index in this._postProcesses) {
  26553. if (!this._postProcesses[index].isSupported) {
  26554. return false;
  26555. }
  26556. }
  26557. return true;
  26558. },
  26559. enumerable: true,
  26560. configurable: true
  26561. });
  26562. PostProcessRenderEffect.prototype._update = function () {
  26563. for (var renderPassName in this._renderPasses) {
  26564. this._renderPasses[renderPassName]._update();
  26565. }
  26566. };
  26567. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26568. this._renderPasses[renderPass._name] = renderPass;
  26569. this._linkParameters();
  26570. };
  26571. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26572. delete this._renderPasses[renderPass._name];
  26573. this._linkParameters();
  26574. };
  26575. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26576. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26577. this._linkParameters();
  26578. };
  26579. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26580. for (var renderPassName in this._renderPasses) {
  26581. if (renderPassName === passName) {
  26582. return this._renderPasses[passName];
  26583. }
  26584. }
  26585. };
  26586. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26587. this._renderPasses = {};
  26588. this._linkParameters();
  26589. };
  26590. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26591. var cameraKey;
  26592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26593. for (var i = 0; i < _cam.length; i++) {
  26594. var camera = _cam[i];
  26595. var cameraName = camera.name;
  26596. if (this._singleInstance) {
  26597. cameraKey = 0;
  26598. }
  26599. else {
  26600. cameraKey = cameraName;
  26601. }
  26602. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26603. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26604. if (!this._indicesForCamera[cameraName]) {
  26605. this._indicesForCamera[cameraName] = [];
  26606. }
  26607. this._indicesForCamera[cameraName].push(index);
  26608. if (this._cameras.indexOf(camera) === -1) {
  26609. this._cameras[cameraName] = camera;
  26610. }
  26611. for (var passName in this._renderPasses) {
  26612. this._renderPasses[passName]._incRefCount();
  26613. }
  26614. }
  26615. this._linkParameters();
  26616. };
  26617. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26618. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26619. for (var i = 0; i < _cam.length; i++) {
  26620. var camera = _cam[i];
  26621. var cameraName = camera.name;
  26622. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26623. var index = this._cameras.indexOf(cameraName);
  26624. this._indicesForCamera.splice(index, 1);
  26625. this._cameras.splice(index, 1);
  26626. for (var passName in this._renderPasses) {
  26627. this._renderPasses[passName]._decRefCount();
  26628. }
  26629. }
  26630. };
  26631. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26632. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26633. for (var i = 0; i < _cam.length; i++) {
  26634. var camera = _cam[i];
  26635. var cameraName = camera.name;
  26636. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26637. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26638. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26639. }
  26640. }
  26641. for (var passName in this._renderPasses) {
  26642. this._renderPasses[passName]._incRefCount();
  26643. }
  26644. }
  26645. };
  26646. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26647. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26648. for (var i = 0; i < _cam.length; i++) {
  26649. var camera = _cam[i];
  26650. var cameraName = camera.Name;
  26651. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26652. for (var passName in this._renderPasses) {
  26653. this._renderPasses[passName]._decRefCount();
  26654. }
  26655. }
  26656. };
  26657. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26658. if (this._singleInstance) {
  26659. return this._postProcesses[0];
  26660. }
  26661. else {
  26662. return this._postProcesses[camera.name];
  26663. }
  26664. };
  26665. PostProcessRenderEffect.prototype._linkParameters = function () {
  26666. var _this = this;
  26667. for (var index in this._postProcesses) {
  26668. if (this.applyParameters) {
  26669. this.applyParameters(this._postProcesses[index]);
  26670. }
  26671. this._postProcesses[index].onBeforeRender = function (effect) {
  26672. _this._linkTextures(effect);
  26673. };
  26674. }
  26675. };
  26676. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26677. for (var renderPassName in this._renderPasses) {
  26678. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26679. }
  26680. for (var renderEffectName in this._renderEffectAsPasses) {
  26681. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26682. }
  26683. };
  26684. return PostProcessRenderEffect;
  26685. })();
  26686. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26687. })(BABYLON || (BABYLON = {}));
  26688. var BABYLON;
  26689. (function (BABYLON) {
  26690. var PostProcessRenderPipeline = (function () {
  26691. function PostProcessRenderPipeline(engine, name) {
  26692. this._engine = engine;
  26693. this._name = name;
  26694. this._renderEffects = {};
  26695. this._renderEffectsForIsolatedPass = {};
  26696. this._cameras = [];
  26697. }
  26698. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26699. get: function () {
  26700. for (var renderEffectName in this._renderEffects) {
  26701. if (!this._renderEffects[renderEffectName].isSupported) {
  26702. return false;
  26703. }
  26704. }
  26705. return true;
  26706. },
  26707. enumerable: true,
  26708. configurable: true
  26709. });
  26710. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26711. this._renderEffects[renderEffect._name] = renderEffect;
  26712. };
  26713. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26714. var renderEffects = this._renderEffects[renderEffectName];
  26715. if (!renderEffects) {
  26716. return;
  26717. }
  26718. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26719. };
  26720. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26721. var renderEffects = this._renderEffects[renderEffectName];
  26722. if (!renderEffects) {
  26723. return;
  26724. }
  26725. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26726. };
  26727. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26728. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26729. var indicesToDelete = [];
  26730. var i;
  26731. for (i = 0; i < _cam.length; i++) {
  26732. var camera = _cam[i];
  26733. var cameraName = camera.name;
  26734. if (this._cameras.indexOf(camera) === -1) {
  26735. this._cameras[cameraName] = camera;
  26736. }
  26737. else if (unique) {
  26738. indicesToDelete.push(i);
  26739. }
  26740. }
  26741. for (i = 0; i < indicesToDelete.length; i++) {
  26742. cameras.splice(indicesToDelete[i], 1);
  26743. }
  26744. for (var renderEffectName in this._renderEffects) {
  26745. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26746. }
  26747. };
  26748. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26749. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26750. for (var renderEffectName in this._renderEffects) {
  26751. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26752. }
  26753. for (var i = 0; i < _cam.length; i++) {
  26754. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26755. }
  26756. };
  26757. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26758. var _this = this;
  26759. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26760. var pass = null;
  26761. var renderEffectName;
  26762. for (renderEffectName in this._renderEffects) {
  26763. pass = this._renderEffects[renderEffectName].getPass(passName);
  26764. if (pass != null) {
  26765. break;
  26766. }
  26767. }
  26768. if (pass === null) {
  26769. return;
  26770. }
  26771. for (renderEffectName in this._renderEffects) {
  26772. this._renderEffects[renderEffectName]._disable(_cam);
  26773. }
  26774. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26775. for (var i = 0; i < _cam.length; i++) {
  26776. var camera = _cam[i];
  26777. var cameraName = camera.name;
  26778. 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); });
  26779. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26780. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26781. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26782. }
  26783. };
  26784. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26785. var _this = this;
  26786. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26787. for (var i = 0; i < _cam.length; i++) {
  26788. var camera = _cam[i];
  26789. var cameraName = camera.name;
  26790. 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); });
  26791. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26792. }
  26793. for (var renderEffectName in this._renderEffects) {
  26794. this._renderEffects[renderEffectName]._enable(_cam);
  26795. }
  26796. };
  26797. PostProcessRenderPipeline.prototype._update = function () {
  26798. for (var renderEffectName in this._renderEffects) {
  26799. this._renderEffects[renderEffectName]._update();
  26800. }
  26801. for (var i = 0; i < this._cameras.length; i++) {
  26802. var cameraName = this._cameras[i].name;
  26803. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26804. this._renderEffectsForIsolatedPass[cameraName]._update();
  26805. }
  26806. }
  26807. };
  26808. PostProcessRenderPipeline.prototype.dispose = function () {
  26809. // Must be implemented by children
  26810. };
  26811. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26812. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26813. return PostProcessRenderPipeline;
  26814. })();
  26815. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26816. })(BABYLON || (BABYLON = {}));
  26817. var BABYLON;
  26818. (function (BABYLON) {
  26819. var PostProcessRenderPipelineManager = (function () {
  26820. function PostProcessRenderPipelineManager() {
  26821. this._renderPipelines = {};
  26822. }
  26823. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26824. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26825. };
  26826. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26827. var renderPipeline = this._renderPipelines[renderPipelineName];
  26828. if (!renderPipeline) {
  26829. return;
  26830. }
  26831. renderPipeline._attachCameras(cameras, unique);
  26832. };
  26833. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26834. var renderPipeline = this._renderPipelines[renderPipelineName];
  26835. if (!renderPipeline) {
  26836. return;
  26837. }
  26838. renderPipeline._detachCameras(cameras);
  26839. };
  26840. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26841. var renderPipeline = this._renderPipelines[renderPipelineName];
  26842. if (!renderPipeline) {
  26843. return;
  26844. }
  26845. renderPipeline._enableEffect(renderEffectName, cameras);
  26846. };
  26847. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26848. var renderPipeline = this._renderPipelines[renderPipelineName];
  26849. if (!renderPipeline) {
  26850. return;
  26851. }
  26852. renderPipeline._disableEffect(renderEffectName, cameras);
  26853. };
  26854. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26855. var renderPipeline = this._renderPipelines[renderPipelineName];
  26856. if (!renderPipeline) {
  26857. return;
  26858. }
  26859. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26860. };
  26861. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26862. var renderPipeline = this._renderPipelines[renderPipelineName];
  26863. if (!renderPipeline) {
  26864. return;
  26865. }
  26866. renderPipeline._disableDisplayOnlyPass(cameras);
  26867. };
  26868. PostProcessRenderPipelineManager.prototype.update = function () {
  26869. for (var renderPipelineName in this._renderPipelines) {
  26870. var pipeline = this._renderPipelines[renderPipelineName];
  26871. if (!pipeline.isSupported) {
  26872. pipeline.dispose();
  26873. delete this._renderPipelines[renderPipelineName];
  26874. }
  26875. else {
  26876. pipeline._update();
  26877. }
  26878. }
  26879. };
  26880. return PostProcessRenderPipelineManager;
  26881. })();
  26882. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26883. })(BABYLON || (BABYLON = {}));
  26884. var BABYLON;
  26885. (function (BABYLON) {
  26886. var BoundingBoxRenderer = (function () {
  26887. function BoundingBoxRenderer(scene) {
  26888. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26889. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26890. this.showBackLines = true;
  26891. this.renderList = new BABYLON.SmartArray(32);
  26892. this._scene = scene;
  26893. }
  26894. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26895. if (this._colorShader) {
  26896. return;
  26897. }
  26898. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26899. attributes: ["position"],
  26900. uniforms: ["worldViewProjection", "color"]
  26901. });
  26902. var engine = this._scene.getEngine();
  26903. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26904. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26905. 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]);
  26906. };
  26907. BoundingBoxRenderer.prototype.reset = function () {
  26908. this.renderList.reset();
  26909. };
  26910. BoundingBoxRenderer.prototype.render = function () {
  26911. if (this.renderList.length === 0) {
  26912. return;
  26913. }
  26914. this._prepareRessources();
  26915. if (!this._colorShader.isReady()) {
  26916. return;
  26917. }
  26918. var engine = this._scene.getEngine();
  26919. engine.setDepthWrite(false);
  26920. this._colorShader._preBind();
  26921. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26922. var boundingBox = this.renderList.data[boundingBoxIndex];
  26923. var min = boundingBox.minimum;
  26924. var max = boundingBox.maximum;
  26925. var diff = max.subtract(min);
  26926. var median = min.add(diff.scale(0.5));
  26927. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26928. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26929. .multiply(boundingBox.getWorldMatrix());
  26930. // VBOs
  26931. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26932. if (this.showBackLines) {
  26933. // Back
  26934. engine.setDepthFunctionToGreaterOrEqual();
  26935. this._scene.resetCachedMaterial();
  26936. this._colorShader.setColor4("color", this.backColor.toColor4());
  26937. this._colorShader.bind(worldMatrix);
  26938. // Draw order
  26939. engine.draw(false, 0, 24);
  26940. }
  26941. // Front
  26942. engine.setDepthFunctionToLess();
  26943. this._scene.resetCachedMaterial();
  26944. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26945. this._colorShader.bind(worldMatrix);
  26946. // Draw order
  26947. engine.draw(false, 0, 24);
  26948. }
  26949. this._colorShader.unbind();
  26950. engine.setDepthFunctionToLessOrEqual();
  26951. engine.setDepthWrite(true);
  26952. };
  26953. BoundingBoxRenderer.prototype.dispose = function () {
  26954. if (!this._colorShader) {
  26955. return;
  26956. }
  26957. this._colorShader.dispose();
  26958. this._vb.dispose();
  26959. this._scene.getEngine()._releaseBuffer(this._ib);
  26960. };
  26961. return BoundingBoxRenderer;
  26962. })();
  26963. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26964. })(BABYLON || (BABYLON = {}));
  26965. var BABYLON;
  26966. (function (BABYLON) {
  26967. var Condition = (function () {
  26968. function Condition(actionManager) {
  26969. this._actionManager = actionManager;
  26970. }
  26971. Condition.prototype.isValid = function () {
  26972. return true;
  26973. };
  26974. Condition.prototype._getProperty = function (propertyPath) {
  26975. return this._actionManager._getProperty(propertyPath);
  26976. };
  26977. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26978. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26979. };
  26980. return Condition;
  26981. })();
  26982. BABYLON.Condition = Condition;
  26983. var ValueCondition = (function (_super) {
  26984. __extends(ValueCondition, _super);
  26985. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26986. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26987. _super.call(this, actionManager);
  26988. this.propertyPath = propertyPath;
  26989. this.value = value;
  26990. this.operator = operator;
  26991. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26992. this._property = this._getProperty(this.propertyPath);
  26993. }
  26994. Object.defineProperty(ValueCondition, "IsEqual", {
  26995. get: function () {
  26996. return ValueCondition._IsEqual;
  26997. },
  26998. enumerable: true,
  26999. configurable: true
  27000. });
  27001. Object.defineProperty(ValueCondition, "IsDifferent", {
  27002. get: function () {
  27003. return ValueCondition._IsDifferent;
  27004. },
  27005. enumerable: true,
  27006. configurable: true
  27007. });
  27008. Object.defineProperty(ValueCondition, "IsGreater", {
  27009. get: function () {
  27010. return ValueCondition._IsGreater;
  27011. },
  27012. enumerable: true,
  27013. configurable: true
  27014. });
  27015. Object.defineProperty(ValueCondition, "IsLesser", {
  27016. get: function () {
  27017. return ValueCondition._IsLesser;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. // Methods
  27023. ValueCondition.prototype.isValid = function () {
  27024. switch (this.operator) {
  27025. case ValueCondition.IsGreater:
  27026. return this._target[this._property] > this.value;
  27027. case ValueCondition.IsLesser:
  27028. return this._target[this._property] < this.value;
  27029. case ValueCondition.IsEqual:
  27030. case ValueCondition.IsDifferent:
  27031. var check;
  27032. if (this.value.equals) {
  27033. check = this.value.equals(this._target[this._property]);
  27034. }
  27035. else {
  27036. check = this.value === this._target[this._property];
  27037. }
  27038. return this.operator === ValueCondition.IsEqual ? check : !check;
  27039. }
  27040. return false;
  27041. };
  27042. // Statics
  27043. ValueCondition._IsEqual = 0;
  27044. ValueCondition._IsDifferent = 1;
  27045. ValueCondition._IsGreater = 2;
  27046. ValueCondition._IsLesser = 3;
  27047. return ValueCondition;
  27048. })(Condition);
  27049. BABYLON.ValueCondition = ValueCondition;
  27050. var PredicateCondition = (function (_super) {
  27051. __extends(PredicateCondition, _super);
  27052. function PredicateCondition(actionManager, predicate) {
  27053. _super.call(this, actionManager);
  27054. this.predicate = predicate;
  27055. }
  27056. PredicateCondition.prototype.isValid = function () {
  27057. return this.predicate();
  27058. };
  27059. return PredicateCondition;
  27060. })(Condition);
  27061. BABYLON.PredicateCondition = PredicateCondition;
  27062. var StateCondition = (function (_super) {
  27063. __extends(StateCondition, _super);
  27064. function StateCondition(actionManager, target, value) {
  27065. _super.call(this, actionManager);
  27066. this.value = value;
  27067. this._target = target;
  27068. }
  27069. // Methods
  27070. StateCondition.prototype.isValid = function () {
  27071. return this._target.state === this.value;
  27072. };
  27073. return StateCondition;
  27074. })(Condition);
  27075. BABYLON.StateCondition = StateCondition;
  27076. })(BABYLON || (BABYLON = {}));
  27077. var BABYLON;
  27078. (function (BABYLON) {
  27079. var Action = (function () {
  27080. function Action(triggerOptions, condition) {
  27081. this.triggerOptions = triggerOptions;
  27082. if (triggerOptions.parameter) {
  27083. this.trigger = triggerOptions.trigger;
  27084. this._triggerParameter = triggerOptions.parameter;
  27085. }
  27086. else {
  27087. this.trigger = triggerOptions;
  27088. }
  27089. this._nextActiveAction = this;
  27090. this._condition = condition;
  27091. }
  27092. // Methods
  27093. Action.prototype._prepare = function () {
  27094. };
  27095. Action.prototype.getTriggerParameter = function () {
  27096. return this._triggerParameter;
  27097. };
  27098. Action.prototype._executeCurrent = function (evt) {
  27099. if (this._nextActiveAction._condition) {
  27100. var condition = this._nextActiveAction._condition;
  27101. var currentRenderId = this._actionManager.getScene().getRenderId();
  27102. // We cache the current evaluation for the current frame
  27103. if (condition._evaluationId === currentRenderId) {
  27104. if (!condition._currentResult) {
  27105. return;
  27106. }
  27107. }
  27108. else {
  27109. condition._evaluationId = currentRenderId;
  27110. if (!condition.isValid()) {
  27111. condition._currentResult = false;
  27112. return;
  27113. }
  27114. condition._currentResult = true;
  27115. }
  27116. }
  27117. this._nextActiveAction.execute(evt);
  27118. this.skipToNextActiveAction();
  27119. };
  27120. Action.prototype.execute = function (evt) {
  27121. };
  27122. Action.prototype.skipToNextActiveAction = function () {
  27123. if (this._nextActiveAction._child) {
  27124. if (!this._nextActiveAction._child._actionManager) {
  27125. this._nextActiveAction._child._actionManager = this._actionManager;
  27126. }
  27127. this._nextActiveAction = this._nextActiveAction._child;
  27128. }
  27129. else {
  27130. this._nextActiveAction = this;
  27131. }
  27132. };
  27133. Action.prototype.then = function (action) {
  27134. this._child = action;
  27135. action._actionManager = this._actionManager;
  27136. action._prepare();
  27137. return action;
  27138. };
  27139. Action.prototype._getProperty = function (propertyPath) {
  27140. return this._actionManager._getProperty(propertyPath);
  27141. };
  27142. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27143. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27144. };
  27145. return Action;
  27146. })();
  27147. BABYLON.Action = Action;
  27148. })(BABYLON || (BABYLON = {}));
  27149. var BABYLON;
  27150. (function (BABYLON) {
  27151. /**
  27152. * ActionEvent is the event beint sent when an action is triggered.
  27153. */
  27154. var ActionEvent = (function () {
  27155. /**
  27156. * @constructor
  27157. * @param source The mesh or sprite that triggered the action.
  27158. * @param pointerX The X mouse cursor position at the time of the event
  27159. * @param pointerY The Y mouse cursor position at the time of the event
  27160. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27161. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27162. */
  27163. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27164. this.source = source;
  27165. this.pointerX = pointerX;
  27166. this.pointerY = pointerY;
  27167. this.meshUnderPointer = meshUnderPointer;
  27168. this.sourceEvent = sourceEvent;
  27169. this.additionalData = additionalData;
  27170. }
  27171. /**
  27172. * Helper function to auto-create an ActionEvent from a source mesh.
  27173. * @param source The source mesh that triggered the event
  27174. * @param evt {Event} The original (browser) event
  27175. */
  27176. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27177. var scene = source.getScene();
  27178. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27179. };
  27180. /**
  27181. * Helper function to auto-create an ActionEvent from a source mesh.
  27182. * @param source The source sprite that triggered the event
  27183. * @param scene Scene associated with the sprite
  27184. * @param evt {Event} The original (browser) event
  27185. */
  27186. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27187. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27188. };
  27189. /**
  27190. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27191. * @param scene the scene where the event occurred
  27192. * @param evt {Event} The original (browser) event
  27193. */
  27194. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27195. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27196. };
  27197. return ActionEvent;
  27198. })();
  27199. BABYLON.ActionEvent = ActionEvent;
  27200. /**
  27201. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27202. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27203. */
  27204. var ActionManager = (function () {
  27205. function ActionManager(scene) {
  27206. // Members
  27207. this.actions = new Array();
  27208. this._scene = scene;
  27209. scene._actionManagers.push(this);
  27210. }
  27211. Object.defineProperty(ActionManager, "NothingTrigger", {
  27212. get: function () {
  27213. return ActionManager._NothingTrigger;
  27214. },
  27215. enumerable: true,
  27216. configurable: true
  27217. });
  27218. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27219. get: function () {
  27220. return ActionManager._OnPickTrigger;
  27221. },
  27222. enumerable: true,
  27223. configurable: true
  27224. });
  27225. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27226. get: function () {
  27227. return ActionManager._OnLeftPickTrigger;
  27228. },
  27229. enumerable: true,
  27230. configurable: true
  27231. });
  27232. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27233. get: function () {
  27234. return ActionManager._OnRightPickTrigger;
  27235. },
  27236. enumerable: true,
  27237. configurable: true
  27238. });
  27239. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27240. get: function () {
  27241. return ActionManager._OnCenterPickTrigger;
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27247. get: function () {
  27248. return ActionManager._OnPickDownTrigger;
  27249. },
  27250. enumerable: true,
  27251. configurable: true
  27252. });
  27253. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27254. get: function () {
  27255. return ActionManager._OnPickUpTrigger;
  27256. },
  27257. enumerable: true,
  27258. configurable: true
  27259. });
  27260. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27261. /// This trigger will only be raised if you also declared a OnPickDown
  27262. get: function () {
  27263. return ActionManager._OnPickOutTrigger;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27269. get: function () {
  27270. return ActionManager._OnLongPressTrigger;
  27271. },
  27272. enumerable: true,
  27273. configurable: true
  27274. });
  27275. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27276. get: function () {
  27277. return ActionManager._OnPointerOverTrigger;
  27278. },
  27279. enumerable: true,
  27280. configurable: true
  27281. });
  27282. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27283. get: function () {
  27284. return ActionManager._OnPointerOutTrigger;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27290. get: function () {
  27291. return ActionManager._OnEveryFrameTrigger;
  27292. },
  27293. enumerable: true,
  27294. configurable: true
  27295. });
  27296. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27297. get: function () {
  27298. return ActionManager._OnIntersectionEnterTrigger;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27304. get: function () {
  27305. return ActionManager._OnIntersectionExitTrigger;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27311. get: function () {
  27312. return ActionManager._OnKeyDownTrigger;
  27313. },
  27314. enumerable: true,
  27315. configurable: true
  27316. });
  27317. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27318. get: function () {
  27319. return ActionManager._OnKeyUpTrigger;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. // Methods
  27325. ActionManager.prototype.dispose = function () {
  27326. var index = this._scene._actionManagers.indexOf(this);
  27327. if (index > -1) {
  27328. this._scene._actionManagers.splice(index, 1);
  27329. }
  27330. };
  27331. ActionManager.prototype.getScene = function () {
  27332. return this._scene;
  27333. };
  27334. /**
  27335. * Does this action manager handles actions of any of the given triggers
  27336. * @param {number[]} triggers - the triggers to be tested
  27337. * @return {boolean} whether one (or more) of the triggers is handeled
  27338. */
  27339. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27340. for (var index = 0; index < this.actions.length; index++) {
  27341. var action = this.actions[index];
  27342. if (triggers.indexOf(action.trigger) > -1) {
  27343. return true;
  27344. }
  27345. }
  27346. return false;
  27347. };
  27348. /**
  27349. * Does this action manager handles actions of a given trigger
  27350. * @param {number} trigger - the trigger to be tested
  27351. * @return {boolean} whether the trigger is handeled
  27352. */
  27353. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27354. for (var index = 0; index < this.actions.length; index++) {
  27355. var action = this.actions[index];
  27356. if (action.trigger === trigger) {
  27357. return true;
  27358. }
  27359. }
  27360. return false;
  27361. };
  27362. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27363. /**
  27364. * Does this action manager has pointer triggers
  27365. * @return {boolean} whether or not it has pointer triggers
  27366. */
  27367. get: function () {
  27368. for (var index = 0; index < this.actions.length; index++) {
  27369. var action = this.actions[index];
  27370. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27371. return true;
  27372. }
  27373. }
  27374. return false;
  27375. },
  27376. enumerable: true,
  27377. configurable: true
  27378. });
  27379. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27380. /**
  27381. * Does this action manager has pick triggers
  27382. * @return {boolean} whether or not it has pick triggers
  27383. */
  27384. get: function () {
  27385. for (var index = 0; index < this.actions.length; index++) {
  27386. var action = this.actions[index];
  27387. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27388. return true;
  27389. }
  27390. }
  27391. return false;
  27392. },
  27393. enumerable: true,
  27394. configurable: true
  27395. });
  27396. /**
  27397. * Registers an action to this action manager
  27398. * @param {BABYLON.Action} action - the action to be registered
  27399. * @return {BABYLON.Action} the action amended (prepared) after registration
  27400. */
  27401. ActionManager.prototype.registerAction = function (action) {
  27402. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27403. if (this.getScene().actionManager !== this) {
  27404. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27405. return null;
  27406. }
  27407. }
  27408. this.actions.push(action);
  27409. action._actionManager = this;
  27410. action._prepare();
  27411. return action;
  27412. };
  27413. /**
  27414. * Process a specific trigger
  27415. * @param {number} trigger - the trigger to process
  27416. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27417. */
  27418. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27419. for (var index = 0; index < this.actions.length; index++) {
  27420. var action = this.actions[index];
  27421. if (action.trigger === trigger) {
  27422. if (trigger === ActionManager.OnKeyUpTrigger
  27423. || trigger === ActionManager.OnKeyDownTrigger) {
  27424. var parameter = action.getTriggerParameter();
  27425. if (parameter) {
  27426. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27427. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27428. if (actualkey !== parameter.toLowerCase()) {
  27429. continue;
  27430. }
  27431. }
  27432. }
  27433. action._executeCurrent(evt);
  27434. }
  27435. }
  27436. };
  27437. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27438. var properties = propertyPath.split(".");
  27439. for (var index = 0; index < properties.length - 1; index++) {
  27440. target = target[properties[index]];
  27441. }
  27442. return target;
  27443. };
  27444. ActionManager.prototype._getProperty = function (propertyPath) {
  27445. var properties = propertyPath.split(".");
  27446. return properties[properties.length - 1];
  27447. };
  27448. ActionManager.Parse = function (parsedActions, object, scene) {
  27449. var actionManager = new BABYLON.ActionManager(scene);
  27450. if (object === null)
  27451. scene.actionManager = actionManager;
  27452. else
  27453. object.actionManager = actionManager;
  27454. // instanciate a new object
  27455. var instanciate = function (name, params) {
  27456. var newInstance = Object.create(BABYLON[name].prototype);
  27457. newInstance.constructor.apply(newInstance, params);
  27458. return newInstance;
  27459. };
  27460. var parseParameter = function (name, value, target, propertyPath) {
  27461. if (propertyPath === null) {
  27462. // String, boolean or float
  27463. var floatValue = parseFloat(value);
  27464. if (value === "true" || value === "false")
  27465. return value === "true";
  27466. else
  27467. return isNaN(floatValue) ? value : floatValue;
  27468. }
  27469. var effectiveTarget = propertyPath.split(".");
  27470. var values = value.split(",");
  27471. // Get effective Target
  27472. for (var i = 0; i < effectiveTarget.length; i++) {
  27473. target = target[effectiveTarget[i]];
  27474. }
  27475. // Return appropriate value with its type
  27476. if (typeof (target) === "boolean")
  27477. return values[0] === "true";
  27478. if (typeof (target) === "string")
  27479. return values[0];
  27480. // Parameters with multiple values such as Vector3 etc.
  27481. var split = new Array();
  27482. for (var i = 0; i < values.length; i++)
  27483. split.push(parseFloat(values[i]));
  27484. if (target instanceof BABYLON.Vector3)
  27485. return BABYLON.Vector3.FromArray(split);
  27486. if (target instanceof BABYLON.Vector4)
  27487. return BABYLON.Vector4.FromArray(split);
  27488. if (target instanceof BABYLON.Color3)
  27489. return BABYLON.Color3.FromArray(split);
  27490. if (target instanceof BABYLON.Color4)
  27491. return BABYLON.Color4.FromArray(split);
  27492. return parseFloat(values[0]);
  27493. };
  27494. // traverse graph per trigger
  27495. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27496. if (combineArray === void 0) { combineArray = null; }
  27497. if (parsedAction.detached)
  27498. return;
  27499. var parameters = new Array();
  27500. var target = null;
  27501. var propertyPath = null;
  27502. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27503. // Parameters
  27504. if (parsedAction.type === 2)
  27505. parameters.push(actionManager);
  27506. else
  27507. parameters.push(trigger);
  27508. if (combine) {
  27509. var actions = new Array();
  27510. for (var j = 0; j < parsedAction.combine.length; j++) {
  27511. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27512. }
  27513. parameters.push(actions);
  27514. }
  27515. else {
  27516. for (var i = 0; i < parsedAction.properties.length; i++) {
  27517. var value = parsedAction.properties[i].value;
  27518. var name = parsedAction.properties[i].name;
  27519. var targetType = parsedAction.properties[i].targetType;
  27520. if (name === "target")
  27521. if (targetType !== null && targetType === "SceneProperties")
  27522. value = target = scene;
  27523. else
  27524. value = target = scene.getNodeByName(value);
  27525. else if (name === "parent")
  27526. value = scene.getNodeByName(value);
  27527. else if (name === "sound")
  27528. value = scene.getSoundByName(value);
  27529. else if (name !== "propertyPath") {
  27530. if (parsedAction.type === 2 && name === "operator")
  27531. value = BABYLON.ValueCondition[value];
  27532. else
  27533. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27534. }
  27535. else {
  27536. propertyPath = value;
  27537. }
  27538. parameters.push(value);
  27539. }
  27540. }
  27541. if (combineArray === null) {
  27542. parameters.push(condition);
  27543. }
  27544. else {
  27545. parameters.push(null);
  27546. }
  27547. // If interpolate value action
  27548. if (parsedAction.name === "InterpolateValueAction") {
  27549. var param = parameters[parameters.length - 2];
  27550. parameters[parameters.length - 1] = param;
  27551. parameters[parameters.length - 2] = condition;
  27552. }
  27553. // Action or condition(s) and not CombineAction
  27554. var newAction = instanciate(parsedAction.name, parameters);
  27555. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27556. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27557. if (action)
  27558. action.then(nothing);
  27559. else
  27560. actionManager.registerAction(nothing);
  27561. action = nothing;
  27562. }
  27563. if (combineArray === null) {
  27564. if (newAction instanceof BABYLON.Condition) {
  27565. condition = newAction;
  27566. newAction = action;
  27567. }
  27568. else {
  27569. condition = null;
  27570. if (action)
  27571. action.then(newAction);
  27572. else
  27573. actionManager.registerAction(newAction);
  27574. }
  27575. }
  27576. else {
  27577. combineArray.push(newAction);
  27578. }
  27579. for (var i = 0; i < parsedAction.children.length; i++)
  27580. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27581. };
  27582. // triggers
  27583. for (var i = 0; i < parsedActions.children.length; i++) {
  27584. var triggerParams;
  27585. var trigger = parsedActions.children[i];
  27586. if (trigger.properties.length > 0) {
  27587. var param = trigger.properties[0].value;
  27588. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27589. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27590. }
  27591. else
  27592. triggerParams = BABYLON.ActionManager[trigger.name];
  27593. for (var j = 0; j < trigger.children.length; j++) {
  27594. if (!trigger.detached)
  27595. traverse(trigger.children[j], triggerParams, null, null);
  27596. }
  27597. }
  27598. };
  27599. // Statics
  27600. ActionManager._NothingTrigger = 0;
  27601. ActionManager._OnPickTrigger = 1;
  27602. ActionManager._OnLeftPickTrigger = 2;
  27603. ActionManager._OnRightPickTrigger = 3;
  27604. ActionManager._OnCenterPickTrigger = 4;
  27605. ActionManager._OnPickDownTrigger = 5;
  27606. ActionManager._OnPickUpTrigger = 6;
  27607. ActionManager._OnLongPressTrigger = 7;
  27608. ActionManager._OnPointerOverTrigger = 8;
  27609. ActionManager._OnPointerOutTrigger = 9;
  27610. ActionManager._OnEveryFrameTrigger = 10;
  27611. ActionManager._OnIntersectionEnterTrigger = 11;
  27612. ActionManager._OnIntersectionExitTrigger = 12;
  27613. ActionManager._OnKeyDownTrigger = 13;
  27614. ActionManager._OnKeyUpTrigger = 14;
  27615. ActionManager._OnPickOutTrigger = 15;
  27616. ActionManager.DragMovementThreshold = 10; // in pixels
  27617. ActionManager.LongPressDelay = 500; // in milliseconds
  27618. return ActionManager;
  27619. })();
  27620. BABYLON.ActionManager = ActionManager;
  27621. })(BABYLON || (BABYLON = {}));
  27622. var BABYLON;
  27623. (function (BABYLON) {
  27624. var InterpolateValueAction = (function (_super) {
  27625. __extends(InterpolateValueAction, _super);
  27626. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27627. if (duration === void 0) { duration = 1000; }
  27628. _super.call(this, triggerOptions, condition);
  27629. this.propertyPath = propertyPath;
  27630. this.value = value;
  27631. this.duration = duration;
  27632. this.stopOtherAnimations = stopOtherAnimations;
  27633. this.onInterpolationDone = onInterpolationDone;
  27634. this._target = target;
  27635. }
  27636. InterpolateValueAction.prototype._prepare = function () {
  27637. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27638. this._property = this._getProperty(this.propertyPath);
  27639. };
  27640. InterpolateValueAction.prototype.execute = function () {
  27641. var scene = this._actionManager.getScene();
  27642. var keys = [
  27643. {
  27644. frame: 0,
  27645. value: this._target[this._property]
  27646. }, {
  27647. frame: 100,
  27648. value: this.value
  27649. }
  27650. ];
  27651. var dataType;
  27652. if (typeof this.value === "number") {
  27653. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27654. }
  27655. else if (this.value instanceof BABYLON.Color3) {
  27656. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27657. }
  27658. else if (this.value instanceof BABYLON.Vector3) {
  27659. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27660. }
  27661. else if (this.value instanceof BABYLON.Matrix) {
  27662. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27663. }
  27664. else if (this.value instanceof BABYLON.Quaternion) {
  27665. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27666. }
  27667. else {
  27668. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27669. return;
  27670. }
  27671. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27672. animation.setKeys(keys);
  27673. if (this.stopOtherAnimations) {
  27674. scene.stopAnimation(this._target);
  27675. }
  27676. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27677. };
  27678. return InterpolateValueAction;
  27679. })(BABYLON.Action);
  27680. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27681. })(BABYLON || (BABYLON = {}));
  27682. var BABYLON;
  27683. (function (BABYLON) {
  27684. var SwitchBooleanAction = (function (_super) {
  27685. __extends(SwitchBooleanAction, _super);
  27686. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27687. _super.call(this, triggerOptions, condition);
  27688. this.propertyPath = propertyPath;
  27689. this._target = target;
  27690. }
  27691. SwitchBooleanAction.prototype._prepare = function () {
  27692. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27693. this._property = this._getProperty(this.propertyPath);
  27694. };
  27695. SwitchBooleanAction.prototype.execute = function () {
  27696. this._target[this._property] = !this._target[this._property];
  27697. };
  27698. return SwitchBooleanAction;
  27699. })(BABYLON.Action);
  27700. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27701. var SetStateAction = (function (_super) {
  27702. __extends(SetStateAction, _super);
  27703. function SetStateAction(triggerOptions, target, value, condition) {
  27704. _super.call(this, triggerOptions, condition);
  27705. this.value = value;
  27706. this._target = target;
  27707. }
  27708. SetStateAction.prototype.execute = function () {
  27709. this._target.state = this.value;
  27710. };
  27711. return SetStateAction;
  27712. })(BABYLON.Action);
  27713. BABYLON.SetStateAction = SetStateAction;
  27714. var SetValueAction = (function (_super) {
  27715. __extends(SetValueAction, _super);
  27716. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27717. _super.call(this, triggerOptions, condition);
  27718. this.propertyPath = propertyPath;
  27719. this.value = value;
  27720. this._target = target;
  27721. }
  27722. SetValueAction.prototype._prepare = function () {
  27723. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27724. this._property = this._getProperty(this.propertyPath);
  27725. };
  27726. SetValueAction.prototype.execute = function () {
  27727. this._target[this._property] = this.value;
  27728. };
  27729. return SetValueAction;
  27730. })(BABYLON.Action);
  27731. BABYLON.SetValueAction = SetValueAction;
  27732. var IncrementValueAction = (function (_super) {
  27733. __extends(IncrementValueAction, _super);
  27734. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27735. _super.call(this, triggerOptions, condition);
  27736. this.propertyPath = propertyPath;
  27737. this.value = value;
  27738. this._target = target;
  27739. }
  27740. IncrementValueAction.prototype._prepare = function () {
  27741. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27742. this._property = this._getProperty(this.propertyPath);
  27743. if (typeof this._target[this._property] !== "number") {
  27744. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27745. }
  27746. };
  27747. IncrementValueAction.prototype.execute = function () {
  27748. this._target[this._property] += this.value;
  27749. };
  27750. return IncrementValueAction;
  27751. })(BABYLON.Action);
  27752. BABYLON.IncrementValueAction = IncrementValueAction;
  27753. var PlayAnimationAction = (function (_super) {
  27754. __extends(PlayAnimationAction, _super);
  27755. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27756. _super.call(this, triggerOptions, condition);
  27757. this.from = from;
  27758. this.to = to;
  27759. this.loop = loop;
  27760. this._target = target;
  27761. }
  27762. PlayAnimationAction.prototype._prepare = function () {
  27763. };
  27764. PlayAnimationAction.prototype.execute = function () {
  27765. var scene = this._actionManager.getScene();
  27766. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27767. };
  27768. return PlayAnimationAction;
  27769. })(BABYLON.Action);
  27770. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27771. var StopAnimationAction = (function (_super) {
  27772. __extends(StopAnimationAction, _super);
  27773. function StopAnimationAction(triggerOptions, target, condition) {
  27774. _super.call(this, triggerOptions, condition);
  27775. this._target = target;
  27776. }
  27777. StopAnimationAction.prototype._prepare = function () {
  27778. };
  27779. StopAnimationAction.prototype.execute = function () {
  27780. var scene = this._actionManager.getScene();
  27781. scene.stopAnimation(this._target);
  27782. };
  27783. return StopAnimationAction;
  27784. })(BABYLON.Action);
  27785. BABYLON.StopAnimationAction = StopAnimationAction;
  27786. var DoNothingAction = (function (_super) {
  27787. __extends(DoNothingAction, _super);
  27788. function DoNothingAction(triggerOptions, condition) {
  27789. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27790. _super.call(this, triggerOptions, condition);
  27791. }
  27792. DoNothingAction.prototype.execute = function () {
  27793. };
  27794. return DoNothingAction;
  27795. })(BABYLON.Action);
  27796. BABYLON.DoNothingAction = DoNothingAction;
  27797. var CombineAction = (function (_super) {
  27798. __extends(CombineAction, _super);
  27799. function CombineAction(triggerOptions, children, condition) {
  27800. _super.call(this, triggerOptions, condition);
  27801. this.children = children;
  27802. }
  27803. CombineAction.prototype._prepare = function () {
  27804. for (var index = 0; index < this.children.length; index++) {
  27805. this.children[index]._actionManager = this._actionManager;
  27806. this.children[index]._prepare();
  27807. }
  27808. };
  27809. CombineAction.prototype.execute = function (evt) {
  27810. for (var index = 0; index < this.children.length; index++) {
  27811. this.children[index].execute(evt);
  27812. }
  27813. };
  27814. return CombineAction;
  27815. })(BABYLON.Action);
  27816. BABYLON.CombineAction = CombineAction;
  27817. var ExecuteCodeAction = (function (_super) {
  27818. __extends(ExecuteCodeAction, _super);
  27819. function ExecuteCodeAction(triggerOptions, func, condition) {
  27820. _super.call(this, triggerOptions, condition);
  27821. this.func = func;
  27822. }
  27823. ExecuteCodeAction.prototype.execute = function (evt) {
  27824. this.func(evt);
  27825. };
  27826. return ExecuteCodeAction;
  27827. })(BABYLON.Action);
  27828. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27829. var SetParentAction = (function (_super) {
  27830. __extends(SetParentAction, _super);
  27831. function SetParentAction(triggerOptions, target, parent, condition) {
  27832. _super.call(this, triggerOptions, condition);
  27833. this._target = target;
  27834. this._parent = parent;
  27835. }
  27836. SetParentAction.prototype._prepare = function () {
  27837. };
  27838. SetParentAction.prototype.execute = function () {
  27839. if (this._target.parent === this._parent) {
  27840. return;
  27841. }
  27842. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27843. invertParentWorldMatrix.invert();
  27844. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27845. this._target.parent = this._parent;
  27846. };
  27847. return SetParentAction;
  27848. })(BABYLON.Action);
  27849. BABYLON.SetParentAction = SetParentAction;
  27850. var PlaySoundAction = (function (_super) {
  27851. __extends(PlaySoundAction, _super);
  27852. function PlaySoundAction(triggerOptions, sound, condition) {
  27853. _super.call(this, triggerOptions, condition);
  27854. this._sound = sound;
  27855. }
  27856. PlaySoundAction.prototype._prepare = function () {
  27857. };
  27858. PlaySoundAction.prototype.execute = function () {
  27859. if (this._sound !== undefined)
  27860. this._sound.play();
  27861. };
  27862. return PlaySoundAction;
  27863. })(BABYLON.Action);
  27864. BABYLON.PlaySoundAction = PlaySoundAction;
  27865. var StopSoundAction = (function (_super) {
  27866. __extends(StopSoundAction, _super);
  27867. function StopSoundAction(triggerOptions, sound, condition) {
  27868. _super.call(this, triggerOptions, condition);
  27869. this._sound = sound;
  27870. }
  27871. StopSoundAction.prototype._prepare = function () {
  27872. };
  27873. StopSoundAction.prototype.execute = function () {
  27874. if (this._sound !== undefined)
  27875. this._sound.stop();
  27876. };
  27877. return StopSoundAction;
  27878. })(BABYLON.Action);
  27879. BABYLON.StopSoundAction = StopSoundAction;
  27880. })(BABYLON || (BABYLON = {}));
  27881. var BABYLON;
  27882. (function (BABYLON) {
  27883. var Geometry = (function () {
  27884. function Geometry(id, scene, vertexData, updatable, mesh) {
  27885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27886. this._totalVertices = 0;
  27887. this._isDisposed = false;
  27888. this.id = id;
  27889. this._engine = scene.getEngine();
  27890. this._meshes = [];
  27891. this._scene = scene;
  27892. //Init vertex buffer cache
  27893. this._vertexBuffers = {};
  27894. this._indices = [];
  27895. // vertexData
  27896. if (vertexData) {
  27897. this.setAllVerticesData(vertexData, updatable);
  27898. }
  27899. else {
  27900. this._totalVertices = 0;
  27901. this._indices = [];
  27902. }
  27903. // applyToMesh
  27904. if (mesh) {
  27905. this.applyToMesh(mesh);
  27906. mesh.computeWorldMatrix(true);
  27907. }
  27908. }
  27909. Object.defineProperty(Geometry.prototype, "extend", {
  27910. get: function () {
  27911. return this._extend;
  27912. },
  27913. enumerable: true,
  27914. configurable: true
  27915. });
  27916. Geometry.prototype.getScene = function () {
  27917. return this._scene;
  27918. };
  27919. Geometry.prototype.getEngine = function () {
  27920. return this._engine;
  27921. };
  27922. Geometry.prototype.isReady = function () {
  27923. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27924. };
  27925. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27926. vertexData.applyToGeometry(this, updatable);
  27927. this.notifyUpdate();
  27928. };
  27929. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27930. if (this._vertexBuffers[kind]) {
  27931. this._vertexBuffers[kind].dispose();
  27932. }
  27933. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27934. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27935. stride = this._vertexBuffers[kind].getStrideSize();
  27936. this._totalVertices = data.length / stride;
  27937. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27938. var meshes = this._meshes;
  27939. var numOfMeshes = meshes.length;
  27940. for (var index = 0; index < numOfMeshes; index++) {
  27941. var mesh = meshes[index];
  27942. mesh._resetPointsArrayCache();
  27943. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27944. mesh._createGlobalSubMesh();
  27945. mesh.computeWorldMatrix(true);
  27946. }
  27947. }
  27948. this.notifyUpdate(kind);
  27949. };
  27950. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27951. var vertexBuffer = this.getVertexBuffer(kind);
  27952. if (!vertexBuffer) {
  27953. return;
  27954. }
  27955. vertexBuffer.updateDirectly(data, offset);
  27956. this.notifyUpdate(kind);
  27957. };
  27958. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27959. var vertexBuffer = this.getVertexBuffer(kind);
  27960. if (!vertexBuffer) {
  27961. return;
  27962. }
  27963. vertexBuffer.update(data);
  27964. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27965. var stride = vertexBuffer.getStrideSize();
  27966. this._totalVertices = data.length / stride;
  27967. if (updateExtends) {
  27968. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27969. }
  27970. var meshes = this._meshes;
  27971. var numOfMeshes = meshes.length;
  27972. for (var index = 0; index < numOfMeshes; index++) {
  27973. var mesh = meshes[index];
  27974. mesh._resetPointsArrayCache();
  27975. if (updateExtends) {
  27976. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27977. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27978. var subMesh = mesh.subMeshes[subIndex];
  27979. subMesh.refreshBoundingInfo();
  27980. }
  27981. }
  27982. }
  27983. }
  27984. this.notifyUpdate(kind);
  27985. };
  27986. Geometry.prototype.getTotalVertices = function () {
  27987. if (!this.isReady()) {
  27988. return 0;
  27989. }
  27990. return this._totalVertices;
  27991. };
  27992. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27993. var vertexBuffer = this.getVertexBuffer(kind);
  27994. if (!vertexBuffer) {
  27995. return null;
  27996. }
  27997. var orig = vertexBuffer.getData();
  27998. if (!copyWhenShared || this._meshes.length === 1) {
  27999. return orig;
  28000. }
  28001. else {
  28002. var len = orig.length;
  28003. var copy = [];
  28004. for (var i = 0; i < len; i++) {
  28005. copy.push(orig[i]);
  28006. }
  28007. return copy;
  28008. }
  28009. };
  28010. Geometry.prototype.getVertexBuffer = function (kind) {
  28011. if (!this.isReady()) {
  28012. return null;
  28013. }
  28014. return this._vertexBuffers[kind];
  28015. };
  28016. Geometry.prototype.getVertexBuffers = function () {
  28017. if (!this.isReady()) {
  28018. return null;
  28019. }
  28020. return this._vertexBuffers;
  28021. };
  28022. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28023. if (!this._vertexBuffers) {
  28024. if (this._delayInfo) {
  28025. return this._delayInfo.indexOf(kind) !== -1;
  28026. }
  28027. return false;
  28028. }
  28029. return this._vertexBuffers[kind] !== undefined;
  28030. };
  28031. Geometry.prototype.getVerticesDataKinds = function () {
  28032. var result = [];
  28033. var kind;
  28034. if (!this._vertexBuffers && this._delayInfo) {
  28035. for (kind in this._delayInfo) {
  28036. result.push(kind);
  28037. }
  28038. }
  28039. else {
  28040. for (kind in this._vertexBuffers) {
  28041. result.push(kind);
  28042. }
  28043. }
  28044. return result;
  28045. };
  28046. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28047. if (this._indexBuffer) {
  28048. this._engine._releaseBuffer(this._indexBuffer);
  28049. }
  28050. this._indices = indices;
  28051. if (this._meshes.length !== 0 && this._indices) {
  28052. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28053. }
  28054. if (totalVertices !== undefined) {
  28055. this._totalVertices = totalVertices;
  28056. }
  28057. var meshes = this._meshes;
  28058. var numOfMeshes = meshes.length;
  28059. for (var index = 0; index < numOfMeshes; index++) {
  28060. meshes[index]._createGlobalSubMesh();
  28061. }
  28062. this.notifyUpdate();
  28063. };
  28064. Geometry.prototype.getTotalIndices = function () {
  28065. if (!this.isReady()) {
  28066. return 0;
  28067. }
  28068. return this._indices.length;
  28069. };
  28070. Geometry.prototype.getIndices = function (copyWhenShared) {
  28071. if (!this.isReady()) {
  28072. return null;
  28073. }
  28074. var orig = this._indices;
  28075. if (!copyWhenShared || this._meshes.length === 1) {
  28076. return orig;
  28077. }
  28078. else {
  28079. var len = orig.length;
  28080. var copy = [];
  28081. for (var i = 0; i < len; i++) {
  28082. copy.push(orig[i]);
  28083. }
  28084. return copy;
  28085. }
  28086. };
  28087. Geometry.prototype.getIndexBuffer = function () {
  28088. if (!this.isReady()) {
  28089. return null;
  28090. }
  28091. return this._indexBuffer;
  28092. };
  28093. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28094. var meshes = this._meshes;
  28095. var index = meshes.indexOf(mesh);
  28096. if (index === -1) {
  28097. return;
  28098. }
  28099. for (var kind in this._vertexBuffers) {
  28100. this._vertexBuffers[kind].dispose();
  28101. }
  28102. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28103. this._indexBuffer = null;
  28104. }
  28105. meshes.splice(index, 1);
  28106. mesh._geometry = null;
  28107. if (meshes.length === 0 && shouldDispose) {
  28108. this.dispose();
  28109. }
  28110. };
  28111. Geometry.prototype.applyToMesh = function (mesh) {
  28112. if (mesh._geometry === this) {
  28113. return;
  28114. }
  28115. var previousGeometry = mesh._geometry;
  28116. if (previousGeometry) {
  28117. previousGeometry.releaseForMesh(mesh);
  28118. }
  28119. var meshes = this._meshes;
  28120. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28121. mesh._geometry = this;
  28122. this._scene.pushGeometry(this);
  28123. meshes.push(mesh);
  28124. if (this.isReady()) {
  28125. this._applyToMesh(mesh);
  28126. }
  28127. else {
  28128. mesh._boundingInfo = this._boundingInfo;
  28129. }
  28130. };
  28131. Geometry.prototype._applyToMesh = function (mesh) {
  28132. var numOfMeshes = this._meshes.length;
  28133. // vertexBuffers
  28134. for (var kind in this._vertexBuffers) {
  28135. if (numOfMeshes === 1) {
  28136. this._vertexBuffers[kind].create();
  28137. }
  28138. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28139. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28140. mesh._resetPointsArrayCache();
  28141. if (!this._extend) {
  28142. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28143. }
  28144. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28145. mesh._createGlobalSubMesh();
  28146. //bounding info was just created again, world matrix should be applied again.
  28147. mesh._updateBoundingInfo();
  28148. }
  28149. }
  28150. // indexBuffer
  28151. if (numOfMeshes === 1 && this._indices) {
  28152. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28153. }
  28154. if (this._indexBuffer) {
  28155. this._indexBuffer.references = numOfMeshes;
  28156. }
  28157. };
  28158. Geometry.prototype.notifyUpdate = function (kind) {
  28159. if (this.onGeometryUpdated) {
  28160. this.onGeometryUpdated(this, kind);
  28161. }
  28162. };
  28163. Geometry.prototype.load = function (scene, onLoaded) {
  28164. var _this = this;
  28165. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28166. return;
  28167. }
  28168. if (this.isReady()) {
  28169. if (onLoaded) {
  28170. onLoaded();
  28171. }
  28172. return;
  28173. }
  28174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28175. scene._addPendingData(this);
  28176. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28177. _this._delayLoadingFunction(JSON.parse(data), _this);
  28178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28179. _this._delayInfo = [];
  28180. scene._removePendingData(_this);
  28181. var meshes = _this._meshes;
  28182. var numOfMeshes = meshes.length;
  28183. for (var index = 0; index < numOfMeshes; index++) {
  28184. _this._applyToMesh(meshes[index]);
  28185. }
  28186. if (onLoaded) {
  28187. onLoaded();
  28188. }
  28189. }, function () { }, scene.database);
  28190. };
  28191. Geometry.prototype.isDisposed = function () {
  28192. return this._isDisposed;
  28193. };
  28194. Geometry.prototype.dispose = function () {
  28195. var meshes = this._meshes;
  28196. var numOfMeshes = meshes.length;
  28197. var index;
  28198. for (index = 0; index < numOfMeshes; index++) {
  28199. this.releaseForMesh(meshes[index]);
  28200. }
  28201. this._meshes = [];
  28202. for (var kind in this._vertexBuffers) {
  28203. this._vertexBuffers[kind].dispose();
  28204. }
  28205. this._vertexBuffers = [];
  28206. this._totalVertices = 0;
  28207. if (this._indexBuffer) {
  28208. this._engine._releaseBuffer(this._indexBuffer);
  28209. }
  28210. this._indexBuffer = null;
  28211. this._indices = [];
  28212. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28213. this.delayLoadingFile = null;
  28214. this._delayLoadingFunction = null;
  28215. this._delayInfo = [];
  28216. this._boundingInfo = null;
  28217. this._scene.removeGeometry(this);
  28218. this._isDisposed = true;
  28219. };
  28220. Geometry.prototype.copy = function (id) {
  28221. var vertexData = new BABYLON.VertexData();
  28222. vertexData.indices = [];
  28223. var indices = this.getIndices();
  28224. for (var index = 0; index < indices.length; index++) {
  28225. vertexData.indices.push(indices[index]);
  28226. }
  28227. var updatable = false;
  28228. var stopChecking = false;
  28229. var kind;
  28230. for (kind in this._vertexBuffers) {
  28231. // using slice() to make a copy of the array and not just reference it
  28232. var data = this.getVerticesData(kind);
  28233. if (data instanceof Float32Array) {
  28234. vertexData.set(new Float32Array(data), kind);
  28235. }
  28236. else {
  28237. vertexData.set(data.slice(0), kind);
  28238. }
  28239. if (!stopChecking) {
  28240. updatable = this.getVertexBuffer(kind).isUpdatable();
  28241. stopChecking = !updatable;
  28242. }
  28243. }
  28244. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28245. geometry.delayLoadState = this.delayLoadState;
  28246. geometry.delayLoadingFile = this.delayLoadingFile;
  28247. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28248. for (kind in this._delayInfo) {
  28249. geometry._delayInfo = geometry._delayInfo || [];
  28250. geometry._delayInfo.push(kind);
  28251. }
  28252. // Bounding info
  28253. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28254. return geometry;
  28255. };
  28256. Geometry.prototype.serialize = function () {
  28257. var serializationObject = {};
  28258. serializationObject.id = this.id;
  28259. if (BABYLON.Tags.HasTags(this)) {
  28260. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28261. }
  28262. return serializationObject;
  28263. };
  28264. Geometry.prototype.serializeVerticeData = function () {
  28265. var serializationObject = this.serialize();
  28266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28267. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28268. }
  28269. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28270. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28271. }
  28272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28273. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28274. }
  28275. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28276. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28277. }
  28278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28279. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28280. }
  28281. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28282. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28283. }
  28284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28285. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28286. }
  28287. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28288. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28289. }
  28290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28291. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28292. }
  28293. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28294. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28295. serializationObject.matricesIndices._isExpanded = true;
  28296. }
  28297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28298. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28299. }
  28300. serializationObject.indices = this.getIndices();
  28301. return serializationObject;
  28302. };
  28303. // Statics
  28304. Geometry.ExtractFromMesh = function (mesh, id) {
  28305. var geometry = mesh._geometry;
  28306. if (!geometry) {
  28307. return null;
  28308. }
  28309. return geometry.copy(id);
  28310. };
  28311. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28312. // be aware Math.random() could cause collisions
  28313. Geometry.RandomId = function () {
  28314. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28315. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28316. return v.toString(16);
  28317. });
  28318. };
  28319. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28320. var scene = mesh.getScene();
  28321. // Geometry
  28322. var geometryId = parsedGeometry.geometryId;
  28323. if (geometryId) {
  28324. var geometry = scene.getGeometryByID(geometryId);
  28325. if (geometry) {
  28326. geometry.applyToMesh(mesh);
  28327. }
  28328. }
  28329. else if (parsedGeometry instanceof ArrayBuffer) {
  28330. var binaryInfo = mesh._binaryInfo;
  28331. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28332. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28333. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28334. }
  28335. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28336. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28337. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28338. }
  28339. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28340. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28341. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28342. }
  28343. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28344. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28345. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28346. }
  28347. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28348. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28349. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28350. }
  28351. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28352. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28353. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28354. }
  28355. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28356. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28357. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28358. }
  28359. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28360. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28361. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28362. }
  28363. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28364. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28365. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28366. }
  28367. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28368. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28369. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28370. }
  28371. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28372. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28373. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28374. }
  28375. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28376. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28377. mesh.setIndices(indicesData);
  28378. }
  28379. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28380. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28381. mesh.subMeshes = [];
  28382. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28383. var materialIndex = subMeshesData[(i * 5) + 0];
  28384. var verticesStart = subMeshesData[(i * 5) + 1];
  28385. var verticesCount = subMeshesData[(i * 5) + 2];
  28386. var indexStart = subMeshesData[(i * 5) + 3];
  28387. var indexCount = subMeshesData[(i * 5) + 4];
  28388. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28389. }
  28390. }
  28391. }
  28392. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28393. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28394. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28395. if (parsedGeometry.uvs) {
  28396. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28397. }
  28398. if (parsedGeometry.uvs2) {
  28399. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28400. }
  28401. if (parsedGeometry.uvs3) {
  28402. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28403. }
  28404. if (parsedGeometry.uvs4) {
  28405. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28406. }
  28407. if (parsedGeometry.uvs5) {
  28408. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28409. }
  28410. if (parsedGeometry.uvs6) {
  28411. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28412. }
  28413. if (parsedGeometry.colors) {
  28414. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28415. }
  28416. if (parsedGeometry.matricesIndices) {
  28417. if (!parsedGeometry.matricesIndices._isExpanded) {
  28418. var floatIndices = [];
  28419. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28420. var matricesIndex = parsedGeometry.matricesIndices[i];
  28421. floatIndices.push(matricesIndex & 0x000000FF);
  28422. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28423. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28424. floatIndices.push(matricesIndex >> 24);
  28425. }
  28426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28427. }
  28428. else {
  28429. delete parsedGeometry.matricesIndices._isExpanded;
  28430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28431. }
  28432. }
  28433. if (parsedGeometry.matricesIndicesExtra) {
  28434. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28435. var floatIndices = [];
  28436. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28437. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28438. floatIndices.push(matricesIndex & 0x000000FF);
  28439. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28440. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28441. floatIndices.push(matricesIndex >> 24);
  28442. }
  28443. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28444. }
  28445. else {
  28446. delete parsedGeometry.matricesIndices._isExpanded;
  28447. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28448. }
  28449. }
  28450. if (parsedGeometry.matricesWeights) {
  28451. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28452. }
  28453. if (parsedGeometry.matricesWeightsExtra) {
  28454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28455. }
  28456. mesh.setIndices(parsedGeometry.indices);
  28457. }
  28458. // SubMeshes
  28459. if (parsedGeometry.subMeshes) {
  28460. mesh.subMeshes = [];
  28461. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28462. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28463. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28464. }
  28465. }
  28466. // Flat shading
  28467. if (mesh._shouldGenerateFlatShading) {
  28468. mesh.convertToFlatShadedMesh();
  28469. delete mesh._shouldGenerateFlatShading;
  28470. }
  28471. // Update
  28472. mesh.computeWorldMatrix(true);
  28473. // Octree
  28474. if (scene['_selectionOctree']) {
  28475. scene['_selectionOctree'].addMesh(mesh);
  28476. }
  28477. };
  28478. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28479. if (scene.getGeometryByID(parsedVertexData.id)) {
  28480. return null; // null since geometry could be something else than a box...
  28481. }
  28482. var geometry = new Geometry(parsedVertexData.id, scene);
  28483. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28484. if (parsedVertexData.delayLoadingFile) {
  28485. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28486. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28487. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28488. geometry._delayInfo = [];
  28489. if (parsedVertexData.hasUVs) {
  28490. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28491. }
  28492. if (parsedVertexData.hasUVs2) {
  28493. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28494. }
  28495. if (parsedVertexData.hasUVs3) {
  28496. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28497. }
  28498. if (parsedVertexData.hasUVs4) {
  28499. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28500. }
  28501. if (parsedVertexData.hasUVs5) {
  28502. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28503. }
  28504. if (parsedVertexData.hasUVs6) {
  28505. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28506. }
  28507. if (parsedVertexData.hasColors) {
  28508. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28509. }
  28510. if (parsedVertexData.hasMatricesIndices) {
  28511. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28512. }
  28513. if (parsedVertexData.hasMatricesWeights) {
  28514. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28515. }
  28516. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28517. }
  28518. else {
  28519. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28520. }
  28521. scene.pushGeometry(geometry, true);
  28522. return geometry;
  28523. };
  28524. return Geometry;
  28525. })();
  28526. BABYLON.Geometry = Geometry;
  28527. /////// Primitives //////////////////////////////////////////////
  28528. var Geometry;
  28529. (function (Geometry) {
  28530. var Primitives;
  28531. (function (Primitives) {
  28532. /// Abstract class
  28533. var _Primitive = (function (_super) {
  28534. __extends(_Primitive, _super);
  28535. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28536. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28537. this._canBeRegenerated = _canBeRegenerated;
  28538. this._beingRegenerated = true;
  28539. this.regenerate();
  28540. this._beingRegenerated = false;
  28541. }
  28542. _Primitive.prototype.canBeRegenerated = function () {
  28543. return this._canBeRegenerated;
  28544. };
  28545. _Primitive.prototype.regenerate = function () {
  28546. if (!this._canBeRegenerated) {
  28547. return;
  28548. }
  28549. this._beingRegenerated = true;
  28550. this.setAllVerticesData(this._regenerateVertexData(), false);
  28551. this._beingRegenerated = false;
  28552. };
  28553. _Primitive.prototype.asNewGeometry = function (id) {
  28554. return _super.prototype.copy.call(this, id);
  28555. };
  28556. // overrides
  28557. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28558. if (!this._beingRegenerated) {
  28559. return;
  28560. }
  28561. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28562. };
  28563. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28564. if (!this._beingRegenerated) {
  28565. return;
  28566. }
  28567. _super.prototype.setVerticesData.call(this, kind, data, false);
  28568. };
  28569. // to override
  28570. // protected
  28571. _Primitive.prototype._regenerateVertexData = function () {
  28572. throw new Error("Abstract method");
  28573. };
  28574. _Primitive.prototype.copy = function (id) {
  28575. throw new Error("Must be overriden in sub-classes.");
  28576. };
  28577. _Primitive.prototype.serialize = function () {
  28578. var serializationObject = _super.prototype.serialize.call(this);
  28579. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28580. return serializationObject;
  28581. };
  28582. return _Primitive;
  28583. })(Geometry);
  28584. Primitives._Primitive = _Primitive;
  28585. var Ribbon = (function (_super) {
  28586. __extends(Ribbon, _super);
  28587. // Members
  28588. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28589. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28590. _super.call(this, id, scene, canBeRegenerated, mesh);
  28591. this.pathArray = pathArray;
  28592. this.closeArray = closeArray;
  28593. this.closePath = closePath;
  28594. this.offset = offset;
  28595. this.side = side;
  28596. }
  28597. Ribbon.prototype._regenerateVertexData = function () {
  28598. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28599. };
  28600. Ribbon.prototype.copy = function (id) {
  28601. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28602. };
  28603. return Ribbon;
  28604. })(_Primitive);
  28605. Primitives.Ribbon = Ribbon;
  28606. var Box = (function (_super) {
  28607. __extends(Box, _super);
  28608. // Members
  28609. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28610. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28611. _super.call(this, id, scene, canBeRegenerated, mesh);
  28612. this.size = size;
  28613. this.side = side;
  28614. }
  28615. Box.prototype._regenerateVertexData = function () {
  28616. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28617. };
  28618. Box.prototype.copy = function (id) {
  28619. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28620. };
  28621. Box.prototype.serialize = function () {
  28622. var serializationObject = _super.prototype.serialize.call(this);
  28623. serializationObject.size = this.size;
  28624. return serializationObject;
  28625. };
  28626. Box.Parse = function (parsedBox, scene) {
  28627. if (scene.getGeometryByID(parsedBox.id)) {
  28628. return null; // null since geometry could be something else than a box...
  28629. }
  28630. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28631. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28632. scene.pushGeometry(box, true);
  28633. return box;
  28634. };
  28635. return Box;
  28636. })(_Primitive);
  28637. Primitives.Box = Box;
  28638. var Sphere = (function (_super) {
  28639. __extends(Sphere, _super);
  28640. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28641. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28642. _super.call(this, id, scene, canBeRegenerated, mesh);
  28643. this.segments = segments;
  28644. this.diameter = diameter;
  28645. this.side = side;
  28646. }
  28647. Sphere.prototype._regenerateVertexData = function () {
  28648. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28649. };
  28650. Sphere.prototype.copy = function (id) {
  28651. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28652. };
  28653. Sphere.prototype.serialize = function () {
  28654. var serializationObject = _super.prototype.serialize.call(this);
  28655. serializationObject.segments = this.segments;
  28656. serializationObject.diameter = this.diameter;
  28657. return serializationObject;
  28658. };
  28659. Sphere.Parse = function (parsedSphere, scene) {
  28660. if (scene.getGeometryByID(parsedSphere.id)) {
  28661. return null; // null since geometry could be something else than a sphere...
  28662. }
  28663. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28664. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28665. scene.pushGeometry(sphere, true);
  28666. return sphere;
  28667. };
  28668. return Sphere;
  28669. })(_Primitive);
  28670. Primitives.Sphere = Sphere;
  28671. var Disc = (function (_super) {
  28672. __extends(Disc, _super);
  28673. // Members
  28674. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28675. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28676. _super.call(this, id, scene, canBeRegenerated, mesh);
  28677. this.radius = radius;
  28678. this.tessellation = tessellation;
  28679. this.side = side;
  28680. }
  28681. Disc.prototype._regenerateVertexData = function () {
  28682. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28683. };
  28684. Disc.prototype.copy = function (id) {
  28685. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28686. };
  28687. return Disc;
  28688. })(_Primitive);
  28689. Primitives.Disc = Disc;
  28690. var Cylinder = (function (_super) {
  28691. __extends(Cylinder, _super);
  28692. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28693. if (subdivisions === void 0) { subdivisions = 1; }
  28694. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28695. _super.call(this, id, scene, canBeRegenerated, mesh);
  28696. this.height = height;
  28697. this.diameterTop = diameterTop;
  28698. this.diameterBottom = diameterBottom;
  28699. this.tessellation = tessellation;
  28700. this.subdivisions = subdivisions;
  28701. this.side = side;
  28702. }
  28703. Cylinder.prototype._regenerateVertexData = function () {
  28704. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28705. };
  28706. Cylinder.prototype.copy = function (id) {
  28707. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28708. };
  28709. Cylinder.prototype.serialize = function () {
  28710. var serializationObject = _super.prototype.serialize.call(this);
  28711. serializationObject.height = this.height;
  28712. serializationObject.diameterTop = this.diameterTop;
  28713. serializationObject.diameterBottom = this.diameterBottom;
  28714. serializationObject.tessellation = this.tessellation;
  28715. return serializationObject;
  28716. };
  28717. Cylinder.Parse = function (parsedCylinder, scene) {
  28718. if (scene.getGeometryByID(parsedCylinder.id)) {
  28719. return null; // null since geometry could be something else than a cylinder...
  28720. }
  28721. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28722. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28723. scene.pushGeometry(cylinder, true);
  28724. return cylinder;
  28725. };
  28726. return Cylinder;
  28727. })(_Primitive);
  28728. Primitives.Cylinder = Cylinder;
  28729. var Torus = (function (_super) {
  28730. __extends(Torus, _super);
  28731. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28732. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28733. _super.call(this, id, scene, canBeRegenerated, mesh);
  28734. this.diameter = diameter;
  28735. this.thickness = thickness;
  28736. this.tessellation = tessellation;
  28737. this.side = side;
  28738. }
  28739. Torus.prototype._regenerateVertexData = function () {
  28740. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28741. };
  28742. Torus.prototype.copy = function (id) {
  28743. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28744. };
  28745. Torus.prototype.serialize = function () {
  28746. var serializationObject = _super.prototype.serialize.call(this);
  28747. serializationObject.diameter = this.diameter;
  28748. serializationObject.thickness = this.thickness;
  28749. serializationObject.tessellation = this.tessellation;
  28750. return serializationObject;
  28751. };
  28752. Torus.Parse = function (parsedTorus, scene) {
  28753. if (scene.getGeometryByID(parsedTorus.id)) {
  28754. return null; // null since geometry could be something else than a torus...
  28755. }
  28756. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28757. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28758. scene.pushGeometry(torus, true);
  28759. return torus;
  28760. };
  28761. return Torus;
  28762. })(_Primitive);
  28763. Primitives.Torus = Torus;
  28764. var Ground = (function (_super) {
  28765. __extends(Ground, _super);
  28766. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28767. _super.call(this, id, scene, canBeRegenerated, mesh);
  28768. this.width = width;
  28769. this.height = height;
  28770. this.subdivisions = subdivisions;
  28771. }
  28772. Ground.prototype._regenerateVertexData = function () {
  28773. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28774. };
  28775. Ground.prototype.copy = function (id) {
  28776. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28777. };
  28778. Ground.prototype.serialize = function () {
  28779. var serializationObject = _super.prototype.serialize.call(this);
  28780. serializationObject.width = this.width;
  28781. serializationObject.height = this.height;
  28782. serializationObject.subdivisions = this.subdivisions;
  28783. return serializationObject;
  28784. };
  28785. Ground.Parse = function (parsedGround, scene) {
  28786. if (scene.getGeometryByID(parsedGround.id)) {
  28787. return null; // null since geometry could be something else than a ground...
  28788. }
  28789. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28790. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28791. scene.pushGeometry(ground, true);
  28792. return ground;
  28793. };
  28794. return Ground;
  28795. })(_Primitive);
  28796. Primitives.Ground = Ground;
  28797. var TiledGround = (function (_super) {
  28798. __extends(TiledGround, _super);
  28799. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28800. _super.call(this, id, scene, canBeRegenerated, mesh);
  28801. this.xmin = xmin;
  28802. this.zmin = zmin;
  28803. this.xmax = xmax;
  28804. this.zmax = zmax;
  28805. this.subdivisions = subdivisions;
  28806. this.precision = precision;
  28807. }
  28808. TiledGround.prototype._regenerateVertexData = function () {
  28809. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28810. };
  28811. TiledGround.prototype.copy = function (id) {
  28812. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28813. };
  28814. return TiledGround;
  28815. })(_Primitive);
  28816. Primitives.TiledGround = TiledGround;
  28817. var Plane = (function (_super) {
  28818. __extends(Plane, _super);
  28819. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28821. _super.call(this, id, scene, canBeRegenerated, mesh);
  28822. this.size = size;
  28823. this.side = side;
  28824. }
  28825. Plane.prototype._regenerateVertexData = function () {
  28826. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28827. };
  28828. Plane.prototype.copy = function (id) {
  28829. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28830. };
  28831. Plane.prototype.serialize = function () {
  28832. var serializationObject = _super.prototype.serialize.call(this);
  28833. serializationObject.size = this.size;
  28834. return serializationObject;
  28835. };
  28836. Plane.Parse = function (parsedPlane, scene) {
  28837. if (scene.getGeometryByID(parsedPlane.id)) {
  28838. return null; // null since geometry could be something else than a ground...
  28839. }
  28840. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28841. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28842. scene.pushGeometry(plane, true);
  28843. return plane;
  28844. };
  28845. return Plane;
  28846. })(_Primitive);
  28847. Primitives.Plane = Plane;
  28848. var TorusKnot = (function (_super) {
  28849. __extends(TorusKnot, _super);
  28850. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28851. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28852. _super.call(this, id, scene, canBeRegenerated, mesh);
  28853. this.radius = radius;
  28854. this.tube = tube;
  28855. this.radialSegments = radialSegments;
  28856. this.tubularSegments = tubularSegments;
  28857. this.p = p;
  28858. this.q = q;
  28859. this.side = side;
  28860. }
  28861. TorusKnot.prototype._regenerateVertexData = function () {
  28862. 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 });
  28863. };
  28864. TorusKnot.prototype.copy = function (id) {
  28865. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28866. };
  28867. TorusKnot.prototype.serialize = function () {
  28868. var serializationObject = _super.prototype.serialize.call(this);
  28869. serializationObject.radius = this.radius;
  28870. serializationObject.tube = this.tube;
  28871. serializationObject.radialSegments = this.radialSegments;
  28872. serializationObject.tubularSegments = this.tubularSegments;
  28873. serializationObject.p = this.p;
  28874. serializationObject.q = this.q;
  28875. return serializationObject;
  28876. };
  28877. ;
  28878. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28879. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28880. return null; // null since geometry could be something else than a ground...
  28881. }
  28882. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28883. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28884. scene.pushGeometry(torusKnot, true);
  28885. return torusKnot;
  28886. };
  28887. return TorusKnot;
  28888. })(_Primitive);
  28889. Primitives.TorusKnot = TorusKnot;
  28890. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28891. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28892. })(BABYLON || (BABYLON = {}));
  28893. var BABYLON;
  28894. (function (BABYLON) {
  28895. var GroundMesh = (function (_super) {
  28896. __extends(GroundMesh, _super);
  28897. function GroundMesh(name, scene) {
  28898. _super.call(this, name, scene);
  28899. this.generateOctree = false;
  28900. this._worldInverse = new BABYLON.Matrix();
  28901. }
  28902. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28903. get: function () {
  28904. return this._subdivisions;
  28905. },
  28906. enumerable: true,
  28907. configurable: true
  28908. });
  28909. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28910. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28911. this._subdivisions = chunksCount;
  28912. this.subdivide(this._subdivisions);
  28913. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28914. };
  28915. /**
  28916. * Returns a height (y) value in the Worl system :
  28917. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28918. * Returns the ground y position if (x, z) are outside the ground surface.
  28919. * Not pertinent if the ground is rotated.
  28920. */
  28921. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28922. // express x and y in the ground local system
  28923. x -= this.position.x;
  28924. z -= this.position.z;
  28925. x /= this.scaling.x;
  28926. z /= this.scaling.z;
  28927. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28928. return this.position.y;
  28929. }
  28930. if (!this._heightQuads || this._heightQuads.length == 0) {
  28931. this._initHeightQuads();
  28932. this._computeHeightQuads();
  28933. }
  28934. var facet = this._getFacetAt(x, z);
  28935. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28936. // return y in the World system
  28937. return y * this.scaling.y + this.position.y;
  28938. };
  28939. /**
  28940. * Returns a normalized vector (Vector3) orthogonal to the ground
  28941. * at the ground coordinates (x, z) expressed in the World system.
  28942. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28943. * Not pertinent if the ground is rotated.
  28944. */
  28945. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28946. var normal = new BABYLON.Vector3(0, 1, 0);
  28947. this.getNormalAtCoordinatesToRef(x, z, normal);
  28948. return normal;
  28949. };
  28950. /**
  28951. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28952. * at the ground coordinates (x, z) expressed in the World system.
  28953. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28954. * Not pertinent if the ground is rotated.
  28955. */
  28956. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28957. // express x and y in the ground local system
  28958. x -= this.position.x;
  28959. z -= this.position.z;
  28960. x /= this.scaling.x;
  28961. z /= this.scaling.z;
  28962. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28963. return;
  28964. }
  28965. if (!this._heightQuads || this._heightQuads.length == 0) {
  28966. this._initHeightQuads();
  28967. this._computeHeightQuads();
  28968. }
  28969. var facet = this._getFacetAt(x, z);
  28970. ref.x = facet.x;
  28971. ref.y = facet.y;
  28972. ref.z = facet.z;
  28973. };
  28974. /**
  28975. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28976. * if the ground has been updated.
  28977. * This can be used in the render loop
  28978. */
  28979. GroundMesh.prototype.updateCoordinateHeights = function () {
  28980. if (!this._heightQuads || this._heightQuads.length == 0) {
  28981. this._initHeightQuads();
  28982. }
  28983. this._computeHeightQuads();
  28984. };
  28985. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28986. GroundMesh.prototype._getFacetAt = function (x, z) {
  28987. // retrieve col and row from x, z coordinates in the ground local system
  28988. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28989. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28990. var quad = this._heightQuads[row * this._subdivisions + col];
  28991. var facet;
  28992. if (z < quad.slope.x * x + quad.slope.y) {
  28993. facet = quad.facet1;
  28994. }
  28995. else {
  28996. facet = quad.facet2;
  28997. }
  28998. return facet;
  28999. };
  29000. // Creates and populates the heightMap array with "facet" elements :
  29001. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  29002. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29003. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29004. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29005. GroundMesh.prototype._initHeightQuads = function () {
  29006. this._heightQuads = new Array();
  29007. for (var row = 0; row < this._subdivisions; row++) {
  29008. for (var col = 0; col < this._subdivisions; col++) {
  29009. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  29010. this._heightQuads[row * this._subdivisions + col] = quad;
  29011. }
  29012. }
  29013. };
  29014. // Compute each quad element values and update the the heightMap array :
  29015. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29016. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29017. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29018. GroundMesh.prototype._computeHeightQuads = function () {
  29019. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29020. var v1 = BABYLON.Tmp.Vector3[0];
  29021. var v2 = BABYLON.Tmp.Vector3[1];
  29022. var v3 = BABYLON.Tmp.Vector3[2];
  29023. var v4 = BABYLON.Tmp.Vector3[3];
  29024. var v1v2 = BABYLON.Tmp.Vector3[4];
  29025. var v1v3 = BABYLON.Tmp.Vector3[5];
  29026. var v1v4 = BABYLON.Tmp.Vector3[6];
  29027. var norm1 = BABYLON.Tmp.Vector3[7];
  29028. var norm2 = BABYLON.Tmp.Vector3[8];
  29029. var i = 0;
  29030. var j = 0;
  29031. var k = 0;
  29032. var cd = 0; // 2D slope coefficient : z = cd * x + h
  29033. var h = 0;
  29034. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  29035. var d2 = 0;
  29036. for (var row = 0; row < this._subdivisions; row++) {
  29037. for (var col = 0; col < this._subdivisions; col++) {
  29038. i = col * 3;
  29039. j = row * (this._subdivisions + 1) * 3;
  29040. k = (row + 1) * (this._subdivisions + 1) * 3;
  29041. v1.x = positions[j + i];
  29042. v1.y = positions[j + i + 1];
  29043. v1.z = positions[j + i + 2];
  29044. v2.x = positions[j + i + 3];
  29045. v2.y = positions[j + i + 4];
  29046. v2.z = positions[j + i + 5];
  29047. v3.x = positions[k + i];
  29048. v3.y = positions[k + i + 1];
  29049. v3.z = positions[k + i + 2];
  29050. v4.x = positions[k + i + 3];
  29051. v4.y = positions[k + i + 4];
  29052. v4.z = positions[k + i + 5];
  29053. // 2D slope V1V4
  29054. cd = (v4.z - v1.z) / (v4.x - v1.x);
  29055. h = v1.z - cd * v1.x; // v1 belongs to the slope
  29056. // facet equations :
  29057. // we compute each facet normal vector
  29058. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  29059. // we compute the value d by applying the equation to v1 which belongs to the plane
  29060. // then we store the facet equation in a Vector4
  29061. v2.subtractToRef(v1, v1v2);
  29062. v3.subtractToRef(v1, v1v3);
  29063. v4.subtractToRef(v1, v1v4);
  29064. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  29065. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  29066. norm1.normalize();
  29067. norm2.normalize();
  29068. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  29069. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  29070. var quad = this._heightQuads[row * this._subdivisions + col];
  29071. quad.slope.copyFromFloats(cd, h);
  29072. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  29073. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  29074. }
  29075. }
  29076. };
  29077. return GroundMesh;
  29078. })(BABYLON.Mesh);
  29079. BABYLON.GroundMesh = GroundMesh;
  29080. })(BABYLON || (BABYLON = {}));
  29081. var BABYLON;
  29082. (function (BABYLON) {
  29083. var LinesMesh = (function (_super) {
  29084. __extends(LinesMesh, _super);
  29085. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29086. if (parent === void 0) { parent = null; }
  29087. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29088. this.color = new BABYLON.Color3(1, 1, 1);
  29089. this.alpha = 1;
  29090. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29091. attributes: ["position"],
  29092. uniforms: ["worldViewProjection", "color"],
  29093. needAlphaBlending: true
  29094. });
  29095. }
  29096. Object.defineProperty(LinesMesh.prototype, "material", {
  29097. get: function () {
  29098. return this._colorShader;
  29099. },
  29100. enumerable: true,
  29101. configurable: true
  29102. });
  29103. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29104. get: function () {
  29105. return false;
  29106. },
  29107. enumerable: true,
  29108. configurable: true
  29109. });
  29110. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29111. get: function () {
  29112. return false;
  29113. },
  29114. enumerable: true,
  29115. configurable: true
  29116. });
  29117. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29118. var engine = this.getScene().getEngine();
  29119. var indexToBind = this._geometry.getIndexBuffer();
  29120. // VBOs
  29121. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29122. // Color
  29123. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29124. };
  29125. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29126. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29127. return;
  29128. }
  29129. var engine = this.getScene().getEngine();
  29130. // Draw order
  29131. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29132. };
  29133. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29134. return null;
  29135. };
  29136. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29137. this._colorShader.dispose();
  29138. _super.prototype.dispose.call(this, doNotRecurse);
  29139. };
  29140. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29141. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29142. };
  29143. return LinesMesh;
  29144. })(BABYLON.Mesh);
  29145. BABYLON.LinesMesh = LinesMesh;
  29146. })(BABYLON || (BABYLON = {}));
  29147. var BABYLON;
  29148. (function (BABYLON) {
  29149. var DebugLayer = (function () {
  29150. function DebugLayer(scene) {
  29151. var _this = this;
  29152. this._transformationMatrix = BABYLON.Matrix.Identity();
  29153. this._enabled = false;
  29154. this._labelsEnabled = false;
  29155. this._displayStatistics = true;
  29156. this._displayTree = false;
  29157. this._displayLogs = false;
  29158. this._identityMatrix = BABYLON.Matrix.Identity();
  29159. this.axisRatio = 0.02;
  29160. this.accentColor = "orange";
  29161. this._scene = scene;
  29162. this._syncPositions = function () {
  29163. var engine = _this._scene.getEngine();
  29164. var canvasRect = engine.getRenderingCanvasClientRect();
  29165. if (_this._showUI) {
  29166. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29167. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29168. _this._statsDiv.style.width = "400px";
  29169. _this._statsDiv.style.height = "auto";
  29170. _this._statsSubsetDiv.style.maxHeight = "240px";
  29171. _this._optionsDiv.style.left = "0px";
  29172. _this._optionsDiv.style.top = "10px";
  29173. _this._optionsDiv.style.width = "200px";
  29174. _this._optionsDiv.style.height = "auto";
  29175. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29176. _this._logDiv.style.left = "0px";
  29177. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29178. _this._logDiv.style.width = "600px";
  29179. _this._logDiv.style.height = "160px";
  29180. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29181. _this._treeDiv.style.top = "10px";
  29182. _this._treeDiv.style.width = "300px";
  29183. _this._treeDiv.style.height = "auto";
  29184. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29185. }
  29186. _this._globalDiv.style.left = canvasRect.left + "px";
  29187. _this._globalDiv.style.top = canvasRect.top + "px";
  29188. _this._drawingCanvas.style.left = "0px";
  29189. _this._drawingCanvas.style.top = "0px";
  29190. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29191. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29192. var devicePixelRatio = window.devicePixelRatio || 1;
  29193. var context = _this._drawingContext;
  29194. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29195. context.mozBackingStorePixelRatio ||
  29196. context.msBackingStorePixelRatio ||
  29197. context.oBackingStorePixelRatio ||
  29198. context.backingStorePixelRatio || 1;
  29199. _this._ratio = devicePixelRatio / backingStoreRatio;
  29200. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29201. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29202. };
  29203. this._onCanvasClick = function (evt) {
  29204. _this._clickPosition = {
  29205. x: evt.clientX * _this._ratio,
  29206. y: evt.clientY * _this._ratio
  29207. };
  29208. };
  29209. this._syncUI = function () {
  29210. if (_this._showUI) {
  29211. if (_this._displayStatistics) {
  29212. _this._displayStats();
  29213. _this._statsDiv.style.display = "";
  29214. }
  29215. else {
  29216. _this._statsDiv.style.display = "none";
  29217. }
  29218. if (_this._displayLogs) {
  29219. _this._logDiv.style.display = "";
  29220. }
  29221. else {
  29222. _this._logDiv.style.display = "none";
  29223. }
  29224. if (_this._displayTree) {
  29225. _this._treeDiv.style.display = "";
  29226. if (_this._needToRefreshMeshesTree) {
  29227. _this._needToRefreshMeshesTree = false;
  29228. _this._refreshMeshesTreeContent();
  29229. }
  29230. }
  29231. else {
  29232. _this._treeDiv.style.display = "none";
  29233. }
  29234. }
  29235. };
  29236. this._syncData = function () {
  29237. if (_this._labelsEnabled || !_this._showUI) {
  29238. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29239. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29240. var engine = _this._scene.getEngine();
  29241. var viewport = _this._camera.viewport;
  29242. var globalViewport = viewport.toGlobal(engine);
  29243. // Meshes
  29244. var meshes = _this._camera.getActiveMeshes();
  29245. var index;
  29246. var projectedPosition;
  29247. for (index = 0; index < meshes.length; index++) {
  29248. var mesh = meshes.data[index];
  29249. var position = mesh.getBoundingInfo().boundingSphere.center;
  29250. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29251. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29252. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29253. }
  29254. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29255. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29256. }
  29257. }
  29258. // Cameras
  29259. var cameras = _this._scene.cameras;
  29260. for (index = 0; index < cameras.length; index++) {
  29261. var camera = cameras[index];
  29262. if (camera === _this._camera) {
  29263. continue;
  29264. }
  29265. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29266. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29267. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29268. _this._camera.detachControl(engine.getRenderingCanvas());
  29269. _this._camera = camera;
  29270. _this._camera.attachControl(engine.getRenderingCanvas());
  29271. }, function () { return "purple"; });
  29272. }
  29273. }
  29274. // Lights
  29275. var lights = _this._scene.lights;
  29276. for (index = 0; index < lights.length; index++) {
  29277. var light = lights[index];
  29278. if (light.position) {
  29279. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29280. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29281. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29282. light.setEnabled(!light.isEnabled());
  29283. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29284. }
  29285. }
  29286. }
  29287. }
  29288. _this._clickPosition = undefined;
  29289. };
  29290. }
  29291. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29292. while (this._treeSubsetDiv.hasChildNodes()) {
  29293. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29294. }
  29295. // Add meshes
  29296. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29297. sortedArray.sort(function (a, b) {
  29298. if (a.name === b.name) {
  29299. return 0;
  29300. }
  29301. return (a.name > b.name) ? 1 : -1;
  29302. });
  29303. for (var index = 0; index < sortedArray.length; index++) {
  29304. var mesh = sortedArray[index];
  29305. if (!mesh.isEnabled()) {
  29306. continue;
  29307. }
  29308. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29309. m.isVisible = element.checked;
  29310. }, mesh);
  29311. }
  29312. };
  29313. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29314. this._drawingContext.beginPath();
  29315. this._drawingContext.moveTo(zero.x, zero.y);
  29316. this._drawingContext.lineTo(unit.x, unit.y);
  29317. this._drawingContext.strokeStyle = color;
  29318. this._drawingContext.lineWidth = 4;
  29319. this._drawingContext.stroke();
  29320. this._drawingContext.font = "normal 14px Segoe UI";
  29321. this._drawingContext.fillStyle = color;
  29322. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29323. };
  29324. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29325. var position = mesh.getBoundingInfo().boundingSphere.center;
  29326. var worldMatrix = mesh.getWorldMatrix();
  29327. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29328. var unit = (unprojectedVector.subtract(position)).length();
  29329. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29330. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29331. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29332. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29333. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29334. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29335. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29336. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29337. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29338. };
  29339. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29340. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29341. this._drawingContext.font = "normal 12px Segoe UI";
  29342. var textMetrics = this._drawingContext.measureText(text);
  29343. var centerX = projectedPosition.x - textMetrics.width / 2;
  29344. var centerY = projectedPosition.y;
  29345. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29346. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29347. onClick();
  29348. }
  29349. this._drawingContext.beginPath();
  29350. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29351. this._drawingContext.fillStyle = getFillStyle();
  29352. this._drawingContext.globalAlpha = 0.5;
  29353. this._drawingContext.fill();
  29354. this._drawingContext.globalAlpha = 1.0;
  29355. this._drawingContext.strokeStyle = '#FFFFFF';
  29356. this._drawingContext.lineWidth = 1;
  29357. this._drawingContext.stroke();
  29358. this._drawingContext.fillStyle = "#FFFFFF";
  29359. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29360. this._drawingContext.beginPath();
  29361. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29362. this._drawingContext.fill();
  29363. }
  29364. };
  29365. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29366. if (!this._clickPosition) {
  29367. return false;
  29368. }
  29369. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29370. return false;
  29371. }
  29372. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29373. return false;
  29374. }
  29375. return true;
  29376. };
  29377. DebugLayer.prototype.isVisible = function () {
  29378. return this._enabled;
  29379. };
  29380. DebugLayer.prototype.hide = function () {
  29381. if (!this._enabled) {
  29382. return;
  29383. }
  29384. this._enabled = false;
  29385. var engine = this._scene.getEngine();
  29386. this._scene.unregisterBeforeRender(this._syncData);
  29387. this._scene.unregisterAfterRender(this._syncUI);
  29388. this._rootElement.removeChild(this._globalDiv);
  29389. this._scene.forceShowBoundingBoxes = false;
  29390. this._scene.forceWireframe = false;
  29391. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29392. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29393. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29394. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29395. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29396. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29397. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29398. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29399. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29400. this._scene.shadowsEnabled = true;
  29401. this._scene.particlesEnabled = true;
  29402. this._scene.postProcessesEnabled = true;
  29403. this._scene.collisionsEnabled = true;
  29404. this._scene.lightsEnabled = true;
  29405. this._scene.texturesEnabled = true;
  29406. this._scene.lensFlaresEnabled = true;
  29407. this._scene.proceduralTexturesEnabled = true;
  29408. this._scene.renderTargetsEnabled = true;
  29409. this._scene.probesEnabled = true;
  29410. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29411. };
  29412. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29413. if (showUI === void 0) { showUI = true; }
  29414. if (camera === void 0) { camera = null; }
  29415. if (rootElement === void 0) { rootElement = null; }
  29416. if (this._enabled) {
  29417. return;
  29418. }
  29419. this._enabled = true;
  29420. if (camera) {
  29421. this._camera = camera;
  29422. }
  29423. else {
  29424. this._camera = this._scene.activeCamera;
  29425. }
  29426. this._showUI = showUI;
  29427. var engine = this._scene.getEngine();
  29428. this._globalDiv = document.createElement("div");
  29429. this._rootElement = rootElement || document.body;
  29430. this._rootElement.appendChild(this._globalDiv);
  29431. this._generateDOMelements();
  29432. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29433. this._syncPositions();
  29434. this._scene.registerBeforeRender(this._syncData);
  29435. this._scene.registerAfterRender(this._syncUI);
  29436. };
  29437. DebugLayer.prototype._clearLabels = function () {
  29438. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29439. for (var index = 0; index < this._scene.meshes.length; index++) {
  29440. var mesh = this._scene.meshes[index];
  29441. mesh.renderOverlay = false;
  29442. }
  29443. };
  29444. DebugLayer.prototype._generateheader = function (root, text) {
  29445. var header = document.createElement("div");
  29446. header.innerHTML = text + "&nbsp;";
  29447. header.style.textAlign = "right";
  29448. header.style.width = "100%";
  29449. header.style.color = "white";
  29450. header.style.backgroundColor = "Black";
  29451. header.style.padding = "5px 5px 4px 0px";
  29452. header.style.marginLeft = "-5px";
  29453. header.style.fontWeight = "bold";
  29454. root.appendChild(header);
  29455. };
  29456. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29457. var label = document.createElement("label");
  29458. label.innerHTML = title;
  29459. label.style.color = color;
  29460. root.appendChild(label);
  29461. root.appendChild(document.createElement("br"));
  29462. };
  29463. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29464. if (tag === void 0) { tag = null; }
  29465. var label = document.createElement("label");
  29466. var boundingBoxesCheckbox = document.createElement("input");
  29467. boundingBoxesCheckbox.type = "checkbox";
  29468. boundingBoxesCheckbox.checked = initialState;
  29469. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29470. task(evt.target, tag);
  29471. });
  29472. label.appendChild(boundingBoxesCheckbox);
  29473. var container = document.createElement("span");
  29474. var leftPart = document.createElement("span");
  29475. var rightPart = document.createElement("span");
  29476. rightPart.style.cssFloat = "right";
  29477. leftPart.innerHTML = leftTitle;
  29478. rightPart.innerHTML = rightTitle;
  29479. rightPart.style.fontSize = "12px";
  29480. rightPart.style.maxWidth = "200px";
  29481. container.appendChild(leftPart);
  29482. container.appendChild(rightPart);
  29483. label.appendChild(container);
  29484. root.appendChild(label);
  29485. root.appendChild(document.createElement("br"));
  29486. };
  29487. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29488. if (tag === void 0) { tag = null; }
  29489. var label = document.createElement("label");
  29490. var checkBox = document.createElement("input");
  29491. checkBox.type = "checkbox";
  29492. checkBox.checked = initialState;
  29493. checkBox.addEventListener("change", function (evt) {
  29494. task(evt.target, tag);
  29495. });
  29496. label.appendChild(checkBox);
  29497. label.appendChild(document.createTextNode(title));
  29498. root.appendChild(label);
  29499. root.appendChild(document.createElement("br"));
  29500. };
  29501. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29502. if (tag === void 0) { tag = null; }
  29503. var button = document.createElement("button");
  29504. button.innerHTML = title;
  29505. button.style.height = "24px";
  29506. button.style.width = "150px";
  29507. button.style.marginBottom = "5px";
  29508. button.style.color = "#444444";
  29509. button.style.border = "1px solid white";
  29510. button.className = "debugLayerButton";
  29511. button.addEventListener("click", function (evt) {
  29512. task(evt.target, tag);
  29513. });
  29514. root.appendChild(button);
  29515. root.appendChild(document.createElement("br"));
  29516. };
  29517. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29518. if (tag === void 0) { tag = null; }
  29519. var label = document.createElement("label");
  29520. var boundingBoxesRadio = document.createElement("input");
  29521. boundingBoxesRadio.type = "radio";
  29522. boundingBoxesRadio.name = name;
  29523. boundingBoxesRadio.checked = initialState;
  29524. boundingBoxesRadio.addEventListener("change", function (evt) {
  29525. task(evt.target, tag);
  29526. });
  29527. label.appendChild(boundingBoxesRadio);
  29528. label.appendChild(document.createTextNode(title));
  29529. root.appendChild(label);
  29530. root.appendChild(document.createElement("br"));
  29531. };
  29532. DebugLayer.prototype._generateDOMelements = function () {
  29533. var _this = this;
  29534. this._globalDiv.id = "DebugLayer";
  29535. this._globalDiv.style.position = "absolute";
  29536. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29537. this._globalDiv.style.fontSize = "14px";
  29538. this._globalDiv.style.color = "white";
  29539. // Drawing canvas
  29540. this._drawingCanvas = document.createElement("canvas");
  29541. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29542. this._drawingCanvas.style.position = "absolute";
  29543. this._drawingCanvas.style.pointerEvents = "none";
  29544. this._drawingCanvas.style.backgroundColor = "transparent";
  29545. this._drawingContext = this._drawingCanvas.getContext("2d");
  29546. this._globalDiv.appendChild(this._drawingCanvas);
  29547. if (this._showUI) {
  29548. var background = "rgba(128, 128, 128, 0.4)";
  29549. var border = "rgb(180, 180, 180) solid 1px";
  29550. // Stats
  29551. this._statsDiv = document.createElement("div");
  29552. this._statsDiv.id = "DebugLayerStats";
  29553. this._statsDiv.style.border = border;
  29554. this._statsDiv.style.position = "absolute";
  29555. this._statsDiv.style.background = background;
  29556. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29557. this._generateheader(this._statsDiv, "STATISTICS");
  29558. this._statsSubsetDiv = document.createElement("div");
  29559. this._statsSubsetDiv.style.paddingTop = "5px";
  29560. this._statsSubsetDiv.style.paddingBottom = "5px";
  29561. this._statsSubsetDiv.style.overflowY = "auto";
  29562. this._statsDiv.appendChild(this._statsSubsetDiv);
  29563. // Tree
  29564. this._treeDiv = document.createElement("div");
  29565. this._treeDiv.id = "DebugLayerTree";
  29566. this._treeDiv.style.border = border;
  29567. this._treeDiv.style.position = "absolute";
  29568. this._treeDiv.style.background = background;
  29569. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29570. this._treeDiv.style.display = "none";
  29571. this._generateheader(this._treeDiv, "MESHES TREE");
  29572. this._treeSubsetDiv = document.createElement("div");
  29573. this._treeSubsetDiv.style.paddingTop = "5px";
  29574. this._treeSubsetDiv.style.paddingRight = "5px";
  29575. this._treeSubsetDiv.style.overflowY = "auto";
  29576. this._treeSubsetDiv.style.maxHeight = "300px";
  29577. this._treeDiv.appendChild(this._treeSubsetDiv);
  29578. this._needToRefreshMeshesTree = true;
  29579. // Logs
  29580. this._logDiv = document.createElement("div");
  29581. this._logDiv.style.border = border;
  29582. this._logDiv.id = "DebugLayerLogs";
  29583. this._logDiv.style.position = "absolute";
  29584. this._logDiv.style.background = background;
  29585. this._logDiv.style.padding = "0px 0px 0px 5px";
  29586. this._logDiv.style.display = "none";
  29587. this._generateheader(this._logDiv, "LOGS");
  29588. this._logSubsetDiv = document.createElement("div");
  29589. this._logSubsetDiv.style.height = "127px";
  29590. this._logSubsetDiv.style.paddingTop = "5px";
  29591. this._logSubsetDiv.style.overflowY = "auto";
  29592. this._logSubsetDiv.style.fontSize = "12px";
  29593. this._logSubsetDiv.style.fontFamily = "consolas";
  29594. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29595. this._logDiv.appendChild(this._logSubsetDiv);
  29596. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29597. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29598. };
  29599. // Options
  29600. this._optionsDiv = document.createElement("div");
  29601. this._optionsDiv.id = "DebugLayerOptions";
  29602. this._optionsDiv.style.border = border;
  29603. this._optionsDiv.style.position = "absolute";
  29604. this._optionsDiv.style.background = background;
  29605. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29606. this._optionsDiv.style.overflowY = "auto";
  29607. this._generateheader(this._optionsDiv, "OPTIONS");
  29608. this._optionsSubsetDiv = document.createElement("div");
  29609. this._optionsSubsetDiv.style.paddingTop = "5px";
  29610. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29611. this._optionsSubsetDiv.style.overflowY = "auto";
  29612. this._optionsSubsetDiv.style.maxHeight = "200px";
  29613. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29614. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29615. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29616. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29617. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29618. _this._displayTree = element.checked;
  29619. _this._needToRefreshMeshesTree = true;
  29620. });
  29621. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29622. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29623. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29624. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29625. _this._labelsEnabled = element.checked;
  29626. if (!_this._labelsEnabled) {
  29627. _this._clearLabels();
  29628. }
  29629. });
  29630. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29631. if (element.checked) {
  29632. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29633. }
  29634. else {
  29635. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29636. }
  29637. });
  29638. ;
  29639. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29640. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29641. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29642. if (element.checked) {
  29643. _this._scene.forceWireframe = false;
  29644. _this._scene.forcePointsCloud = false;
  29645. }
  29646. });
  29647. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29648. if (element.checked) {
  29649. _this._scene.forceWireframe = true;
  29650. _this._scene.forcePointsCloud = false;
  29651. }
  29652. });
  29653. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29654. if (element.checked) {
  29655. _this._scene.forceWireframe = false;
  29656. _this._scene.forcePointsCloud = true;
  29657. }
  29658. });
  29659. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29660. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29661. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29662. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29663. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29664. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29665. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29666. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29667. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29668. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29669. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29670. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29671. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29672. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29673. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29674. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29675. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29676. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29677. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29678. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29679. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29680. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29681. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29682. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29683. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29684. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29685. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29686. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29687. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29688. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29689. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29690. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29691. if (element.checked) {
  29692. _this._scene.headphone = true;
  29693. }
  29694. });
  29695. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29696. if (element.checked) {
  29697. _this._scene.headphone = false;
  29698. }
  29699. });
  29700. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29701. _this._scene.audioEnabled = !element.checked;
  29702. });
  29703. }
  29704. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29705. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29706. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29707. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29708. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29709. if (_this._camera) {
  29710. console.log(_this._camera);
  29711. }
  29712. else {
  29713. console.warn("No camera defined, or debug layer created before camera creation!");
  29714. }
  29715. });
  29716. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29717. this._globalDiv.appendChild(this._statsDiv);
  29718. this._globalDiv.appendChild(this._logDiv);
  29719. this._globalDiv.appendChild(this._optionsDiv);
  29720. this._globalDiv.appendChild(this._treeDiv);
  29721. }
  29722. };
  29723. DebugLayer.prototype._displayStats = function () {
  29724. var scene = this._scene;
  29725. var engine = scene.getEngine();
  29726. var glInfo = engine.getGlInfo();
  29727. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29728. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29729. + "<b>Count</b><br>"
  29730. + "Total meshes: " + scene.meshes.length + "<br>"
  29731. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29732. + "Total materials: " + scene.materials.length + "<br>"
  29733. + "Total textures: " + scene.textures.length + "<br>"
  29734. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29735. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29736. + "Active bones: " + scene.getActiveBones() + "<br>"
  29737. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29738. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29739. + "<b>Duration</b><br>"
  29740. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29741. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29742. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29743. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29744. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29745. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29746. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29747. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29748. + "</div>"
  29749. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29750. + "<b>Extensions</b><br>"
  29751. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29752. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29753. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29754. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29755. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29756. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29757. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29758. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29759. + "</div><br>"
  29760. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29761. + "<b>Caps.</b><br>"
  29762. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29763. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29764. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29765. + "<b>Info</b><br>"
  29766. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29767. + glInfo.version + "<br>"
  29768. + "</div><br>"
  29769. + glInfo.renderer + "<br>";
  29770. if (this.customStatsFunction) {
  29771. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29772. }
  29773. };
  29774. return DebugLayer;
  29775. })();
  29776. BABYLON.DebugLayer = DebugLayer;
  29777. })(BABYLON || (BABYLON = {}));
  29778. var BABYLON;
  29779. (function (BABYLON) {
  29780. var DefaultLoadingScreen = (function () {
  29781. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29782. var _this = this;
  29783. if (_loadingText === void 0) { _loadingText = ""; }
  29784. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29785. this._renderingCanvas = _renderingCanvas;
  29786. this._loadingText = _loadingText;
  29787. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29788. // Resize
  29789. this._resizeLoadingUI = function () {
  29790. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29791. _this._loadingDiv.style.position = "absolute";
  29792. _this._loadingDiv.style.left = canvasRect.left + "px";
  29793. _this._loadingDiv.style.top = canvasRect.top + "px";
  29794. _this._loadingDiv.style.width = canvasRect.width + "px";
  29795. _this._loadingDiv.style.height = canvasRect.height + "px";
  29796. };
  29797. }
  29798. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29799. var _this = this;
  29800. if (this._loadingDiv) {
  29801. // Do not add a loading screen if there is already one
  29802. return;
  29803. }
  29804. this._loadingDiv = document.createElement("div");
  29805. this._loadingDiv.id = "babylonjsLoadingDiv";
  29806. this._loadingDiv.style.opacity = "0";
  29807. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29808. // Loading text
  29809. this._loadingTextDiv = document.createElement("div");
  29810. this._loadingTextDiv.style.position = "absolute";
  29811. this._loadingTextDiv.style.left = "0";
  29812. this._loadingTextDiv.style.top = "50%";
  29813. this._loadingTextDiv.style.marginTop = "80px";
  29814. this._loadingTextDiv.style.width = "100%";
  29815. this._loadingTextDiv.style.height = "20px";
  29816. this._loadingTextDiv.style.fontFamily = "Arial";
  29817. this._loadingTextDiv.style.fontSize = "14px";
  29818. this._loadingTextDiv.style.color = "white";
  29819. this._loadingTextDiv.style.textAlign = "center";
  29820. this._loadingTextDiv.innerHTML = "Loading";
  29821. this._loadingDiv.appendChild(this._loadingTextDiv);
  29822. //set the predefined text
  29823. this._loadingTextDiv.innerHTML = this._loadingText;
  29824. // Loading img
  29825. var imgBack = new Image();
  29826. 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==";
  29827. imgBack.style.position = "absolute";
  29828. imgBack.style.left = "50%";
  29829. imgBack.style.top = "50%";
  29830. imgBack.style.marginLeft = "-50px";
  29831. imgBack.style.marginTop = "-50px";
  29832. imgBack.style.transition = "transform 1.0s ease";
  29833. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29834. var deg = 360;
  29835. var onTransitionEnd = function () {
  29836. deg += 360;
  29837. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29838. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29839. };
  29840. imgBack.addEventListener("transitionend", onTransitionEnd);
  29841. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29842. this._loadingDiv.appendChild(imgBack);
  29843. // front image
  29844. var imgFront = new Image();
  29845. 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=";
  29846. imgFront.style.position = "absolute";
  29847. imgFront.style.left = "50%";
  29848. imgFront.style.top = "50%";
  29849. imgFront.style.marginLeft = "-50px";
  29850. imgFront.style.marginTop = "-50px";
  29851. this._loadingDiv.appendChild(imgFront);
  29852. this._resizeLoadingUI();
  29853. window.addEventListener("resize", this._resizeLoadingUI);
  29854. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29855. document.body.appendChild(this._loadingDiv);
  29856. setTimeout(function () {
  29857. _this._loadingDiv.style.opacity = "1";
  29858. imgBack.style.transform = "rotateZ(360deg)";
  29859. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29860. }, 0);
  29861. };
  29862. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29863. var _this = this;
  29864. if (!this._loadingDiv) {
  29865. return;
  29866. }
  29867. var onTransitionEnd = function () {
  29868. if (!_this._loadingDiv) {
  29869. return;
  29870. }
  29871. document.body.removeChild(_this._loadingDiv);
  29872. window.removeEventListener("resize", _this._resizeLoadingUI);
  29873. _this._loadingDiv = null;
  29874. };
  29875. this._loadingDiv.style.opacity = "0";
  29876. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29877. };
  29878. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29879. set: function (text) {
  29880. this._loadingText = text;
  29881. if (this._loadingTextDiv) {
  29882. this._loadingTextDiv.innerHTML = this._loadingText;
  29883. }
  29884. },
  29885. enumerable: true,
  29886. configurable: true
  29887. });
  29888. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29889. get: function () {
  29890. return this._loadingDivBackgroundColor;
  29891. },
  29892. set: function (color) {
  29893. this._loadingDivBackgroundColor = color;
  29894. if (!this._loadingDiv) {
  29895. return;
  29896. }
  29897. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29898. },
  29899. enumerable: true,
  29900. configurable: true
  29901. });
  29902. return DefaultLoadingScreen;
  29903. })();
  29904. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29905. })(BABYLON || (BABYLON = {}));
  29906. var BABYLON;
  29907. (function (BABYLON) {
  29908. var SIMDVector3 = (function () {
  29909. function SIMDVector3() {
  29910. }
  29911. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29912. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29913. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29914. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29915. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29916. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29917. 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));
  29918. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29919. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29920. };
  29921. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29922. var v0 = SIMD.float32x4.splat(x);
  29923. var v1 = SIMD.float32x4.splat(y);
  29924. var v2 = SIMD.float32x4.splat(z);
  29925. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29926. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29927. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29928. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29929. 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));
  29930. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29931. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29932. };
  29933. return SIMDVector3;
  29934. })();
  29935. BABYLON.SIMDVector3 = SIMDVector3;
  29936. var SIMDMatrix = (function () {
  29937. function SIMDMatrix() {
  29938. }
  29939. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29940. if (offset === void 0) { offset = 0; }
  29941. var tm = this.m;
  29942. var om = other.m;
  29943. var om0 = SIMD.float32x4.load(om, 0);
  29944. var om1 = SIMD.float32x4.load(om, 4);
  29945. var om2 = SIMD.float32x4.load(om, 8);
  29946. var om3 = SIMD.float32x4.load(om, 12);
  29947. var tm0 = SIMD.float32x4.load(tm, 0);
  29948. 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)))));
  29949. var tm1 = SIMD.float32x4.load(tm, 4);
  29950. 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)))));
  29951. var tm2 = SIMD.float32x4.load(tm, 8);
  29952. 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)))));
  29953. var tm3 = SIMD.float32x4.load(tm, 12);
  29954. 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)))));
  29955. };
  29956. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29957. var src = this.m;
  29958. var dest = other.m;
  29959. var row0, row1, row2, row3;
  29960. var tmp1;
  29961. var minor0, minor1, minor2, minor3;
  29962. var det;
  29963. // Load the 4 rows
  29964. var src0 = SIMD.float32x4.load(src, 0);
  29965. var src1 = SIMD.float32x4.load(src, 4);
  29966. var src2 = SIMD.float32x4.load(src, 8);
  29967. var src3 = SIMD.float32x4.load(src, 12);
  29968. // Transpose the source matrix. Sort of. Not a true transpose operation
  29969. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29970. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29971. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29972. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29973. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29974. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29975. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29976. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29977. // This is a true transposition, but it will lead to an incorrect result
  29978. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29979. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29980. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29981. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29982. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29983. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29984. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29985. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29986. // ----
  29987. tmp1 = SIMD.float32x4.mul(row2, row3);
  29988. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29989. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29990. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29991. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29992. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29993. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29994. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29995. // ----
  29996. tmp1 = SIMD.float32x4.mul(row1, row2);
  29997. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29998. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29999. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30000. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30001. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30002. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30003. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30004. // ----
  30005. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30006. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30007. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30008. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30009. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30010. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30011. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30012. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30013. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30014. // ----
  30015. tmp1 = SIMD.float32x4.mul(row0, row1);
  30016. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30017. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30018. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30019. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30020. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30021. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30022. // ----
  30023. tmp1 = SIMD.float32x4.mul(row0, row3);
  30024. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30025. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30026. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30027. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30028. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30029. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30030. // ----
  30031. tmp1 = SIMD.float32x4.mul(row0, row2);
  30032. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30033. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30034. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30035. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30036. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30037. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30038. // Compute determinant
  30039. det = SIMD.float32x4.mul(row0, minor0);
  30040. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30041. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30042. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30043. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30044. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30045. // These shuffles aren't necessary if the faulty transposition is done
  30046. // up at the top of this function.
  30047. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30048. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30049. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30050. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30051. // Compute final values by multiplying with 1/det
  30052. minor0 = SIMD.float32x4.mul(det, minor0);
  30053. minor1 = SIMD.float32x4.mul(det, minor1);
  30054. minor2 = SIMD.float32x4.mul(det, minor2);
  30055. minor3 = SIMD.float32x4.mul(det, minor3);
  30056. SIMD.float32x4.store(dest, 0, minor0);
  30057. SIMD.float32x4.store(dest, 4, minor1);
  30058. SIMD.float32x4.store(dest, 8, minor2);
  30059. SIMD.float32x4.store(dest, 12, minor3);
  30060. return this;
  30061. };
  30062. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30063. var out = result.m;
  30064. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30065. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30066. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30067. // cc.kmVec3Subtract(f, pCenter, pEye);
  30068. var f = SIMD.float32x4.sub(center, eye);
  30069. // cc.kmVec3Normalize(f, f);
  30070. var tmp = SIMD.float32x4.mul(f, f);
  30071. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30072. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30073. // cc.kmVec3Assign(up, pUp);
  30074. // cc.kmVec3Normalize(up, up);
  30075. tmp = SIMD.float32x4.mul(up, up);
  30076. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30077. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30078. // cc.kmVec3Cross(s, f, up);
  30079. 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)));
  30080. // cc.kmVec3Normalize(s, s);
  30081. tmp = SIMD.float32x4.mul(s, s);
  30082. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30083. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30084. // cc.kmVec3Cross(u, s, f);
  30085. 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)));
  30086. // cc.kmVec3Normalize(s, s);
  30087. tmp = SIMD.float32x4.mul(s, s);
  30088. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30089. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30090. var zero = SIMD.float32x4.splat(0.0);
  30091. s = SIMD.float32x4.neg(s);
  30092. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30093. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30094. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30095. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30096. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30097. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30098. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30099. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30100. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30101. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30102. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30103. var b3 = SIMD.float32x4.neg(eye);
  30104. b3 = SIMD.float32x4.withW(b3, 1.0);
  30105. 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)))));
  30106. 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)))));
  30107. 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)))));
  30108. 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)))));
  30109. };
  30110. return SIMDMatrix;
  30111. })();
  30112. BABYLON.SIMDMatrix = SIMDMatrix;
  30113. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30114. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30115. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30116. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30117. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30118. var SIMDHelper = (function () {
  30119. function SIMDHelper() {
  30120. }
  30121. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30122. get: function () {
  30123. return SIMDHelper._isEnabled;
  30124. },
  30125. enumerable: true,
  30126. configurable: true
  30127. });
  30128. SIMDHelper.DisableSIMD = function () {
  30129. // Replace functions
  30130. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30131. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30132. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30133. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30134. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30135. SIMDHelper._isEnabled = false;
  30136. };
  30137. SIMDHelper.EnableSIMD = function () {
  30138. if (window.SIMD === undefined) {
  30139. return;
  30140. }
  30141. // Replace functions
  30142. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30143. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30144. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30145. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30147. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30148. get: function () { return this._data[0]; },
  30149. set: function (value) {
  30150. if (!this._data) {
  30151. this._data = new Float32Array(3);
  30152. }
  30153. this._data[0] = value;
  30154. }
  30155. });
  30156. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30157. get: function () { return this._data[1]; },
  30158. set: function (value) {
  30159. this._data[1] = value;
  30160. }
  30161. });
  30162. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30163. get: function () { return this._data[2]; },
  30164. set: function (value) {
  30165. this._data[2] = value;
  30166. }
  30167. });
  30168. SIMDHelper._isEnabled = true;
  30169. };
  30170. SIMDHelper._isEnabled = false;
  30171. return SIMDHelper;
  30172. })();
  30173. BABYLON.SIMDHelper = SIMDHelper;
  30174. })(BABYLON || (BABYLON = {}));
  30175. var BABYLON;
  30176. (function (BABYLON) {
  30177. var ShaderMaterial = (function (_super) {
  30178. __extends(ShaderMaterial, _super);
  30179. function ShaderMaterial(name, scene, shaderPath, options) {
  30180. _super.call(this, name, scene);
  30181. this._textures = {};
  30182. this._floats = {};
  30183. this._floatsArrays = {};
  30184. this._colors3 = {};
  30185. this._colors4 = {};
  30186. this._vectors2 = {};
  30187. this._vectors3 = {};
  30188. this._vectors4 = {};
  30189. this._matrices = {};
  30190. this._matrices3x3 = {};
  30191. this._matrices2x2 = {};
  30192. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30193. this._shaderPath = shaderPath;
  30194. options.needAlphaBlending = options.needAlphaBlending || false;
  30195. options.needAlphaTesting = options.needAlphaTesting || false;
  30196. options.attributes = options.attributes || ["position", "normal", "uv"];
  30197. options.uniforms = options.uniforms || ["worldViewProjection"];
  30198. options.samplers = options.samplers || [];
  30199. options.defines = options.defines || [];
  30200. this._options = options;
  30201. }
  30202. ShaderMaterial.prototype.needAlphaBlending = function () {
  30203. return this._options.needAlphaBlending;
  30204. };
  30205. ShaderMaterial.prototype.needAlphaTesting = function () {
  30206. return this._options.needAlphaTesting;
  30207. };
  30208. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30209. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30210. this._options.uniforms.push(uniformName);
  30211. }
  30212. };
  30213. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30214. if (this._options.samplers.indexOf(name) === -1) {
  30215. this._options.samplers.push(name);
  30216. }
  30217. this._textures[name] = texture;
  30218. return this;
  30219. };
  30220. ShaderMaterial.prototype.setFloat = function (name, value) {
  30221. this._checkUniform(name);
  30222. this._floats[name] = value;
  30223. return this;
  30224. };
  30225. ShaderMaterial.prototype.setFloats = function (name, value) {
  30226. this._checkUniform(name);
  30227. this._floatsArrays[name] = value;
  30228. return this;
  30229. };
  30230. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30231. this._checkUniform(name);
  30232. this._colors3[name] = value;
  30233. return this;
  30234. };
  30235. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30236. this._checkUniform(name);
  30237. this._colors4[name] = value;
  30238. return this;
  30239. };
  30240. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30241. this._checkUniform(name);
  30242. this._vectors2[name] = value;
  30243. return this;
  30244. };
  30245. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30246. this._checkUniform(name);
  30247. this._vectors3[name] = value;
  30248. return this;
  30249. };
  30250. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30251. this._checkUniform(name);
  30252. this._vectors4[name] = value;
  30253. return this;
  30254. };
  30255. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30256. this._checkUniform(name);
  30257. this._matrices[name] = value;
  30258. return this;
  30259. };
  30260. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30261. this._checkUniform(name);
  30262. this._matrices3x3[name] = value;
  30263. return this;
  30264. };
  30265. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30266. this._checkUniform(name);
  30267. this._matrices2x2[name] = value;
  30268. return this;
  30269. };
  30270. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30271. var scene = this.getScene();
  30272. var engine = scene.getEngine();
  30273. if (!this.checkReadyOnEveryCall) {
  30274. if (this._renderId === scene.getRenderId()) {
  30275. return true;
  30276. }
  30277. }
  30278. // Instances
  30279. var defines = [];
  30280. var fallbacks = new BABYLON.EffectFallbacks();
  30281. if (useInstances) {
  30282. defines.push("#define INSTANCES");
  30283. }
  30284. for (var index = 0; index < this._options.defines.length; index++) {
  30285. defines.push(this._options.defines[index]);
  30286. }
  30287. // Bones
  30288. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30290. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30291. fallbacks.addCPUSkinningFallback(0, mesh);
  30292. }
  30293. // Alpha test
  30294. if (engine.getAlphaTesting()) {
  30295. defines.push("#define ALPHATEST");
  30296. }
  30297. var previousEffect = this._effect;
  30298. var join = defines.join("\n");
  30299. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30300. if (!this._effect.isReady()) {
  30301. return false;
  30302. }
  30303. if (previousEffect !== this._effect) {
  30304. scene.resetCachedMaterial();
  30305. }
  30306. this._renderId = scene.getRenderId();
  30307. return true;
  30308. };
  30309. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30310. var scene = this.getScene();
  30311. if (this._options.uniforms.indexOf("world") !== -1) {
  30312. this._effect.setMatrix("world", world);
  30313. }
  30314. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30315. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30316. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30317. }
  30318. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30319. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30320. }
  30321. };
  30322. ShaderMaterial.prototype.bind = function (world, mesh) {
  30323. // Std values
  30324. this.bindOnlyWorldMatrix(world);
  30325. if (this.getScene().getCachedMaterial() !== this) {
  30326. if (this._options.uniforms.indexOf("view") !== -1) {
  30327. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30328. }
  30329. if (this._options.uniforms.indexOf("projection") !== -1) {
  30330. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30331. }
  30332. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30333. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30334. }
  30335. // Bones
  30336. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30337. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30338. }
  30339. // Texture
  30340. for (var name in this._textures) {
  30341. this._effect.setTexture(name, this._textures[name]);
  30342. }
  30343. // Float
  30344. for (name in this._floats) {
  30345. this._effect.setFloat(name, this._floats[name]);
  30346. }
  30347. // Float s
  30348. for (name in this._floatsArrays) {
  30349. this._effect.setArray(name, this._floatsArrays[name]);
  30350. }
  30351. // Color3
  30352. for (name in this._colors3) {
  30353. this._effect.setColor3(name, this._colors3[name]);
  30354. }
  30355. // Color4
  30356. for (name in this._colors4) {
  30357. var color = this._colors4[name];
  30358. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30359. }
  30360. // Vector2
  30361. for (name in this._vectors2) {
  30362. this._effect.setVector2(name, this._vectors2[name]);
  30363. }
  30364. // Vector3
  30365. for (name in this._vectors3) {
  30366. this._effect.setVector3(name, this._vectors3[name]);
  30367. }
  30368. // Vector4
  30369. for (name in this._vectors4) {
  30370. this._effect.setVector4(name, this._vectors4[name]);
  30371. }
  30372. // Matrix
  30373. for (name in this._matrices) {
  30374. this._effect.setMatrix(name, this._matrices[name]);
  30375. }
  30376. // Matrix 3x3
  30377. for (name in this._matrices3x3) {
  30378. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30379. }
  30380. // Matrix 2x2
  30381. for (name in this._matrices2x2) {
  30382. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30383. }
  30384. }
  30385. _super.prototype.bind.call(this, world, mesh);
  30386. };
  30387. ShaderMaterial.prototype.clone = function (name) {
  30388. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30389. return newShaderMaterial;
  30390. };
  30391. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30392. for (var name in this._textures) {
  30393. this._textures[name].dispose();
  30394. }
  30395. this._textures = {};
  30396. _super.prototype.dispose.call(this, forceDisposeEffect);
  30397. };
  30398. ShaderMaterial.prototype.serialize = function () {
  30399. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30400. serializationObject.customType = "BABYLON.ShaderMaterial";
  30401. serializationObject.options = this._options;
  30402. serializationObject.shaderPath = this._shaderPath;
  30403. // Texture
  30404. serializationObject.textures = {};
  30405. for (var name in this._textures) {
  30406. serializationObject.textures[name] = this._textures[name].serialize();
  30407. }
  30408. // Float
  30409. serializationObject.floats = {};
  30410. for (name in this._floats) {
  30411. serializationObject.floats[name] = this._floats[name];
  30412. }
  30413. // Float s
  30414. serializationObject.floatArrays = {};
  30415. for (name in this._floatsArrays) {
  30416. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30417. }
  30418. // Color3
  30419. serializationObject.colors3 = {};
  30420. for (name in this._colors3) {
  30421. serializationObject.colors3[name] = this._colors3[name].asArray();
  30422. }
  30423. // Color4
  30424. serializationObject.colors4 = {};
  30425. for (name in this._colors4) {
  30426. serializationObject.colors4[name] = this._colors4[name].asArray();
  30427. }
  30428. // Vector2
  30429. serializationObject.vectors2 = {};
  30430. for (name in this._vectors2) {
  30431. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30432. }
  30433. // Vector3
  30434. serializationObject.vectors3 = {};
  30435. for (name in this._vectors3) {
  30436. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30437. }
  30438. // Vector4
  30439. serializationObject.vectors4 = {};
  30440. for (name in this._vectors4) {
  30441. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30442. }
  30443. // Matrix
  30444. serializationObject.matrices = {};
  30445. for (name in this._matrices) {
  30446. serializationObject.matrices[name] = this._matrices[name].asArray();
  30447. }
  30448. // Matrix 3x3
  30449. serializationObject.matrices3x3 = {};
  30450. for (name in this._matrices3x3) {
  30451. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30452. }
  30453. // Matrix 2x2
  30454. serializationObject.matrices2x2 = {};
  30455. for (name in this._matrices2x2) {
  30456. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30457. }
  30458. return serializationObject;
  30459. };
  30460. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30461. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30462. // Texture
  30463. for (var name in source.textures) {
  30464. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30465. }
  30466. // Float
  30467. for (name in source.floats) {
  30468. material.setFloat(name, source.floats[name]);
  30469. }
  30470. // Float s
  30471. for (name in source.floatsArrays) {
  30472. material.setFloats(name, source.floatsArrays[name]);
  30473. }
  30474. // Color3
  30475. for (name in source.colors3) {
  30476. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30477. }
  30478. // Color4
  30479. for (name in source.colors4) {
  30480. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30481. }
  30482. // Vector2
  30483. for (name in source.vectors2) {
  30484. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30485. }
  30486. // Vector3
  30487. for (name in source.vectors3) {
  30488. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30489. }
  30490. // Vector4
  30491. for (name in source.vectors4) {
  30492. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30493. }
  30494. // Matrix
  30495. for (name in source.matrices) {
  30496. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30497. }
  30498. // Matrix 3x3
  30499. for (name in source.matrices3x3) {
  30500. material.setMatrix3x3(name, source.matrices3x3[name]);
  30501. }
  30502. // Matrix 2x2
  30503. for (name in source.matrices2x2) {
  30504. material.setMatrix2x2(name, source.matrices2x2[name]);
  30505. }
  30506. return material;
  30507. };
  30508. return ShaderMaterial;
  30509. })(BABYLON.Material);
  30510. BABYLON.ShaderMaterial = ShaderMaterial;
  30511. })(BABYLON || (BABYLON = {}));
  30512. var BABYLON;
  30513. (function (BABYLON) {
  30514. var Internals;
  30515. (function (Internals) {
  30516. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30517. // All values and structures referenced from:
  30518. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30519. var DDS_MAGIC = 0x20534444;
  30520. 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;
  30521. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30522. 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;
  30523. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30524. function FourCCToInt32(value) {
  30525. return value.charCodeAt(0) +
  30526. (value.charCodeAt(1) << 8) +
  30527. (value.charCodeAt(2) << 16) +
  30528. (value.charCodeAt(3) << 24);
  30529. }
  30530. function Int32ToFourCC(value) {
  30531. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30532. }
  30533. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30534. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30535. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30536. var headerLengthInt = 31; // The header length in 32 bit ints
  30537. // Offsets into the header array
  30538. var off_magic = 0;
  30539. var off_size = 1;
  30540. var off_flags = 2;
  30541. var off_height = 3;
  30542. var off_width = 4;
  30543. var off_mipmapCount = 7;
  30544. var off_pfFlags = 20;
  30545. var off_pfFourCC = 21;
  30546. var off_RGBbpp = 22;
  30547. var off_RMask = 23;
  30548. var off_GMask = 24;
  30549. var off_BMask = 25;
  30550. var off_AMask = 26;
  30551. var off_caps1 = 27;
  30552. var off_caps2 = 28;
  30553. ;
  30554. var DDSTools = (function () {
  30555. function DDSTools() {
  30556. }
  30557. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30558. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30559. var mipmapCount = 1;
  30560. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30561. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30562. }
  30563. return {
  30564. width: header[off_width],
  30565. height: header[off_height],
  30566. mipmapCount: mipmapCount,
  30567. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30568. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30569. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30570. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30571. };
  30572. };
  30573. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30574. var byteArray = new Uint8Array(dataLength);
  30575. var srcData = new Uint8Array(arrayBuffer);
  30576. var index = 0;
  30577. for (var y = height - 1; y >= 0; y--) {
  30578. for (var x = 0; x < width; x++) {
  30579. var srcPos = dataOffset + (x + y * width) * 4;
  30580. byteArray[index + 2] = srcData[srcPos];
  30581. byteArray[index + 1] = srcData[srcPos + 1];
  30582. byteArray[index] = srcData[srcPos + 2];
  30583. byteArray[index + 3] = srcData[srcPos + 3];
  30584. index += 4;
  30585. }
  30586. }
  30587. return byteArray;
  30588. };
  30589. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30590. var byteArray = new Uint8Array(dataLength);
  30591. var srcData = new Uint8Array(arrayBuffer);
  30592. var index = 0;
  30593. for (var y = height - 1; y >= 0; y--) {
  30594. for (var x = 0; x < width; x++) {
  30595. var srcPos = dataOffset + (x + y * width) * 3;
  30596. byteArray[index + 2] = srcData[srcPos];
  30597. byteArray[index + 1] = srcData[srcPos + 1];
  30598. byteArray[index] = srcData[srcPos + 2];
  30599. index += 3;
  30600. }
  30601. }
  30602. return byteArray;
  30603. };
  30604. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30605. var byteArray = new Uint8Array(dataLength);
  30606. var srcData = new Uint8Array(arrayBuffer);
  30607. var index = 0;
  30608. for (var y = height - 1; y >= 0; y--) {
  30609. for (var x = 0; x < width; x++) {
  30610. var srcPos = dataOffset + (x + y * width);
  30611. byteArray[index] = srcData[srcPos];
  30612. index++;
  30613. }
  30614. }
  30615. return byteArray;
  30616. };
  30617. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30618. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30619. if (header[off_magic] != DDS_MAGIC) {
  30620. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30621. return;
  30622. }
  30623. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30624. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30625. return;
  30626. }
  30627. if (info.isFourCC) {
  30628. fourCC = header[off_pfFourCC];
  30629. switch (fourCC) {
  30630. case FOURCC_DXT1:
  30631. blockBytes = 8;
  30632. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30633. break;
  30634. case FOURCC_DXT3:
  30635. blockBytes = 16;
  30636. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30637. break;
  30638. case FOURCC_DXT5:
  30639. blockBytes = 16;
  30640. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30641. break;
  30642. default:
  30643. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30644. return;
  30645. }
  30646. }
  30647. mipmapCount = 1;
  30648. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30649. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30650. }
  30651. var bpp = header[off_RGBbpp];
  30652. for (var face = 0; face < faces; face++) {
  30653. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30654. width = header[off_width];
  30655. height = header[off_height];
  30656. dataOffset = header[off_size] + 4;
  30657. for (i = 0; i < mipmapCount; ++i) {
  30658. if (info.isRGB) {
  30659. if (bpp === 24) {
  30660. dataLength = width * height * 3;
  30661. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30662. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30663. }
  30664. else {
  30665. dataLength = width * height * 4;
  30666. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30667. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30668. }
  30669. }
  30670. else if (info.isLuminance) {
  30671. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30672. var unpaddedRowSize = width;
  30673. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30674. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30675. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30676. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30677. }
  30678. else {
  30679. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30680. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30681. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30682. }
  30683. dataOffset += dataLength;
  30684. width *= 0.5;
  30685. height *= 0.5;
  30686. width = Math.max(1.0, width);
  30687. height = Math.max(1.0, height);
  30688. }
  30689. }
  30690. };
  30691. return DDSTools;
  30692. })();
  30693. Internals.DDSTools = DDSTools;
  30694. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30695. })(BABYLON || (BABYLON = {}));
  30696. var BABYLON;
  30697. (function (BABYLON) {
  30698. var CannonJSPlugin = (function () {
  30699. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30700. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30701. if (iterations === void 0) { iterations = 10; }
  30702. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30703. this.name = "CannonJSPlugin";
  30704. this._physicsMaterials = [];
  30705. this._fixedTimeStep = 1 / 60;
  30706. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30707. this._currentCollisionGroup = 2;
  30708. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30709. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30710. this._tmpPosition = BABYLON.Vector3.Zero();
  30711. this._tmpQuaternion = new BABYLON.Quaternion();
  30712. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30713. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30714. this._tmpUnityRotation = new BABYLON.Quaternion();
  30715. if (!this.isSupported()) {
  30716. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30717. return;
  30718. }
  30719. this.world = new CANNON.World();
  30720. this.world.broadphase = new CANNON.NaiveBroadphase();
  30721. this.world.solver.iterations = iterations;
  30722. }
  30723. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30724. this.world.gravity.copy(gravity);
  30725. };
  30726. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30727. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30728. };
  30729. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30730. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30731. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30732. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30733. };
  30734. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30735. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30736. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30737. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30738. };
  30739. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30740. //parent-child relationship. Does this impostor has a parent impostor?
  30741. if (impostor.parent) {
  30742. if (impostor.physicsBody) {
  30743. this.removePhysicsBody(impostor);
  30744. //TODO is that needed?
  30745. impostor.forceUpdate();
  30746. }
  30747. return;
  30748. }
  30749. //should a new body be created for this impostor?
  30750. if (impostor.isBodyInitRequired()) {
  30751. if (!impostor.mesh.rotationQuaternion) {
  30752. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30753. }
  30754. var shape = this._createShape(impostor);
  30755. //unregister events, if body is being changed
  30756. var oldBody = impostor.physicsBody;
  30757. if (oldBody) {
  30758. this.removePhysicsBody(impostor);
  30759. }
  30760. //create the body and material
  30761. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  30762. var bodyCreationObject = {
  30763. mass: impostor.getParam("mass"),
  30764. material: material
  30765. };
  30766. // A simple extend, in case native options were used.
  30767. var nativeOptions = impostor.getParam("nativeOptions");
  30768. for (var key in nativeOptions) {
  30769. if (nativeOptions.hasOwnProperty(key)) {
  30770. bodyCreationObject[key] = nativeOptions[key];
  30771. }
  30772. }
  30773. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30774. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30775. this.world.addEventListener("preStep", impostor.beforeStep);
  30776. this.world.addEventListener("postStep", impostor.afterStep);
  30777. impostor.physicsBody.addShape(shape);
  30778. this.world.add(impostor.physicsBody);
  30779. //try to keep the body moving in the right direction by taking old properties.
  30780. //Should be tested!
  30781. if (oldBody) {
  30782. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30783. impostor.physicsBody[param].copy(oldBody[param]);
  30784. });
  30785. }
  30786. this._processChildMeshes(impostor);
  30787. }
  30788. //now update the body's transformation
  30789. this._updatePhysicsBodyTransformation(impostor);
  30790. };
  30791. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30792. var _this = this;
  30793. var meshChildren = mainImpostor.mesh.getChildMeshes();
  30794. if (meshChildren.length) {
  30795. var processMesh = function (localPosition, mesh) {
  30796. var childImpostor = mesh.getPhysicsImpostor();
  30797. if (childImpostor) {
  30798. var parent = childImpostor.parent;
  30799. if (parent !== mainImpostor) {
  30800. var localPosition = mesh.position;
  30801. if (childImpostor.physicsBody) {
  30802. _this.removePhysicsBody(childImpostor);
  30803. childImpostor.physicsBody = null;
  30804. }
  30805. childImpostor.parent = mainImpostor;
  30806. childImpostor.resetUpdateFlags();
  30807. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30808. //Add the mass of the children.
  30809. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30810. }
  30811. }
  30812. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  30813. };
  30814. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30815. }
  30816. };
  30817. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30818. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30819. this.world.removeEventListener("preStep", impostor.beforeStep);
  30820. this.world.removeEventListener("postStep", impostor.afterStep);
  30821. this.world.remove(impostor.physicsBody);
  30822. };
  30823. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30824. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30825. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30826. if (!mainBody || !connectedBody) {
  30827. return;
  30828. }
  30829. var constraint;
  30830. var jointData = impostorJoint.joint.jointData;
  30831. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30832. var constraintData = {
  30833. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30834. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30835. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30836. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30837. maxForce: jointData.nativeParams.maxForce,
  30838. collideConnected: !!jointData.collision
  30839. };
  30840. //Not needed, Cannon has a collideConnected flag
  30841. /*if (!jointData.collision) {
  30842. //add 1st body to a collision group of its own, if it is not in 1
  30843. if (mainBody.collisionFilterGroup === 1) {
  30844. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30845. this._currentCollisionGroup <<= 1;
  30846. }
  30847. if (connectedBody.collisionFilterGroup === 1) {
  30848. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30849. this._currentCollisionGroup <<= 1;
  30850. }
  30851. //add their mask to the collisionFilterMask of each other:
  30852. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30853. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30854. }*/
  30855. switch (impostorJoint.joint.type) {
  30856. case BABYLON.PhysicsJoint.HingeJoint:
  30857. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30858. break;
  30859. case BABYLON.PhysicsJoint.DistanceJoint:
  30860. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30861. break;
  30862. case BABYLON.PhysicsJoint.SpringJoint:
  30863. var springData = jointData;
  30864. constraint = new CANNON.Spring(mainBody, connectedBody, {
  30865. restLength: springData.length,
  30866. stiffness: springData.stiffness,
  30867. damping: springData.damping,
  30868. localAnchorA: constraintData.pivotA,
  30869. localAnchorB: constraintData.pivotB
  30870. });
  30871. break;
  30872. default:
  30873. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30874. break;
  30875. }
  30876. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  30877. constraint.collideConnected = !!jointData.collision;
  30878. impostorJoint.joint.physicsJoint = constraint;
  30879. this.world.addConstraint(constraint);
  30880. };
  30881. CannonJSPlugin.prototype.removeJoint = function (joint) {
  30882. //TODO
  30883. };
  30884. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  30885. var index;
  30886. var mat;
  30887. for (index = 0; index < this._physicsMaterials.length; index++) {
  30888. mat = this._physicsMaterials[index];
  30889. if (mat.friction === friction && mat.restitution === restitution) {
  30890. return mat;
  30891. }
  30892. }
  30893. var currentMat = new CANNON.Material("mat");
  30894. currentMat.friction = friction;
  30895. currentMat.restitution = restitution;
  30896. this._physicsMaterials.push(currentMat);
  30897. return currentMat;
  30898. };
  30899. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30900. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30901. };
  30902. CannonJSPlugin.prototype._createShape = function (impostor) {
  30903. var mesh = impostor.mesh;
  30904. //get the correct bounding box
  30905. var oldQuaternion = mesh.rotationQuaternion;
  30906. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30907. mesh.computeWorldMatrix(true);
  30908. var returnValue;
  30909. switch (impostor.type) {
  30910. case BABYLON.PhysicsEngine.SphereImpostor:
  30911. var bbox = mesh.getBoundingInfo().boundingBox;
  30912. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30913. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30914. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30915. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30916. break;
  30917. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30918. case BABYLON.PhysicsEngine.CylinderImpostor:
  30919. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30920. case BABYLON.PhysicsEngine.BoxImpostor:
  30921. bbox = mesh.getBoundingInfo().boundingBox;
  30922. var min = bbox.minimumWorld;
  30923. var max = bbox.maximumWorld;
  30924. var box = max.subtract(min).scale(0.5);
  30925. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30926. break;
  30927. case BABYLON.PhysicsEngine.PlaneImpostor:
  30928. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  30929. returnValue = new CANNON.Plane();
  30930. break;
  30931. case BABYLON.PhysicsEngine.MeshImpostor:
  30932. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30933. var rawFaces = mesh.getIndices();
  30934. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30935. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  30936. break;
  30937. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30938. returnValue = this._createHeightmap(mesh);
  30939. break;
  30940. }
  30941. mesh.rotationQuaternion = oldQuaternion;
  30942. return returnValue;
  30943. };
  30944. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30945. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30946. var matrix = [];
  30947. //For now pointDepth will not be used and will be automatically calculated.
  30948. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30949. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30950. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30951. var elementSize = dim * 2 / arraySize;
  30952. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30953. for (var i = 0; i < pos.length; i = i + 3) {
  30954. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30955. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30956. var y = pos[i + 1] + minY;
  30957. if (!matrix[x]) {
  30958. matrix[x] = [];
  30959. }
  30960. if (!matrix[x][z]) {
  30961. matrix[x][z] = y;
  30962. }
  30963. matrix[x][z] = Math.max(y, matrix[x][z]);
  30964. }
  30965. for (var x = 0; x <= arraySize; ++x) {
  30966. if (!matrix[x]) {
  30967. var loc = 1;
  30968. while (!matrix[(x + loc) % arraySize]) {
  30969. loc++;
  30970. }
  30971. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30972. }
  30973. for (var z = 0; z <= arraySize; ++z) {
  30974. if (!matrix[x][z]) {
  30975. var loc = 1;
  30976. var newValue;
  30977. while (newValue === undefined) {
  30978. newValue = matrix[x][(z + loc++) % arraySize];
  30979. }
  30980. matrix[x][z] = newValue;
  30981. }
  30982. }
  30983. }
  30984. var shape = new CANNON.Heightfield(matrix, {
  30985. elementSize: elementSize
  30986. });
  30987. //For future reference, needed for body transformation
  30988. shape.minY = minY;
  30989. return shape;
  30990. };
  30991. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  30992. var mesh = impostor.mesh;
  30993. //make sure it is updated...
  30994. impostor.mesh.computeWorldMatrix(true);
  30995. // The delta between the mesh position and the mesh bounding box center
  30996. var bbox = mesh.getBoundingInfo().boundingBox;
  30997. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  30998. var quaternion = mesh.rotationQuaternion;
  30999. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  31000. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31001. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31002. //-90 DEG in X, precalculated
  31003. quaternion = quaternion.multiply(this._minus90X);
  31004. //Invert! (Precalculated, 90 deg in X)
  31005. //No need to clone. this will never change.
  31006. impostor.setDeltaRotation(this._plus90X);
  31007. }
  31008. //If it is a heightfield, if should be centered.
  31009. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31010. //calculate the correct body position:
  31011. var rotationQuaternion = mesh.rotationQuaternion;
  31012. mesh.rotationQuaternion = this._tmpUnityRotation;
  31013. mesh.computeWorldMatrix(true);
  31014. //get original center with no rotation
  31015. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31016. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31017. //rotation is back
  31018. mesh.rotationQuaternion = rotationQuaternion;
  31019. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31020. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31021. mesh.setPivotMatrix(p);
  31022. mesh.computeWorldMatrix(true);
  31023. //calculate the translation
  31024. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31025. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31026. //add it inverted to the delta
  31027. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  31028. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31029. mesh.setPivotMatrix(oldPivot);
  31030. mesh.computeWorldMatrix(true);
  31031. }
  31032. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31033. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31034. this._tmpPosition.copyFrom(mesh.position);
  31035. }
  31036. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31037. //Now update the impostor object
  31038. impostor.physicsBody.position.copy(this._tmpPosition);
  31039. impostor.physicsBody.quaternion.copy(quaternion);
  31040. };
  31041. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31042. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31043. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31044. };
  31045. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31046. impostor.physicsBody.position.copy(newPosition);
  31047. impostor.physicsBody.quaternion.copy(newRotation);
  31048. };
  31049. CannonJSPlugin.prototype.isSupported = function () {
  31050. return window.CANNON !== undefined;
  31051. };
  31052. CannonJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31053. impostor.physicsBody.velocity.copy(velocity);
  31054. };
  31055. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  31056. impostor.physicsBody.sleep();
  31057. };
  31058. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  31059. impostor.physicsBody.wakeUp();
  31060. };
  31061. CannonJSPlugin.prototype.dispose = function () {
  31062. //nothing to do, actually.
  31063. };
  31064. return CannonJSPlugin;
  31065. })();
  31066. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31067. })(BABYLON || (BABYLON = {}));
  31068. var BABYLON;
  31069. (function (BABYLON) {
  31070. var OimoJSPlugin = (function () {
  31071. function OimoJSPlugin(iterations) {
  31072. this.name = "OimoJSPlugin";
  31073. this._tmpImpostorsArray = [];
  31074. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31075. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31076. this.world.clear();
  31077. //making sure no stats are calculated
  31078. this.world.isNoStat = true;
  31079. }
  31080. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31081. this.world.gravity.copy(gravity);
  31082. };
  31083. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31084. var _this = this;
  31085. impostors.forEach(function (impostor) {
  31086. impostor.beforeStep();
  31087. });
  31088. this.world.step();
  31089. impostors.forEach(function (impostor) {
  31090. impostor.afterStep();
  31091. //update the ordered impostors array
  31092. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31093. });
  31094. //check for collisions
  31095. var contact = this.world.contacts;
  31096. while (contact !== null) {
  31097. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31098. contact = contact.next;
  31099. continue;
  31100. }
  31101. //is this body colliding with any other? get the impostor
  31102. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31103. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31104. if (!mainImpostor || !collidingImpostor) {
  31105. contact = contact.next;
  31106. continue;
  31107. }
  31108. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31109. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31110. contact = contact.next;
  31111. }
  31112. };
  31113. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31114. var mass = impostor.physicsBody.massInfo.mass;
  31115. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31116. };
  31117. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31118. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31119. this.applyImpulse(impostor, force, contactPoint);
  31120. };
  31121. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31122. var _this = this;
  31123. //parent-child relationship. Does this impostor has a parent impostor?
  31124. if (impostor.parent) {
  31125. if (impostor.physicsBody) {
  31126. this.removePhysicsBody(impostor);
  31127. //TODO is that needed?
  31128. impostor.forceUpdate();
  31129. }
  31130. return;
  31131. }
  31132. impostor.mesh.computeWorldMatrix(true);
  31133. if (impostor.isBodyInitRequired()) {
  31134. if (!impostor.mesh.rotationQuaternion) {
  31135. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31136. }
  31137. var bodyConfig = {
  31138. name: impostor.mesh.uniqueId,
  31139. //Oimo must have mass, also for static objects.
  31140. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31141. size: [],
  31142. type: [],
  31143. pos: [],
  31144. rot: [],
  31145. move: impostor.getParam("mass") !== 0,
  31146. //Supporting older versions of Oimo
  31147. world: this.world
  31148. };
  31149. var impostors = [impostor];
  31150. function addToArray(parent) {
  31151. parent.getChildMeshes().forEach(function (m) {
  31152. if (m.physicsImpostor) {
  31153. impostors.push(m.physicsImpostor);
  31154. m.physicsImpostor._init();
  31155. }
  31156. });
  31157. }
  31158. addToArray(impostor.mesh);
  31159. function checkWithEpsilon(value) {
  31160. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31161. }
  31162. impostors.forEach(function (i) {
  31163. //get the correct bounding box
  31164. var oldQuaternion = i.mesh.rotationQuaternion;
  31165. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  31166. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31167. i.mesh.computeWorldMatrix(true);
  31168. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31169. if (i === impostor) {
  31170. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31171. //Can also use Array.prototype.push.apply
  31172. bodyConfig.pos.push(bbox.center.x);
  31173. bodyConfig.pos.push(bbox.center.y);
  31174. bodyConfig.pos.push(bbox.center.z);
  31175. //tmp solution
  31176. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31177. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31178. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31179. }
  31180. else {
  31181. bodyConfig.pos.push(i.mesh.position.x);
  31182. bodyConfig.pos.push(i.mesh.position.y);
  31183. bodyConfig.pos.push(i.mesh.position.z);
  31184. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31185. bodyConfig.rot.push(0);
  31186. bodyConfig.rot.push(0);
  31187. bodyConfig.rot.push(0);
  31188. }
  31189. // register mesh
  31190. switch (i.type) {
  31191. case BABYLON.PhysicsEngine.SphereImpostor:
  31192. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31193. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31194. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31195. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31196. bodyConfig.type.push('sphere');
  31197. //due to the way oimo works with compounds, add 3 times
  31198. bodyConfig.size.push(size);
  31199. bodyConfig.size.push(size);
  31200. bodyConfig.size.push(size);
  31201. break;
  31202. case BABYLON.PhysicsEngine.PlaneImpostor:
  31203. //TODO Oimo now supports cylinder!
  31204. case BABYLON.PhysicsEngine.CylinderImpostor:
  31205. case BABYLON.PhysicsEngine.BoxImpostor:
  31206. default:
  31207. var min = bbox.minimumWorld;
  31208. var max = bbox.maximumWorld;
  31209. var box = max.subtract(min);
  31210. var sizeX = checkWithEpsilon(box.x);
  31211. var sizeY = checkWithEpsilon(box.y);
  31212. var sizeZ = checkWithEpsilon(box.z);
  31213. bodyConfig.type.push('box');
  31214. bodyConfig.size.push(sizeX);
  31215. bodyConfig.size.push(sizeY);
  31216. bodyConfig.size.push(sizeZ);
  31217. break;
  31218. }
  31219. //actually not needed, but hey...
  31220. i.mesh.rotationQuaternion = oldQuaternion;
  31221. });
  31222. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31223. }
  31224. else {
  31225. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31226. }
  31227. impostor.setDeltaPosition(this._tmpPositionVector);
  31228. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31229. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31230. };
  31231. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31232. //impostor.physicsBody.dispose();
  31233. //Same as : (older oimo versions)
  31234. this.world.removeRigidBody(impostor.physicsBody);
  31235. };
  31236. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31237. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31238. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31239. if (!mainBody || !connectedBody) {
  31240. return;
  31241. }
  31242. var jointData = impostorJoint.joint.jointData;
  31243. var options = jointData.nativeParams || {};
  31244. var type;
  31245. var nativeJointData = {
  31246. body1: mainBody,
  31247. body2: connectedBody,
  31248. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31249. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31250. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31251. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31252. min: options.min,
  31253. max: options.max,
  31254. collision: options.collision || jointData.collision,
  31255. spring: options.spring,
  31256. //supporting older version of Oimo
  31257. world: this.world
  31258. };
  31259. switch (impostorJoint.joint.type) {
  31260. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31261. type = "jointBall";
  31262. break;
  31263. case BABYLON.PhysicsJoint.SpringJoint:
  31264. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  31265. var springData = jointData;
  31266. nativeJointData.min = springData.length || nativeJointData.min;
  31267. //Max should also be set, just make sure it is at least min
  31268. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  31269. case BABYLON.PhysicsJoint.DistanceJoint:
  31270. type = "jointDistance";
  31271. nativeJointData.max = jointData.maxDistance;
  31272. break;
  31273. case BABYLON.PhysicsJoint.PrismaticJoint:
  31274. type = "jointPrisme";
  31275. break;
  31276. case BABYLON.PhysicsJoint.SliderJoint:
  31277. type = "jointSlide";
  31278. break;
  31279. case BABYLON.PhysicsJoint.WheelJoint:
  31280. type = "jointWheel";
  31281. break;
  31282. case BABYLON.PhysicsJoint.HingeJoint:
  31283. default:
  31284. type = "jointHinge";
  31285. break;
  31286. }
  31287. nativeJointData.type = type;
  31288. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31289. };
  31290. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31291. joint.joint.physicsJoint.dispose();
  31292. };
  31293. OimoJSPlugin.prototype.isSupported = function () {
  31294. return OIMO !== undefined;
  31295. };
  31296. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31297. if (!impostor.physicsBody.sleeping) {
  31298. //TODO check that
  31299. if (impostor.physicsBody.shapes.next) {
  31300. var parentShape = this._getLastShape(impostor.physicsBody);
  31301. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31302. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31303. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31304. }
  31305. else {
  31306. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31307. }
  31308. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31309. }
  31310. };
  31311. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31312. var body = impostor.physicsBody;
  31313. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31314. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31315. body.syncShapes();
  31316. body.awake();
  31317. };
  31318. OimoJSPlugin.prototype._getLastShape = function (body) {
  31319. var lastShape = body.shapes;
  31320. while (lastShape.next) {
  31321. lastShape = lastShape.next;
  31322. }
  31323. return lastShape;
  31324. };
  31325. OimoJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31326. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31327. };
  31328. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  31329. impostor.physicsBody.sleep();
  31330. };
  31331. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  31332. impostor.physicsBody.awake();
  31333. };
  31334. OimoJSPlugin.prototype.dispose = function () {
  31335. this.world.clear();
  31336. };
  31337. return OimoJSPlugin;
  31338. })();
  31339. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31340. })(BABYLON || (BABYLON = {}));
  31341. var BABYLON;
  31342. (function (BABYLON) {
  31343. var DisplayPassPostProcess = (function (_super) {
  31344. __extends(DisplayPassPostProcess, _super);
  31345. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31346. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31347. }
  31348. return DisplayPassPostProcess;
  31349. })(BABYLON.PostProcess);
  31350. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31351. })(BABYLON || (BABYLON = {}));
  31352. var BABYLON;
  31353. (function (BABYLON) {
  31354. var SimplificationSettings = (function () {
  31355. function SimplificationSettings(quality, distance, optimizeMesh) {
  31356. this.quality = quality;
  31357. this.distance = distance;
  31358. this.optimizeMesh = optimizeMesh;
  31359. }
  31360. return SimplificationSettings;
  31361. })();
  31362. BABYLON.SimplificationSettings = SimplificationSettings;
  31363. var SimplificationQueue = (function () {
  31364. function SimplificationQueue() {
  31365. this.running = false;
  31366. this._simplificationArray = [];
  31367. }
  31368. SimplificationQueue.prototype.addTask = function (task) {
  31369. this._simplificationArray.push(task);
  31370. };
  31371. SimplificationQueue.prototype.executeNext = function () {
  31372. var task = this._simplificationArray.pop();
  31373. if (task) {
  31374. this.running = true;
  31375. this.runSimplification(task);
  31376. }
  31377. else {
  31378. this.running = false;
  31379. }
  31380. };
  31381. SimplificationQueue.prototype.runSimplification = function (task) {
  31382. var _this = this;
  31383. if (task.parallelProcessing) {
  31384. //parallel simplifier
  31385. task.settings.forEach(function (setting) {
  31386. var simplifier = _this.getSimplifier(task);
  31387. simplifier.simplify(setting, function (newMesh) {
  31388. task.mesh.addLODLevel(setting.distance, newMesh);
  31389. newMesh.isVisible = true;
  31390. //check if it is the last
  31391. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31392. //all done, run the success callback.
  31393. task.successCallback();
  31394. }
  31395. _this.executeNext();
  31396. });
  31397. });
  31398. }
  31399. else {
  31400. //single simplifier.
  31401. var simplifier = this.getSimplifier(task);
  31402. var runDecimation = function (setting, callback) {
  31403. simplifier.simplify(setting, function (newMesh) {
  31404. task.mesh.addLODLevel(setting.distance, newMesh);
  31405. newMesh.isVisible = true;
  31406. //run the next quality level
  31407. callback();
  31408. });
  31409. };
  31410. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31411. runDecimation(task.settings[loop.index], function () {
  31412. loop.executeNext();
  31413. });
  31414. }, function () {
  31415. //execution ended, run the success callback.
  31416. if (task.successCallback) {
  31417. task.successCallback();
  31418. }
  31419. _this.executeNext();
  31420. });
  31421. }
  31422. };
  31423. SimplificationQueue.prototype.getSimplifier = function (task) {
  31424. switch (task.simplificationType) {
  31425. case SimplificationType.QUADRATIC:
  31426. default:
  31427. return new QuadraticErrorSimplification(task.mesh);
  31428. }
  31429. };
  31430. return SimplificationQueue;
  31431. })();
  31432. BABYLON.SimplificationQueue = SimplificationQueue;
  31433. /**
  31434. * The implemented types of simplification.
  31435. * At the moment only Quadratic Error Decimation is implemented.
  31436. */
  31437. (function (SimplificationType) {
  31438. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31439. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31440. var SimplificationType = BABYLON.SimplificationType;
  31441. var DecimationTriangle = (function () {
  31442. function DecimationTriangle(vertices) {
  31443. this.vertices = vertices;
  31444. this.error = new Array(4);
  31445. this.deleted = false;
  31446. this.isDirty = false;
  31447. this.deletePending = false;
  31448. this.borderFactor = 0;
  31449. }
  31450. return DecimationTriangle;
  31451. })();
  31452. BABYLON.DecimationTriangle = DecimationTriangle;
  31453. var DecimationVertex = (function () {
  31454. function DecimationVertex(position, id) {
  31455. this.position = position;
  31456. this.id = id;
  31457. this.isBorder = true;
  31458. this.q = new QuadraticMatrix();
  31459. this.triangleCount = 0;
  31460. this.triangleStart = 0;
  31461. this.originalOffsets = [];
  31462. }
  31463. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31464. this.position.copyFrom(newPosition);
  31465. };
  31466. return DecimationVertex;
  31467. })();
  31468. BABYLON.DecimationVertex = DecimationVertex;
  31469. var QuadraticMatrix = (function () {
  31470. function QuadraticMatrix(data) {
  31471. this.data = new Array(10);
  31472. for (var i = 0; i < 10; ++i) {
  31473. if (data && data[i]) {
  31474. this.data[i] = data[i];
  31475. }
  31476. else {
  31477. this.data[i] = 0;
  31478. }
  31479. }
  31480. }
  31481. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31482. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31483. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31484. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31485. return det;
  31486. };
  31487. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31488. for (var i = 0; i < 10; ++i) {
  31489. this.data[i] += matrix.data[i];
  31490. }
  31491. };
  31492. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31493. for (var i = 0; i < 10; ++i) {
  31494. this.data[i] += data[i];
  31495. }
  31496. };
  31497. QuadraticMatrix.prototype.add = function (matrix) {
  31498. var m = new QuadraticMatrix();
  31499. for (var i = 0; i < 10; ++i) {
  31500. m.data[i] = this.data[i] + matrix.data[i];
  31501. }
  31502. return m;
  31503. };
  31504. QuadraticMatrix.FromData = function (a, b, c, d) {
  31505. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31506. };
  31507. //returning an array to avoid garbage collection
  31508. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31509. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31510. };
  31511. return QuadraticMatrix;
  31512. })();
  31513. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31514. var Reference = (function () {
  31515. function Reference(vertexId, triangleId) {
  31516. this.vertexId = vertexId;
  31517. this.triangleId = triangleId;
  31518. }
  31519. return Reference;
  31520. })();
  31521. BABYLON.Reference = Reference;
  31522. /**
  31523. * An implementation of the Quadratic Error simplification algorithm.
  31524. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31525. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31526. * @author RaananW
  31527. */
  31528. var QuadraticErrorSimplification = (function () {
  31529. function QuadraticErrorSimplification(_mesh) {
  31530. this._mesh = _mesh;
  31531. this.initialized = false;
  31532. this.syncIterations = 5000;
  31533. this.aggressiveness = 7;
  31534. this.decimationIterations = 100;
  31535. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31536. }
  31537. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31538. var _this = this;
  31539. this.initDecimatedMesh();
  31540. //iterating through the submeshes array, one after the other.
  31541. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31542. _this.initWithMesh(loop.index, function () {
  31543. _this.runDecimation(settings, loop.index, function () {
  31544. loop.executeNext();
  31545. });
  31546. }, settings.optimizeMesh);
  31547. }, function () {
  31548. setTimeout(function () {
  31549. successCallback(_this._reconstructedMesh);
  31550. }, 0);
  31551. });
  31552. };
  31553. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31554. var _this = this;
  31555. var gCount = 0;
  31556. triangle.vertices.forEach(function (vertex) {
  31557. var count = 0;
  31558. var vPos = vertex.position;
  31559. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31560. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31561. ++count;
  31562. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31563. ++count;
  31564. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31565. ++count;
  31566. if (count > 1) {
  31567. ++gCount;
  31568. }
  31569. ;
  31570. });
  31571. if (gCount > 1) {
  31572. console.log(triangle, gCount);
  31573. }
  31574. return gCount > 1;
  31575. };
  31576. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31577. var _this = this;
  31578. var targetCount = ~~(this.triangles.length * settings.quality);
  31579. var deletedTriangles = 0;
  31580. var triangleCount = this.triangles.length;
  31581. var iterationFunction = function (iteration, callback) {
  31582. setTimeout(function () {
  31583. if (iteration % 5 === 0) {
  31584. _this.updateMesh(iteration === 0);
  31585. }
  31586. for (var i = 0; i < _this.triangles.length; ++i) {
  31587. _this.triangles[i].isDirty = false;
  31588. }
  31589. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31590. var trianglesIterator = function (i) {
  31591. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31592. var t = _this.triangles[tIdx];
  31593. if (!t)
  31594. return;
  31595. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31596. return;
  31597. }
  31598. for (var j = 0; j < 3; ++j) {
  31599. if (t.error[j] < threshold) {
  31600. var deleted0 = [];
  31601. var deleted1 = [];
  31602. var v0 = t.vertices[j];
  31603. var v1 = t.vertices[(j + 1) % 3];
  31604. if (v0.isBorder !== v1.isBorder)
  31605. continue;
  31606. var p = BABYLON.Vector3.Zero();
  31607. var n = BABYLON.Vector3.Zero();
  31608. var uv = BABYLON.Vector2.Zero();
  31609. var color = new BABYLON.Color4(0, 0, 0, 1);
  31610. _this.calculateError(v0, v1, p, n, uv, color);
  31611. var delTr = [];
  31612. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31613. continue;
  31614. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31615. continue;
  31616. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31617. continue;
  31618. var uniqueArray = [];
  31619. delTr.forEach(function (deletedT) {
  31620. if (uniqueArray.indexOf(deletedT) === -1) {
  31621. deletedT.deletePending = true;
  31622. uniqueArray.push(deletedT);
  31623. }
  31624. });
  31625. if (uniqueArray.length % 2 !== 0) {
  31626. continue;
  31627. }
  31628. v0.q = v1.q.add(v0.q);
  31629. v0.updatePosition(p);
  31630. var tStart = _this.references.length;
  31631. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31632. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31633. var tCount = _this.references.length - tStart;
  31634. if (tCount <= v0.triangleCount) {
  31635. if (tCount) {
  31636. for (var c = 0; c < tCount; c++) {
  31637. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31638. }
  31639. }
  31640. }
  31641. else {
  31642. v0.triangleStart = tStart;
  31643. }
  31644. v0.triangleCount = tCount;
  31645. break;
  31646. }
  31647. }
  31648. };
  31649. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31650. }, 0);
  31651. };
  31652. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31653. if (triangleCount - deletedTriangles <= targetCount)
  31654. loop.breakLoop();
  31655. else {
  31656. iterationFunction(loop.index, function () {
  31657. loop.executeNext();
  31658. });
  31659. }
  31660. }, function () {
  31661. setTimeout(function () {
  31662. //reconstruct this part of the mesh
  31663. _this.reconstructMesh(submeshIndex);
  31664. successCallback();
  31665. }, 0);
  31666. });
  31667. };
  31668. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31669. var _this = this;
  31670. this.vertices = [];
  31671. this.triangles = [];
  31672. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31673. var indices = this._mesh.getIndices();
  31674. var submesh = this._mesh.subMeshes[submeshIndex];
  31675. var findInVertices = function (positionToSearch) {
  31676. if (optimizeMesh) {
  31677. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31678. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31679. return _this.vertices[ii];
  31680. }
  31681. }
  31682. }
  31683. return null;
  31684. };
  31685. var vertexReferences = [];
  31686. var vertexInit = function (i) {
  31687. var offset = i + submesh.verticesStart;
  31688. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31689. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31690. vertex.originalOffsets.push(offset);
  31691. if (vertex.id === _this.vertices.length) {
  31692. _this.vertices.push(vertex);
  31693. }
  31694. vertexReferences.push(vertex.id);
  31695. };
  31696. //var totalVertices = mesh.getTotalVertices();
  31697. var totalVertices = submesh.verticesCount;
  31698. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31699. var indicesInit = function (i) {
  31700. var offset = (submesh.indexStart / 3) + i;
  31701. var pos = (offset * 3);
  31702. var i0 = indices[pos + 0];
  31703. var i1 = indices[pos + 1];
  31704. var i2 = indices[pos + 2];
  31705. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31706. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31707. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31708. var triangle = new DecimationTriangle([v0, v1, v2]);
  31709. triangle.originalOffset = pos;
  31710. _this.triangles.push(triangle);
  31711. };
  31712. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31713. _this.init(callback);
  31714. });
  31715. });
  31716. };
  31717. QuadraticErrorSimplification.prototype.init = function (callback) {
  31718. var _this = this;
  31719. var triangleInit1 = function (i) {
  31720. var t = _this.triangles[i];
  31721. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31722. for (var j = 0; j < 3; j++) {
  31723. 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))));
  31724. }
  31725. };
  31726. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31727. var triangleInit2 = function (i) {
  31728. var t = _this.triangles[i];
  31729. for (var j = 0; j < 3; ++j) {
  31730. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31731. }
  31732. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31733. };
  31734. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31735. _this.initialized = true;
  31736. callback();
  31737. });
  31738. });
  31739. };
  31740. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31741. var newTriangles = [];
  31742. var i;
  31743. for (i = 0; i < this.vertices.length; ++i) {
  31744. this.vertices[i].triangleCount = 0;
  31745. }
  31746. var t;
  31747. var j;
  31748. for (i = 0; i < this.triangles.length; ++i) {
  31749. if (!this.triangles[i].deleted) {
  31750. t = this.triangles[i];
  31751. for (j = 0; j < 3; ++j) {
  31752. t.vertices[j].triangleCount = 1;
  31753. }
  31754. newTriangles.push(t);
  31755. }
  31756. }
  31757. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31758. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31759. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31760. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31761. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31762. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31763. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31764. var vertexCount = 0;
  31765. for (i = 0; i < this.vertices.length; ++i) {
  31766. var vertex = this.vertices[i];
  31767. vertex.id = vertexCount;
  31768. if (vertex.triangleCount) {
  31769. vertex.originalOffsets.forEach(function (originalOffset) {
  31770. newPositionData.push(vertex.position.x);
  31771. newPositionData.push(vertex.position.y);
  31772. newPositionData.push(vertex.position.z);
  31773. newNormalData.push(normalData[originalOffset * 3]);
  31774. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31775. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31776. if (uvs && uvs.length) {
  31777. newUVsData.push(uvs[(originalOffset * 2)]);
  31778. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31779. }
  31780. else if (colorsData && colorsData.length) {
  31781. newColorsData.push(colorsData[(originalOffset * 4)]);
  31782. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31783. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31784. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31785. }
  31786. ++vertexCount;
  31787. });
  31788. }
  31789. }
  31790. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31791. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31792. var submeshesArray = this._reconstructedMesh.subMeshes;
  31793. this._reconstructedMesh.subMeshes = [];
  31794. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31795. var originalIndices = this._mesh.getIndices();
  31796. for (i = 0; i < newTriangles.length; ++i) {
  31797. t = newTriangles[i]; //now get the new referencing point for each vertex
  31798. [0, 1, 2].forEach(function (idx) {
  31799. var id = originalIndices[t.originalOffset + idx];
  31800. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31801. if (offset < 0)
  31802. offset = 0;
  31803. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31804. });
  31805. }
  31806. //overwriting the old vertex buffers and indices.
  31807. this._reconstructedMesh.setIndices(newIndicesArray);
  31808. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31809. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31810. if (newUVsData.length > 0)
  31811. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31812. if (newColorsData.length > 0)
  31813. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31814. //create submesh
  31815. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31816. if (submeshIndex > 0) {
  31817. this._reconstructedMesh.subMeshes = [];
  31818. submeshesArray.forEach(function (submesh) {
  31819. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31820. });
  31821. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31822. }
  31823. };
  31824. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31825. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31826. this._reconstructedMesh.material = this._mesh.material;
  31827. this._reconstructedMesh.parent = this._mesh.parent;
  31828. this._reconstructedMesh.isVisible = false;
  31829. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31830. };
  31831. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31832. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31833. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31834. if (t.deleted)
  31835. continue;
  31836. var s = this.references[vertex1.triangleStart + i].vertexId;
  31837. var v1 = t.vertices[(s + 1) % 3];
  31838. var v2 = t.vertices[(s + 2) % 3];
  31839. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31840. deletedArray[i] = true;
  31841. delTr.push(t);
  31842. continue;
  31843. }
  31844. var d1 = v1.position.subtract(point);
  31845. d1 = d1.normalize();
  31846. var d2 = v2.position.subtract(point);
  31847. d2 = d2.normalize();
  31848. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31849. return true;
  31850. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31851. deletedArray[i] = false;
  31852. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31853. return true;
  31854. }
  31855. return false;
  31856. };
  31857. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31858. var newDeleted = deletedTriangles;
  31859. for (var i = 0; i < vertex.triangleCount; ++i) {
  31860. var ref = this.references[vertex.triangleStart + i];
  31861. var t = this.triangles[ref.triangleId];
  31862. if (t.deleted)
  31863. continue;
  31864. if (deletedArray[i] && t.deletePending) {
  31865. t.deleted = true;
  31866. newDeleted++;
  31867. continue;
  31868. }
  31869. t.vertices[ref.vertexId] = origVertex;
  31870. t.isDirty = true;
  31871. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31872. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31873. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31874. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31875. this.references.push(ref);
  31876. }
  31877. return newDeleted;
  31878. };
  31879. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31880. for (var i = 0; i < this.vertices.length; ++i) {
  31881. var vCount = [];
  31882. var vId = [];
  31883. var v = this.vertices[i];
  31884. var j;
  31885. for (j = 0; j < v.triangleCount; ++j) {
  31886. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31887. for (var ii = 0; ii < 3; ii++) {
  31888. var ofs = 0;
  31889. var vv = triangle.vertices[ii];
  31890. while (ofs < vCount.length) {
  31891. if (vId[ofs] === vv.id)
  31892. break;
  31893. ++ofs;
  31894. }
  31895. if (ofs === vCount.length) {
  31896. vCount.push(1);
  31897. vId.push(vv.id);
  31898. }
  31899. else {
  31900. vCount[ofs]++;
  31901. }
  31902. }
  31903. }
  31904. for (j = 0; j < vCount.length; ++j) {
  31905. if (vCount[j] === 1) {
  31906. this.vertices[vId[j]].isBorder = true;
  31907. }
  31908. else {
  31909. this.vertices[vId[j]].isBorder = false;
  31910. }
  31911. }
  31912. }
  31913. };
  31914. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31915. if (identifyBorders === void 0) { identifyBorders = false; }
  31916. var i;
  31917. if (!identifyBorders) {
  31918. var newTrianglesVector = [];
  31919. for (i = 0; i < this.triangles.length; ++i) {
  31920. if (!this.triangles[i].deleted) {
  31921. newTrianglesVector.push(this.triangles[i]);
  31922. }
  31923. }
  31924. this.triangles = newTrianglesVector;
  31925. }
  31926. for (i = 0; i < this.vertices.length; ++i) {
  31927. this.vertices[i].triangleCount = 0;
  31928. this.vertices[i].triangleStart = 0;
  31929. }
  31930. var t;
  31931. var j;
  31932. var v;
  31933. for (i = 0; i < this.triangles.length; ++i) {
  31934. t = this.triangles[i];
  31935. for (j = 0; j < 3; ++j) {
  31936. v = t.vertices[j];
  31937. v.triangleCount++;
  31938. }
  31939. }
  31940. var tStart = 0;
  31941. for (i = 0; i < this.vertices.length; ++i) {
  31942. this.vertices[i].triangleStart = tStart;
  31943. tStart += this.vertices[i].triangleCount;
  31944. this.vertices[i].triangleCount = 0;
  31945. }
  31946. var newReferences = new Array(this.triangles.length * 3);
  31947. for (i = 0; i < this.triangles.length; ++i) {
  31948. t = this.triangles[i];
  31949. for (j = 0; j < 3; ++j) {
  31950. v = t.vertices[j];
  31951. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31952. v.triangleCount++;
  31953. }
  31954. }
  31955. this.references = newReferences;
  31956. if (identifyBorders) {
  31957. this.identifyBorder();
  31958. }
  31959. };
  31960. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31961. var x = point.x;
  31962. var y = point.y;
  31963. var z = point.z;
  31964. 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
  31965. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31966. };
  31967. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31968. var q = vertex1.q.add(vertex2.q);
  31969. var border = vertex1.isBorder && vertex2.isBorder;
  31970. var error = 0;
  31971. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31972. if (qDet !== 0 && !border) {
  31973. if (!pointResult) {
  31974. pointResult = BABYLON.Vector3.Zero();
  31975. }
  31976. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31977. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31978. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31979. error = this.vertexError(q, pointResult);
  31980. }
  31981. else {
  31982. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31983. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31984. var error1 = this.vertexError(q, vertex1.position);
  31985. var error2 = this.vertexError(q, vertex2.position);
  31986. var error3 = this.vertexError(q, p3);
  31987. error = Math.min(error1, error2, error3);
  31988. if (error === error1) {
  31989. if (pointResult) {
  31990. pointResult.copyFrom(vertex1.position);
  31991. }
  31992. }
  31993. else if (error === error2) {
  31994. if (pointResult) {
  31995. pointResult.copyFrom(vertex2.position);
  31996. }
  31997. }
  31998. else {
  31999. if (pointResult) {
  32000. pointResult.copyFrom(p3);
  32001. }
  32002. }
  32003. }
  32004. return error;
  32005. };
  32006. return QuadraticErrorSimplification;
  32007. })();
  32008. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32009. })(BABYLON || (BABYLON = {}));
  32010. var BABYLON;
  32011. (function (BABYLON) {
  32012. var serializedGeometries = [];
  32013. var serializeGeometry = function (geometry, serializationGeometries) {
  32014. if (serializedGeometries[geometry.id]) {
  32015. return;
  32016. }
  32017. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32018. serializationGeometries.boxes.push(geometry.serialize());
  32019. }
  32020. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32021. serializationGeometries.spheres.push(geometry.serialize());
  32022. }
  32023. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32024. serializationGeometries.cylinders.push(geometry.serialize());
  32025. }
  32026. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32027. serializationGeometries.toruses.push(geometry.serialize());
  32028. }
  32029. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32030. serializationGeometries.grounds.push(geometry.serialize());
  32031. }
  32032. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32033. serializationGeometries.planes.push(geometry.serialize());
  32034. }
  32035. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32036. serializationGeometries.torusKnots.push(geometry.serialize());
  32037. }
  32038. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32039. throw new Error("Unknown primitive type");
  32040. }
  32041. else {
  32042. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32043. }
  32044. serializedGeometries[geometry.id] = true;
  32045. };
  32046. var serializeMesh = function (mesh, serializationScene) {
  32047. var serializationObject = {};
  32048. serializationObject.name = mesh.name;
  32049. serializationObject.id = mesh.id;
  32050. if (BABYLON.Tags.HasTags(mesh)) {
  32051. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32052. }
  32053. serializationObject.position = mesh.position.asArray();
  32054. if (mesh.rotationQuaternion) {
  32055. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32056. }
  32057. else if (mesh.rotation) {
  32058. serializationObject.rotation = mesh.rotation.asArray();
  32059. }
  32060. serializationObject.scaling = mesh.scaling.asArray();
  32061. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32062. serializationObject.isEnabled = mesh.isEnabled();
  32063. serializationObject.isVisible = mesh.isVisible;
  32064. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32065. serializationObject.pickable = mesh.isPickable;
  32066. serializationObject.receiveShadows = mesh.receiveShadows;
  32067. serializationObject.billboardMode = mesh.billboardMode;
  32068. serializationObject.visibility = mesh.visibility;
  32069. serializationObject.checkCollisions = mesh.checkCollisions;
  32070. // Parent
  32071. if (mesh.parent) {
  32072. serializationObject.parentId = mesh.parent.id;
  32073. }
  32074. // Geometry
  32075. var geometry = mesh._geometry;
  32076. if (geometry) {
  32077. var geometryId = geometry.id;
  32078. serializationObject.geometryId = geometryId;
  32079. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32080. // 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
  32081. serializeGeometry(geometry, serializationScene.geometries);
  32082. }
  32083. // SubMeshes
  32084. serializationObject.subMeshes = [];
  32085. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32086. var subMesh = mesh.subMeshes[subIndex];
  32087. serializationObject.subMeshes.push({
  32088. materialIndex: subMesh.materialIndex,
  32089. verticesStart: subMesh.verticesStart,
  32090. verticesCount: subMesh.verticesCount,
  32091. indexStart: subMesh.indexStart,
  32092. indexCount: subMesh.indexCount
  32093. });
  32094. }
  32095. }
  32096. // Material
  32097. if (mesh.material) {
  32098. serializationObject.materialId = mesh.material.id;
  32099. }
  32100. else {
  32101. mesh.material = null;
  32102. }
  32103. // Skeleton
  32104. if (mesh.skeleton) {
  32105. serializationObject.skeletonId = mesh.skeleton.id;
  32106. }
  32107. // Physics
  32108. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32109. serializationObject.physicsMass = mesh.getPhysicsMass();
  32110. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32111. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32112. switch (mesh.getPhysicsImpostor().type) {
  32113. case BABYLON.PhysicsEngine.BoxImpostor:
  32114. serializationObject.physicsImpostor = 1;
  32115. break;
  32116. case BABYLON.PhysicsEngine.SphereImpostor:
  32117. serializationObject.physicsImpostor = 2;
  32118. break;
  32119. }
  32120. }
  32121. // Instances
  32122. serializationObject.instances = [];
  32123. for (var index = 0; index < mesh.instances.length; index++) {
  32124. var instance = mesh.instances[index];
  32125. var serializationInstance = {
  32126. name: instance.name,
  32127. position: instance.position.asArray(),
  32128. scaling: instance.scaling.asArray()
  32129. };
  32130. if (instance.rotationQuaternion) {
  32131. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32132. }
  32133. else if (instance.rotation) {
  32134. serializationInstance.rotation = instance.rotation.asArray();
  32135. }
  32136. serializationObject.instances.push(serializationInstance);
  32137. // Animations
  32138. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32139. serializationInstance.ranges = instance.serializeAnimationRanges();
  32140. }
  32141. // Animations
  32142. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32143. serializationObject.ranges = mesh.serializeAnimationRanges();
  32144. // Layer mask
  32145. serializationObject.layerMask = mesh.layerMask;
  32146. return serializationObject;
  32147. };
  32148. var finalizeSingleMesh = function (mesh, serializationObject) {
  32149. //only works if the mesh is already loaded
  32150. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32151. //serialize material
  32152. if (mesh.material) {
  32153. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32154. serializationObject.materials = serializationObject.materials || [];
  32155. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32156. serializationObject.materials.push(mesh.material.serialize());
  32157. }
  32158. }
  32159. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32160. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32161. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32162. serializationObject.multiMaterials.push(mesh.material.serialize());
  32163. }
  32164. }
  32165. }
  32166. //serialize geometry
  32167. var geometry = mesh._geometry;
  32168. if (geometry) {
  32169. if (!serializationObject.geometries) {
  32170. serializationObject.geometries = {};
  32171. serializationObject.geometries.boxes = [];
  32172. serializationObject.geometries.spheres = [];
  32173. serializationObject.geometries.cylinders = [];
  32174. serializationObject.geometries.toruses = [];
  32175. serializationObject.geometries.grounds = [];
  32176. serializationObject.geometries.planes = [];
  32177. serializationObject.geometries.torusKnots = [];
  32178. serializationObject.geometries.vertexData = [];
  32179. }
  32180. serializeGeometry(geometry, serializationObject.geometries);
  32181. }
  32182. // Skeletons
  32183. if (mesh.skeleton) {
  32184. serializationObject.skeletons = serializationObject.skeletons || [];
  32185. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32186. }
  32187. //serialize the actual mesh
  32188. serializationObject.meshes = serializationObject.meshes || [];
  32189. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32190. }
  32191. };
  32192. var SceneSerializer = (function () {
  32193. function SceneSerializer() {
  32194. }
  32195. SceneSerializer.ClearCache = function () {
  32196. serializedGeometries = [];
  32197. };
  32198. SceneSerializer.Serialize = function (scene) {
  32199. var serializationObject = {};
  32200. // Scene
  32201. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32202. serializationObject.autoClear = scene.autoClear;
  32203. serializationObject.clearColor = scene.clearColor.asArray();
  32204. serializationObject.ambientColor = scene.ambientColor.asArray();
  32205. serializationObject.gravity = scene.gravity.asArray();
  32206. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32207. serializationObject.workerCollisions = scene.workerCollisions;
  32208. // Fog
  32209. if (scene.fogMode && scene.fogMode !== 0) {
  32210. serializationObject.fogMode = scene.fogMode;
  32211. serializationObject.fogColor = scene.fogColor.asArray();
  32212. serializationObject.fogStart = scene.fogStart;
  32213. serializationObject.fogEnd = scene.fogEnd;
  32214. serializationObject.fogDensity = scene.fogDensity;
  32215. }
  32216. //Physics
  32217. if (scene.isPhysicsEnabled()) {
  32218. serializationObject.physicsEnabled = true;
  32219. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32220. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32221. }
  32222. // Lights
  32223. serializationObject.lights = [];
  32224. var index;
  32225. var light;
  32226. for (index = 0; index < scene.lights.length; index++) {
  32227. light = scene.lights[index];
  32228. serializationObject.lights.push(light.serialize());
  32229. }
  32230. // Cameras
  32231. serializationObject.cameras = [];
  32232. for (index = 0; index < scene.cameras.length; index++) {
  32233. var camera = scene.cameras[index];
  32234. serializationObject.cameras.push(camera.serialize());
  32235. }
  32236. if (scene.activeCamera) {
  32237. serializationObject.activeCameraID = scene.activeCamera.id;
  32238. }
  32239. // Animations
  32240. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32241. // Materials
  32242. serializationObject.materials = [];
  32243. serializationObject.multiMaterials = [];
  32244. var material;
  32245. for (index = 0; index < scene.materials.length; index++) {
  32246. material = scene.materials[index];
  32247. serializationObject.materials.push(material.serialize());
  32248. }
  32249. // MultiMaterials
  32250. serializationObject.multiMaterials = [];
  32251. for (index = 0; index < scene.multiMaterials.length; index++) {
  32252. var multiMaterial = scene.multiMaterials[index];
  32253. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32254. }
  32255. // Skeletons
  32256. serializationObject.skeletons = [];
  32257. for (index = 0; index < scene.skeletons.length; index++) {
  32258. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32259. }
  32260. // Geometries
  32261. serializationObject.geometries = {};
  32262. serializationObject.geometries.boxes = [];
  32263. serializationObject.geometries.spheres = [];
  32264. serializationObject.geometries.cylinders = [];
  32265. serializationObject.geometries.toruses = [];
  32266. serializationObject.geometries.grounds = [];
  32267. serializationObject.geometries.planes = [];
  32268. serializationObject.geometries.torusKnots = [];
  32269. serializationObject.geometries.vertexData = [];
  32270. serializedGeometries = [];
  32271. var geometries = scene.getGeometries();
  32272. for (index = 0; index < geometries.length; index++) {
  32273. var geometry = geometries[index];
  32274. if (geometry.isReady()) {
  32275. serializeGeometry(geometry, serializationObject.geometries);
  32276. }
  32277. }
  32278. // Meshes
  32279. serializationObject.meshes = [];
  32280. for (index = 0; index < scene.meshes.length; index++) {
  32281. var abstractMesh = scene.meshes[index];
  32282. if (abstractMesh instanceof BABYLON.Mesh) {
  32283. var mesh = abstractMesh;
  32284. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32285. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32286. }
  32287. }
  32288. }
  32289. // Particles Systems
  32290. serializationObject.particleSystems = [];
  32291. for (index = 0; index < scene.particleSystems.length; index++) {
  32292. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32293. }
  32294. // Lens flares
  32295. serializationObject.lensFlareSystems = [];
  32296. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32297. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32298. }
  32299. // Shadows
  32300. serializationObject.shadowGenerators = [];
  32301. for (index = 0; index < scene.lights.length; index++) {
  32302. light = scene.lights[index];
  32303. if (light.getShadowGenerator()) {
  32304. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32305. }
  32306. }
  32307. return serializationObject;
  32308. };
  32309. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32310. if (withParents === void 0) { withParents = false; }
  32311. if (withChildren === void 0) { withChildren = false; }
  32312. var serializationObject = {};
  32313. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32314. if (withParents || withChildren) {
  32315. //deliberate for loop! not for each, appended should be processed as well.
  32316. for (var i = 0; i < toSerialize.length; ++i) {
  32317. if (withChildren) {
  32318. toSerialize[i].getDescendants().forEach(function (node) {
  32319. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32320. toSerialize.push(node);
  32321. }
  32322. });
  32323. }
  32324. //make sure the array doesn't contain the object already
  32325. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32326. toSerialize.push(toSerialize[i].parent);
  32327. }
  32328. }
  32329. }
  32330. toSerialize.forEach(function (mesh) {
  32331. finalizeSingleMesh(mesh, serializationObject);
  32332. });
  32333. return serializationObject;
  32334. };
  32335. return SceneSerializer;
  32336. })();
  32337. BABYLON.SceneSerializer = SceneSerializer;
  32338. })(BABYLON || (BABYLON = {}));
  32339. var BABYLON;
  32340. (function (BABYLON) {
  32341. // Unique ID when we import meshes from Babylon to CSG
  32342. var currentCSGMeshId = 0;
  32343. // # class Vertex
  32344. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32345. // one to provide additional features like texture coordinates and vertex
  32346. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32347. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32348. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32349. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32350. // is not used anywhere else.
  32351. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32352. var Vertex = (function () {
  32353. function Vertex(pos, normal, uv) {
  32354. this.pos = pos;
  32355. this.normal = normal;
  32356. this.uv = uv;
  32357. }
  32358. Vertex.prototype.clone = function () {
  32359. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32360. };
  32361. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32362. // orientation of a polygon is flipped.
  32363. Vertex.prototype.flip = function () {
  32364. this.normal = this.normal.scale(-1);
  32365. };
  32366. // Create a new vertex between this vertex and `other` by linearly
  32367. // interpolating all properties using a parameter of `t`. Subclasses should
  32368. // override this to interpolate additional properties.
  32369. Vertex.prototype.interpolate = function (other, t) {
  32370. 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));
  32371. };
  32372. return Vertex;
  32373. })();
  32374. // # class Plane
  32375. // Represents a plane in 3D space.
  32376. var Plane = (function () {
  32377. function Plane(normal, w) {
  32378. this.normal = normal;
  32379. this.w = w;
  32380. }
  32381. Plane.FromPoints = function (a, b, c) {
  32382. var v0 = c.subtract(a);
  32383. var v1 = b.subtract(a);
  32384. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32385. return null;
  32386. }
  32387. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32388. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32389. };
  32390. Plane.prototype.clone = function () {
  32391. return new Plane(this.normal.clone(), this.w);
  32392. };
  32393. Plane.prototype.flip = function () {
  32394. this.normal.scaleInPlace(-1);
  32395. this.w = -this.w;
  32396. };
  32397. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32398. // fragments in the appropriate lists. Coplanar polygons go into either
  32399. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32400. // respect to this plane. Polygons in front or in back of this plane go into
  32401. // either `front` or `back`.
  32402. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32403. var COPLANAR = 0;
  32404. var FRONT = 1;
  32405. var BACK = 2;
  32406. var SPANNING = 3;
  32407. // Classify each point as well as the entire polygon into one of the above
  32408. // four classes.
  32409. var polygonType = 0;
  32410. var types = [];
  32411. var i;
  32412. var t;
  32413. for (i = 0; i < polygon.vertices.length; i++) {
  32414. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32415. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32416. polygonType |= type;
  32417. types.push(type);
  32418. }
  32419. // Put the polygon in the correct list, splitting it when necessary.
  32420. switch (polygonType) {
  32421. case COPLANAR:
  32422. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32423. break;
  32424. case FRONT:
  32425. front.push(polygon);
  32426. break;
  32427. case BACK:
  32428. back.push(polygon);
  32429. break;
  32430. case SPANNING:
  32431. var f = [], b = [];
  32432. for (i = 0; i < polygon.vertices.length; i++) {
  32433. var j = (i + 1) % polygon.vertices.length;
  32434. var ti = types[i], tj = types[j];
  32435. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32436. if (ti !== BACK)
  32437. f.push(vi);
  32438. if (ti !== FRONT)
  32439. b.push(ti !== BACK ? vi.clone() : vi);
  32440. if ((ti | tj) === SPANNING) {
  32441. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32442. var v = vi.interpolate(vj, t);
  32443. f.push(v);
  32444. b.push(v.clone());
  32445. }
  32446. }
  32447. var poly;
  32448. if (f.length >= 3) {
  32449. poly = new Polygon(f, polygon.shared);
  32450. if (poly.plane)
  32451. front.push(poly);
  32452. }
  32453. if (b.length >= 3) {
  32454. poly = new Polygon(b, polygon.shared);
  32455. if (poly.plane)
  32456. back.push(poly);
  32457. }
  32458. break;
  32459. }
  32460. };
  32461. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32462. // point is on the plane.
  32463. Plane.EPSILON = 1e-5;
  32464. return Plane;
  32465. })();
  32466. // # class Polygon
  32467. // Represents a convex polygon. The vertices used to initialize a polygon must
  32468. // be coplanar and form a convex loop.
  32469. //
  32470. // Each convex polygon has a `shared` property, which is shared between all
  32471. // polygons that are clones of each other or were split from the same polygon.
  32472. // This can be used to define per-polygon properties (such as surface color).
  32473. var Polygon = (function () {
  32474. function Polygon(vertices, shared) {
  32475. this.vertices = vertices;
  32476. this.shared = shared;
  32477. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32478. }
  32479. Polygon.prototype.clone = function () {
  32480. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32481. return new Polygon(vertices, this.shared);
  32482. };
  32483. Polygon.prototype.flip = function () {
  32484. this.vertices.reverse().map(function (v) { v.flip(); });
  32485. this.plane.flip();
  32486. };
  32487. return Polygon;
  32488. })();
  32489. // # class Node
  32490. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32491. // by picking a polygon to split along. That polygon (and all other coplanar
  32492. // polygons) are added directly to that node and the other polygons are added to
  32493. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32494. // no distinction between internal and leaf nodes.
  32495. var Node = (function () {
  32496. function Node(polygons) {
  32497. this.plane = null;
  32498. this.front = null;
  32499. this.back = null;
  32500. this.polygons = [];
  32501. if (polygons) {
  32502. this.build(polygons);
  32503. }
  32504. }
  32505. Node.prototype.clone = function () {
  32506. var node = new Node();
  32507. node.plane = this.plane && this.plane.clone();
  32508. node.front = this.front && this.front.clone();
  32509. node.back = this.back && this.back.clone();
  32510. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32511. return node;
  32512. };
  32513. // Convert solid space to empty space and empty space to solid space.
  32514. Node.prototype.invert = function () {
  32515. for (var i = 0; i < this.polygons.length; i++) {
  32516. this.polygons[i].flip();
  32517. }
  32518. if (this.plane) {
  32519. this.plane.flip();
  32520. }
  32521. if (this.front) {
  32522. this.front.invert();
  32523. }
  32524. if (this.back) {
  32525. this.back.invert();
  32526. }
  32527. var temp = this.front;
  32528. this.front = this.back;
  32529. this.back = temp;
  32530. };
  32531. // Recursively remove all polygons in `polygons` that are inside this BSP
  32532. // tree.
  32533. Node.prototype.clipPolygons = function (polygons) {
  32534. if (!this.plane)
  32535. return polygons.slice();
  32536. var front = [], back = [];
  32537. for (var i = 0; i < polygons.length; i++) {
  32538. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32539. }
  32540. if (this.front) {
  32541. front = this.front.clipPolygons(front);
  32542. }
  32543. if (this.back) {
  32544. back = this.back.clipPolygons(back);
  32545. }
  32546. else {
  32547. back = [];
  32548. }
  32549. return front.concat(back);
  32550. };
  32551. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32552. // `bsp`.
  32553. Node.prototype.clipTo = function (bsp) {
  32554. this.polygons = bsp.clipPolygons(this.polygons);
  32555. if (this.front)
  32556. this.front.clipTo(bsp);
  32557. if (this.back)
  32558. this.back.clipTo(bsp);
  32559. };
  32560. // Return a list of all polygons in this BSP tree.
  32561. Node.prototype.allPolygons = function () {
  32562. var polygons = this.polygons.slice();
  32563. if (this.front)
  32564. polygons = polygons.concat(this.front.allPolygons());
  32565. if (this.back)
  32566. polygons = polygons.concat(this.back.allPolygons());
  32567. return polygons;
  32568. };
  32569. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32570. // new polygons are filtered down to the bottom of the tree and become new
  32571. // nodes there. Each set of polygons is partitioned using the first polygon
  32572. // (no heuristic is used to pick a good split).
  32573. Node.prototype.build = function (polygons) {
  32574. if (!polygons.length)
  32575. return;
  32576. if (!this.plane)
  32577. this.plane = polygons[0].plane.clone();
  32578. var front = [], back = [];
  32579. for (var i = 0; i < polygons.length; i++) {
  32580. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32581. }
  32582. if (front.length) {
  32583. if (!this.front)
  32584. this.front = new Node();
  32585. this.front.build(front);
  32586. }
  32587. if (back.length) {
  32588. if (!this.back)
  32589. this.back = new Node();
  32590. this.back.build(back);
  32591. }
  32592. };
  32593. return Node;
  32594. })();
  32595. var CSG = (function () {
  32596. function CSG() {
  32597. this.polygons = new Array();
  32598. }
  32599. // Convert BABYLON.Mesh to BABYLON.CSG
  32600. CSG.FromMesh = function (mesh) {
  32601. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32602. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32603. if (mesh instanceof BABYLON.Mesh) {
  32604. mesh.computeWorldMatrix(true);
  32605. matrix = mesh.getWorldMatrix();
  32606. meshPosition = mesh.position.clone();
  32607. meshRotation = mesh.rotation.clone();
  32608. if (mesh.rotationQuaternion) {
  32609. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32610. }
  32611. meshScaling = mesh.scaling.clone();
  32612. }
  32613. else {
  32614. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32615. }
  32616. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32617. var subMeshes = mesh.subMeshes;
  32618. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32619. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32620. vertices = [];
  32621. for (var j = 0; j < 3; j++) {
  32622. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32623. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32624. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32625. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32626. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32627. vertex = new Vertex(position, normal, uv);
  32628. vertices.push(vertex);
  32629. }
  32630. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32631. // To handle the case of degenerated triangle
  32632. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32633. if (polygon.plane)
  32634. polygons.push(polygon);
  32635. }
  32636. }
  32637. var csg = CSG.FromPolygons(polygons);
  32638. csg.matrix = matrix;
  32639. csg.position = meshPosition;
  32640. csg.rotation = meshRotation;
  32641. csg.scaling = meshScaling;
  32642. csg.rotationQuaternion = meshRotationQuaternion;
  32643. currentCSGMeshId++;
  32644. return csg;
  32645. };
  32646. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32647. CSG.FromPolygons = function (polygons) {
  32648. var csg = new CSG();
  32649. csg.polygons = polygons;
  32650. return csg;
  32651. };
  32652. CSG.prototype.clone = function () {
  32653. var csg = new CSG();
  32654. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32655. csg.copyTransformAttributes(this);
  32656. return csg;
  32657. };
  32658. CSG.prototype.toPolygons = function () {
  32659. return this.polygons;
  32660. };
  32661. CSG.prototype.union = function (csg) {
  32662. var a = new Node(this.clone().polygons);
  32663. var b = new Node(csg.clone().polygons);
  32664. a.clipTo(b);
  32665. b.clipTo(a);
  32666. b.invert();
  32667. b.clipTo(a);
  32668. b.invert();
  32669. a.build(b.allPolygons());
  32670. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32671. };
  32672. CSG.prototype.unionInPlace = function (csg) {
  32673. var a = new Node(this.polygons);
  32674. var b = new Node(csg.polygons);
  32675. a.clipTo(b);
  32676. b.clipTo(a);
  32677. b.invert();
  32678. b.clipTo(a);
  32679. b.invert();
  32680. a.build(b.allPolygons());
  32681. this.polygons = a.allPolygons();
  32682. };
  32683. CSG.prototype.subtract = function (csg) {
  32684. var a = new Node(this.clone().polygons);
  32685. var b = new Node(csg.clone().polygons);
  32686. a.invert();
  32687. a.clipTo(b);
  32688. b.clipTo(a);
  32689. b.invert();
  32690. b.clipTo(a);
  32691. b.invert();
  32692. a.build(b.allPolygons());
  32693. a.invert();
  32694. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32695. };
  32696. CSG.prototype.subtractInPlace = function (csg) {
  32697. var a = new Node(this.polygons);
  32698. var b = new Node(csg.polygons);
  32699. a.invert();
  32700. a.clipTo(b);
  32701. b.clipTo(a);
  32702. b.invert();
  32703. b.clipTo(a);
  32704. b.invert();
  32705. a.build(b.allPolygons());
  32706. a.invert();
  32707. this.polygons = a.allPolygons();
  32708. };
  32709. CSG.prototype.intersect = function (csg) {
  32710. var a = new Node(this.clone().polygons);
  32711. var b = new Node(csg.clone().polygons);
  32712. a.invert();
  32713. b.clipTo(a);
  32714. b.invert();
  32715. a.clipTo(b);
  32716. b.clipTo(a);
  32717. a.build(b.allPolygons());
  32718. a.invert();
  32719. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32720. };
  32721. CSG.prototype.intersectInPlace = function (csg) {
  32722. var a = new Node(this.polygons);
  32723. var b = new Node(csg.polygons);
  32724. a.invert();
  32725. b.clipTo(a);
  32726. b.invert();
  32727. a.clipTo(b);
  32728. b.clipTo(a);
  32729. a.build(b.allPolygons());
  32730. a.invert();
  32731. this.polygons = a.allPolygons();
  32732. };
  32733. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32734. // not modified.
  32735. CSG.prototype.inverse = function () {
  32736. var csg = this.clone();
  32737. csg.inverseInPlace();
  32738. return csg;
  32739. };
  32740. CSG.prototype.inverseInPlace = function () {
  32741. this.polygons.map(function (p) { p.flip(); });
  32742. };
  32743. // This is used to keep meshes transformations so they can be restored
  32744. // when we build back a Babylon Mesh
  32745. // NB : All CSG operations are performed in world coordinates
  32746. CSG.prototype.copyTransformAttributes = function (csg) {
  32747. this.matrix = csg.matrix;
  32748. this.position = csg.position;
  32749. this.rotation = csg.rotation;
  32750. this.scaling = csg.scaling;
  32751. this.rotationQuaternion = csg.rotationQuaternion;
  32752. return this;
  32753. };
  32754. // Build Raw mesh from CSG
  32755. // Coordinates here are in world space
  32756. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32757. var matrix = this.matrix.clone();
  32758. matrix.invert();
  32759. 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;
  32760. if (keepSubMeshes) {
  32761. // Sort Polygons, since subMeshes are indices range
  32762. polygons.sort(function (a, b) {
  32763. if (a.shared.meshId === b.shared.meshId) {
  32764. return a.shared.subMeshId - b.shared.subMeshId;
  32765. }
  32766. else {
  32767. return a.shared.meshId - b.shared.meshId;
  32768. }
  32769. });
  32770. }
  32771. for (var i = 0, il = polygons.length; i < il; i++) {
  32772. polygon = polygons[i];
  32773. // Building SubMeshes
  32774. if (!subMesh_dict[polygon.shared.meshId]) {
  32775. subMesh_dict[polygon.shared.meshId] = {};
  32776. }
  32777. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32778. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32779. indexStart: +Infinity,
  32780. indexEnd: -Infinity,
  32781. materialIndex: polygon.shared.materialIndex
  32782. };
  32783. }
  32784. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32785. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32786. polygonIndices[0] = 0;
  32787. polygonIndices[1] = j - 1;
  32788. polygonIndices[2] = j;
  32789. for (var k = 0; k < 3; k++) {
  32790. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32791. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32792. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32793. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32794. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32795. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32796. // Check if 2 points can be merged
  32797. if (!(typeof vertex_idx !== 'undefined' &&
  32798. normals[vertex_idx * 3] === localNormal.x &&
  32799. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32800. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32801. uvs[vertex_idx * 2] === uv.x &&
  32802. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32803. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32804. uvs.push(uv.x, uv.y);
  32805. normals.push(normal.x, normal.y, normal.z);
  32806. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32807. }
  32808. indices.push(vertex_idx);
  32809. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32810. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32811. currentIndex++;
  32812. }
  32813. }
  32814. }
  32815. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32816. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32817. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32818. mesh.setIndices(indices);
  32819. if (keepSubMeshes) {
  32820. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32821. var materialIndexOffset = 0, materialMaxIndex;
  32822. mesh.subMeshes = new Array();
  32823. for (var m in subMesh_dict) {
  32824. materialMaxIndex = -1;
  32825. for (var sm in subMesh_dict[m]) {
  32826. subMesh_obj = subMesh_dict[m][sm];
  32827. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32828. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32829. }
  32830. materialIndexOffset += ++materialMaxIndex;
  32831. }
  32832. }
  32833. return mesh;
  32834. };
  32835. // Build Mesh from CSG taking material and transforms into account
  32836. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32837. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32838. mesh.material = material;
  32839. mesh.position.copyFrom(this.position);
  32840. mesh.rotation.copyFrom(this.rotation);
  32841. if (this.rotationQuaternion) {
  32842. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32843. }
  32844. mesh.scaling.copyFrom(this.scaling);
  32845. mesh.computeWorldMatrix(true);
  32846. return mesh;
  32847. };
  32848. return CSG;
  32849. })();
  32850. BABYLON.CSG = CSG;
  32851. })(BABYLON || (BABYLON = {}));
  32852. var BABYLON;
  32853. (function (BABYLON) {
  32854. var VRDistortionCorrectionPostProcess = (function (_super) {
  32855. __extends(VRDistortionCorrectionPostProcess, _super);
  32856. //ANY
  32857. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32858. var _this = this;
  32859. _super.call(this, name, "vrDistortionCorrection", [
  32860. 'LensCenter',
  32861. 'Scale',
  32862. 'ScaleIn',
  32863. 'HmdWarpParam'
  32864. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32865. this._isRightEye = isRightEye;
  32866. this._distortionFactors = vrMetrics.distortionK;
  32867. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32868. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32869. this.onSizeChanged = function () {
  32870. _this.aspectRatio = _this.width * .5 / _this.height;
  32871. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32872. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32873. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32874. };
  32875. this.onApply = function (effect) {
  32876. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32877. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32878. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32879. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32880. };
  32881. }
  32882. return VRDistortionCorrectionPostProcess;
  32883. })(BABYLON.PostProcess);
  32884. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32885. })(BABYLON || (BABYLON = {}));
  32886. // Mainly based on these 2 articles :
  32887. // 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
  32888. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32889. var BABYLON;
  32890. (function (BABYLON) {
  32891. (function (JoystickAxis) {
  32892. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32893. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32894. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32895. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32896. var JoystickAxis = BABYLON.JoystickAxis;
  32897. var VirtualJoystick = (function () {
  32898. function VirtualJoystick(leftJoystick) {
  32899. var _this = this;
  32900. if (leftJoystick) {
  32901. this._leftJoystick = true;
  32902. }
  32903. else {
  32904. this._leftJoystick = false;
  32905. }
  32906. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32907. VirtualJoystick._globalJoystickIndex++;
  32908. // By default left & right arrow keys are moving the X
  32909. // and up & down keys are moving the Y
  32910. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32911. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32912. this.reverseLeftRight = false;
  32913. this.reverseUpDown = false;
  32914. // collections of pointers
  32915. this._touches = new BABYLON.SmartCollection();
  32916. this.deltaPosition = BABYLON.Vector3.Zero();
  32917. this._joystickSensibility = 25;
  32918. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32919. this._rotationSpeed = 25;
  32920. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32921. this._rotateOnAxisRelativeToMesh = false;
  32922. this._onResize = function (evt) {
  32923. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32924. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32925. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32926. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32927. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32928. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32929. };
  32930. // injecting a canvas element on top of the canvas 3D game
  32931. if (!VirtualJoystick.vjCanvas) {
  32932. window.addEventListener("resize", this._onResize, false);
  32933. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32934. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32935. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32936. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32937. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32938. VirtualJoystick.vjCanvas.style.width = "100%";
  32939. VirtualJoystick.vjCanvas.style.height = "100%";
  32940. VirtualJoystick.vjCanvas.style.position = "absolute";
  32941. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32942. VirtualJoystick.vjCanvas.style.top = "0px";
  32943. VirtualJoystick.vjCanvas.style.left = "0px";
  32944. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32945. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32946. // Support for jQuery PEP polyfill
  32947. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32948. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32949. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32950. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32951. document.body.appendChild(VirtualJoystick.vjCanvas);
  32952. }
  32953. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32954. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32955. this.pressed = false;
  32956. // default joystick color
  32957. this._joystickColor = "cyan";
  32958. this._joystickPointerID = -1;
  32959. // current joystick position
  32960. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32961. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32962. // origin joystick position
  32963. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32964. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32965. this._onPointerDownHandlerRef = function (evt) {
  32966. _this._onPointerDown(evt);
  32967. };
  32968. this._onPointerMoveHandlerRef = function (evt) {
  32969. _this._onPointerMove(evt);
  32970. };
  32971. this._onPointerOutHandlerRef = function (evt) {
  32972. _this._onPointerUp(evt);
  32973. };
  32974. this._onPointerUpHandlerRef = function (evt) {
  32975. _this._onPointerUp(evt);
  32976. };
  32977. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32978. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32979. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32980. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32981. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32982. evt.preventDefault(); // Disables system menu
  32983. }, false);
  32984. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32985. }
  32986. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32987. this._joystickSensibility = newJoystickSensibility;
  32988. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32989. };
  32990. VirtualJoystick.prototype._onPointerDown = function (e) {
  32991. var positionOnScreenCondition;
  32992. e.preventDefault();
  32993. if (this._leftJoystick === true) {
  32994. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32995. }
  32996. else {
  32997. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32998. }
  32999. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33000. // First contact will be dedicated to the virtual joystick
  33001. this._joystickPointerID = e.pointerId;
  33002. this._joystickPointerStartPos.x = e.clientX;
  33003. this._joystickPointerStartPos.y = e.clientY;
  33004. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33005. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33006. this._deltaJoystickVector.x = 0;
  33007. this._deltaJoystickVector.y = 0;
  33008. this.pressed = true;
  33009. this._touches.add(e.pointerId.toString(), e);
  33010. }
  33011. else {
  33012. // You can only trigger the action buttons with a joystick declared
  33013. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33014. this._action();
  33015. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33016. }
  33017. }
  33018. };
  33019. VirtualJoystick.prototype._onPointerMove = function (e) {
  33020. // If the current pointer is the one associated to the joystick (first touch contact)
  33021. if (this._joystickPointerID == e.pointerId) {
  33022. this._joystickPointerPos.x = e.clientX;
  33023. this._joystickPointerPos.y = e.clientY;
  33024. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33025. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33026. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33027. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33028. switch (this._axisTargetedByLeftAndRight) {
  33029. case JoystickAxis.X:
  33030. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33031. break;
  33032. case JoystickAxis.Y:
  33033. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33034. break;
  33035. case JoystickAxis.Z:
  33036. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33037. break;
  33038. }
  33039. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33040. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33041. switch (this._axisTargetedByUpAndDown) {
  33042. case JoystickAxis.X:
  33043. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33044. break;
  33045. case JoystickAxis.Y:
  33046. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33047. break;
  33048. case JoystickAxis.Z:
  33049. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33050. break;
  33051. }
  33052. }
  33053. else {
  33054. if (this._touches.item(e.pointerId.toString())) {
  33055. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33056. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33057. }
  33058. }
  33059. };
  33060. VirtualJoystick.prototype._onPointerUp = function (e) {
  33061. if (this._joystickPointerID == e.pointerId) {
  33062. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33063. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33064. this._joystickPointerID = -1;
  33065. this.pressed = false;
  33066. }
  33067. else {
  33068. var touch = this._touches.item(e.pointerId.toString());
  33069. if (touch) {
  33070. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33071. }
  33072. }
  33073. this._deltaJoystickVector.x = 0;
  33074. this._deltaJoystickVector.y = 0;
  33075. this._touches.remove(e.pointerId.toString());
  33076. };
  33077. /**
  33078. * Change the color of the virtual joystick
  33079. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33080. */
  33081. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33082. this._joystickColor = newColor;
  33083. };
  33084. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33085. this._action = action;
  33086. };
  33087. // Define which axis you'd like to control for left & right
  33088. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33089. switch (axis) {
  33090. case JoystickAxis.X:
  33091. case JoystickAxis.Y:
  33092. case JoystickAxis.Z:
  33093. this._axisTargetedByLeftAndRight = axis;
  33094. break;
  33095. default:
  33096. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33097. break;
  33098. }
  33099. };
  33100. // Define which axis you'd like to control for up & down
  33101. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33102. switch (axis) {
  33103. case JoystickAxis.X:
  33104. case JoystickAxis.Y:
  33105. case JoystickAxis.Z:
  33106. this._axisTargetedByUpAndDown = axis;
  33107. break;
  33108. default:
  33109. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33110. break;
  33111. }
  33112. };
  33113. VirtualJoystick.prototype._clearCanvas = function () {
  33114. if (this._leftJoystick) {
  33115. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33116. }
  33117. else {
  33118. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33119. }
  33120. };
  33121. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33122. var _this = this;
  33123. if (this.pressed) {
  33124. this._touches.forEach(function (touch) {
  33125. if (touch.pointerId === _this._joystickPointerID) {
  33126. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33127. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33128. VirtualJoystick.vjCanvasContext.beginPath();
  33129. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33130. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33131. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33132. VirtualJoystick.vjCanvasContext.stroke();
  33133. VirtualJoystick.vjCanvasContext.closePath();
  33134. VirtualJoystick.vjCanvasContext.beginPath();
  33135. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33136. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33137. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33138. VirtualJoystick.vjCanvasContext.stroke();
  33139. VirtualJoystick.vjCanvasContext.closePath();
  33140. VirtualJoystick.vjCanvasContext.beginPath();
  33141. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33142. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33143. VirtualJoystick.vjCanvasContext.stroke();
  33144. VirtualJoystick.vjCanvasContext.closePath();
  33145. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33146. }
  33147. else {
  33148. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33149. VirtualJoystick.vjCanvasContext.beginPath();
  33150. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33151. VirtualJoystick.vjCanvasContext.beginPath();
  33152. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33153. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33154. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33155. VirtualJoystick.vjCanvasContext.stroke();
  33156. VirtualJoystick.vjCanvasContext.closePath();
  33157. touch.prevX = touch.x;
  33158. touch.prevY = touch.y;
  33159. }
  33160. ;
  33161. });
  33162. }
  33163. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33164. };
  33165. VirtualJoystick.prototype.releaseCanvas = function () {
  33166. if (VirtualJoystick.vjCanvas) {
  33167. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33168. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33169. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33170. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33171. window.removeEventListener("resize", this._onResize);
  33172. document.body.removeChild(VirtualJoystick.vjCanvas);
  33173. VirtualJoystick.vjCanvas = null;
  33174. }
  33175. };
  33176. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33177. VirtualJoystick._globalJoystickIndex = 0;
  33178. return VirtualJoystick;
  33179. })();
  33180. BABYLON.VirtualJoystick = VirtualJoystick;
  33181. })(BABYLON || (BABYLON = {}));
  33182. var BABYLON;
  33183. (function (BABYLON) {
  33184. // We're mainly based on the logic defined into the FreeCamera code
  33185. var VirtualJoysticksCamera = (function (_super) {
  33186. __extends(VirtualJoysticksCamera, _super);
  33187. function VirtualJoysticksCamera(name, position, scene) {
  33188. _super.call(this, name, position, scene);
  33189. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33190. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33191. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33192. this._leftjoystick.setJoystickSensibility(0.15);
  33193. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33194. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33195. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33196. this._rightjoystick.reverseUpDown = true;
  33197. this._rightjoystick.setJoystickSensibility(0.05);
  33198. this._rightjoystick.setJoystickColor("yellow");
  33199. }
  33200. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33201. return this._leftjoystick;
  33202. };
  33203. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33204. return this._rightjoystick;
  33205. };
  33206. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33207. var speed = this._computeLocalCameraSpeed() * 50;
  33208. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33209. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33210. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33211. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33212. if (!this._leftjoystick.pressed) {
  33213. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33214. }
  33215. if (!this._rightjoystick.pressed) {
  33216. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33217. }
  33218. _super.prototype._checkInputs.call(this);
  33219. };
  33220. VirtualJoysticksCamera.prototype.dispose = function () {
  33221. this._leftjoystick.releaseCanvas();
  33222. _super.prototype.dispose.call(this);
  33223. };
  33224. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33225. return "VirtualJoysticksCamera";
  33226. };
  33227. return VirtualJoysticksCamera;
  33228. })(BABYLON.FreeCamera);
  33229. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33230. })(BABYLON || (BABYLON = {}));
  33231. var BABYLON;
  33232. (function (BABYLON) {
  33233. var AnaglyphPostProcess = (function (_super) {
  33234. __extends(AnaglyphPostProcess, _super);
  33235. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33236. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33237. }
  33238. return AnaglyphPostProcess;
  33239. })(BABYLON.PostProcess);
  33240. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33241. })(BABYLON || (BABYLON = {}));
  33242. var BABYLON;
  33243. (function (BABYLON) {
  33244. var OutlineRenderer = (function () {
  33245. function OutlineRenderer(scene) {
  33246. this._scene = scene;
  33247. }
  33248. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33249. var _this = this;
  33250. if (useOverlay === void 0) { useOverlay = false; }
  33251. var scene = this._scene;
  33252. var engine = this._scene.getEngine();
  33253. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33254. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33255. return;
  33256. }
  33257. var mesh = subMesh.getRenderingMesh();
  33258. var material = subMesh.getMaterial();
  33259. engine.enableEffect(this._effect);
  33260. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33261. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33262. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33263. // Bones
  33264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33265. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33266. }
  33267. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33268. // Alpha test
  33269. if (material && material.needAlphaTesting()) {
  33270. var alphaTexture = material.getAlphaTestTexture();
  33271. this._effect.setTexture("diffuseSampler", alphaTexture);
  33272. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33273. }
  33274. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33275. };
  33276. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33277. var defines = [];
  33278. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33279. var mesh = subMesh.getMesh();
  33280. var material = subMesh.getMaterial();
  33281. // Alpha test
  33282. if (material && material.needAlphaTesting()) {
  33283. defines.push("#define ALPHATEST");
  33284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33285. attribs.push(BABYLON.VertexBuffer.UVKind);
  33286. defines.push("#define UV1");
  33287. }
  33288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33290. defines.push("#define UV2");
  33291. }
  33292. }
  33293. // Bones
  33294. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33297. if (mesh.numBoneInfluencers > 4) {
  33298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33300. }
  33301. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33302. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33303. }
  33304. else {
  33305. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33306. }
  33307. // Instances
  33308. if (useInstances) {
  33309. defines.push("#define INSTANCES");
  33310. attribs.push("world0");
  33311. attribs.push("world1");
  33312. attribs.push("world2");
  33313. attribs.push("world3");
  33314. }
  33315. // Get correct effect
  33316. var join = defines.join("\n");
  33317. if (this._cachedDefines !== join) {
  33318. this._cachedDefines = join;
  33319. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33320. }
  33321. return this._effect.isReady();
  33322. };
  33323. return OutlineRenderer;
  33324. })();
  33325. BABYLON.OutlineRenderer = OutlineRenderer;
  33326. })(BABYLON || (BABYLON = {}));
  33327. var BABYLON;
  33328. (function (BABYLON) {
  33329. var MeshAssetTask = (function () {
  33330. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33331. this.name = name;
  33332. this.meshesNames = meshesNames;
  33333. this.rootUrl = rootUrl;
  33334. this.sceneFilename = sceneFilename;
  33335. this.isCompleted = false;
  33336. }
  33337. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33338. var _this = this;
  33339. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33340. _this.loadedMeshes = meshes;
  33341. _this.loadedParticleSystems = particleSystems;
  33342. _this.loadedSkeletons = skeletons;
  33343. _this.isCompleted = true;
  33344. if (_this.onSuccess) {
  33345. _this.onSuccess(_this);
  33346. }
  33347. onSuccess();
  33348. }, null, function () {
  33349. if (_this.onError) {
  33350. _this.onError(_this);
  33351. }
  33352. onError();
  33353. });
  33354. };
  33355. return MeshAssetTask;
  33356. })();
  33357. BABYLON.MeshAssetTask = MeshAssetTask;
  33358. var TextFileAssetTask = (function () {
  33359. function TextFileAssetTask(name, url) {
  33360. this.name = name;
  33361. this.url = url;
  33362. this.isCompleted = false;
  33363. }
  33364. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33365. var _this = this;
  33366. BABYLON.Tools.LoadFile(this.url, function (data) {
  33367. _this.text = data;
  33368. _this.isCompleted = true;
  33369. if (_this.onSuccess) {
  33370. _this.onSuccess(_this);
  33371. }
  33372. onSuccess();
  33373. }, null, scene.database, false, function () {
  33374. if (_this.onError) {
  33375. _this.onError(_this);
  33376. }
  33377. onError();
  33378. });
  33379. };
  33380. return TextFileAssetTask;
  33381. })();
  33382. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33383. var BinaryFileAssetTask = (function () {
  33384. function BinaryFileAssetTask(name, url) {
  33385. this.name = name;
  33386. this.url = url;
  33387. this.isCompleted = false;
  33388. }
  33389. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33390. var _this = this;
  33391. BABYLON.Tools.LoadFile(this.url, function (data) {
  33392. _this.data = data;
  33393. _this.isCompleted = true;
  33394. if (_this.onSuccess) {
  33395. _this.onSuccess(_this);
  33396. }
  33397. onSuccess();
  33398. }, null, scene.database, true, function () {
  33399. if (_this.onError) {
  33400. _this.onError(_this);
  33401. }
  33402. onError();
  33403. });
  33404. };
  33405. return BinaryFileAssetTask;
  33406. })();
  33407. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33408. var ImageAssetTask = (function () {
  33409. function ImageAssetTask(name, url) {
  33410. this.name = name;
  33411. this.url = url;
  33412. this.isCompleted = false;
  33413. }
  33414. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33415. var _this = this;
  33416. var img = new Image();
  33417. img.onload = function () {
  33418. _this.image = img;
  33419. _this.isCompleted = true;
  33420. if (_this.onSuccess) {
  33421. _this.onSuccess(_this);
  33422. }
  33423. onSuccess();
  33424. };
  33425. img.onerror = function () {
  33426. if (_this.onError) {
  33427. _this.onError(_this);
  33428. }
  33429. onError();
  33430. };
  33431. img.src = this.url;
  33432. };
  33433. return ImageAssetTask;
  33434. })();
  33435. BABYLON.ImageAssetTask = ImageAssetTask;
  33436. var TextureAssetTask = (function () {
  33437. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33439. this.name = name;
  33440. this.url = url;
  33441. this.noMipmap = noMipmap;
  33442. this.invertY = invertY;
  33443. this.samplingMode = samplingMode;
  33444. this.isCompleted = false;
  33445. }
  33446. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33447. var _this = this;
  33448. var onload = function () {
  33449. _this.isCompleted = true;
  33450. if (_this.onSuccess) {
  33451. _this.onSuccess(_this);
  33452. }
  33453. onSuccess();
  33454. };
  33455. var onerror = function () {
  33456. if (_this.onError) {
  33457. _this.onError(_this);
  33458. }
  33459. onError();
  33460. };
  33461. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33462. };
  33463. return TextureAssetTask;
  33464. })();
  33465. BABYLON.TextureAssetTask = TextureAssetTask;
  33466. var AssetsManager = (function () {
  33467. function AssetsManager(scene) {
  33468. this._tasks = new Array();
  33469. this._waitingTasksCount = 0;
  33470. this.useDefaultLoadingScreen = true;
  33471. this._scene = scene;
  33472. }
  33473. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33474. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33475. this._tasks.push(task);
  33476. return task;
  33477. };
  33478. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33479. var task = new TextFileAssetTask(taskName, url);
  33480. this._tasks.push(task);
  33481. return task;
  33482. };
  33483. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33484. var task = new BinaryFileAssetTask(taskName, url);
  33485. this._tasks.push(task);
  33486. return task;
  33487. };
  33488. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33489. var task = new ImageAssetTask(taskName, url);
  33490. this._tasks.push(task);
  33491. return task;
  33492. };
  33493. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33494. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33495. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33496. this._tasks.push(task);
  33497. return task;
  33498. };
  33499. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33500. this._waitingTasksCount--;
  33501. if (this._waitingTasksCount === 0) {
  33502. if (this.onFinish) {
  33503. this.onFinish(this._tasks);
  33504. }
  33505. this._scene.getEngine().hideLoadingUI();
  33506. }
  33507. };
  33508. AssetsManager.prototype._runTask = function (task) {
  33509. var _this = this;
  33510. task.run(this._scene, function () {
  33511. if (_this.onTaskSuccess) {
  33512. _this.onTaskSuccess(task);
  33513. }
  33514. _this._decreaseWaitingTasksCount();
  33515. }, function () {
  33516. if (_this.onTaskError) {
  33517. _this.onTaskError(task);
  33518. }
  33519. _this._decreaseWaitingTasksCount();
  33520. });
  33521. };
  33522. AssetsManager.prototype.reset = function () {
  33523. this._tasks = new Array();
  33524. return this;
  33525. };
  33526. AssetsManager.prototype.load = function () {
  33527. this._waitingTasksCount = this._tasks.length;
  33528. if (this._waitingTasksCount === 0) {
  33529. if (this.onFinish) {
  33530. this.onFinish(this._tasks);
  33531. }
  33532. return this;
  33533. }
  33534. if (this.useDefaultLoadingScreen) {
  33535. this._scene.getEngine().displayLoadingUI();
  33536. }
  33537. for (var index = 0; index < this._tasks.length; index++) {
  33538. var task = this._tasks[index];
  33539. this._runTask(task);
  33540. }
  33541. return this;
  33542. };
  33543. return AssetsManager;
  33544. })();
  33545. BABYLON.AssetsManager = AssetsManager;
  33546. })(BABYLON || (BABYLON = {}));
  33547. var BABYLON;
  33548. (function (BABYLON) {
  33549. var VRCameraMetrics = (function () {
  33550. function VRCameraMetrics() {
  33551. this.compensateDistortion = true;
  33552. }
  33553. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33554. get: function () {
  33555. return this.hResolution / (2 * this.vResolution);
  33556. },
  33557. enumerable: true,
  33558. configurable: true
  33559. });
  33560. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33561. get: function () {
  33562. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33563. },
  33564. enumerable: true,
  33565. configurable: true
  33566. });
  33567. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33568. get: function () {
  33569. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33570. var h = (4 * meters) / this.hScreenSize;
  33571. return BABYLON.Matrix.Translation(h, 0, 0);
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33577. get: function () {
  33578. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33579. var h = (4 * meters) / this.hScreenSize;
  33580. return BABYLON.Matrix.Translation(-h, 0, 0);
  33581. },
  33582. enumerable: true,
  33583. configurable: true
  33584. });
  33585. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33586. get: function () {
  33587. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33588. },
  33589. enumerable: true,
  33590. configurable: true
  33591. });
  33592. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33593. get: function () {
  33594. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33595. },
  33596. enumerable: true,
  33597. configurable: true
  33598. });
  33599. VRCameraMetrics.GetDefault = function () {
  33600. var result = new VRCameraMetrics();
  33601. result.hResolution = 1280;
  33602. result.vResolution = 800;
  33603. result.hScreenSize = 0.149759993;
  33604. result.vScreenSize = 0.0935999975;
  33605. result.vScreenCenter = 0.0467999987,
  33606. result.eyeToScreenDistance = 0.0410000011;
  33607. result.lensSeparationDistance = 0.0635000020;
  33608. result.interpupillaryDistance = 0.0640000030;
  33609. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33610. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33611. result.postProcessScaleFactor = 1.714605507808412;
  33612. result.lensCenterOffset = 0.151976421;
  33613. return result;
  33614. };
  33615. return VRCameraMetrics;
  33616. })();
  33617. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33618. })(BABYLON || (BABYLON = {}));
  33619. var BABYLON;
  33620. (function (BABYLON) {
  33621. var VRDeviceOrientationFreeCamera = (function (_super) {
  33622. __extends(VRDeviceOrientationFreeCamera, _super);
  33623. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33624. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33625. _super.call(this, name, position, scene);
  33626. this._alpha = 0;
  33627. this._beta = 0;
  33628. this._gamma = 0;
  33629. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33630. metrics.compensateDistortion = compensateDistortion;
  33631. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33632. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33633. }
  33634. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33635. this._alpha = +evt.alpha | 0;
  33636. this._beta = +evt.beta | 0;
  33637. this._gamma = +evt.gamma | 0;
  33638. if (this._gamma < 0) {
  33639. this._gamma = 90 + this._gamma;
  33640. }
  33641. else {
  33642. // Incline it in the correct angle.
  33643. this._gamma = 270 - this._gamma;
  33644. }
  33645. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33646. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33647. this.rotation.z = this._beta / 180.0 * Math.PI;
  33648. };
  33649. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33650. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33651. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33652. };
  33653. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33654. _super.prototype.detachControl.call(this, element);
  33655. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33656. };
  33657. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33658. return "VRDeviceOrientationFreeCamera";
  33659. };
  33660. return VRDeviceOrientationFreeCamera;
  33661. })(BABYLON.FreeCamera);
  33662. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33663. })(BABYLON || (BABYLON = {}));
  33664. var BABYLON;
  33665. (function (BABYLON) {
  33666. var WebVRFreeCamera = (function (_super) {
  33667. __extends(WebVRFreeCamera, _super);
  33668. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33669. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33670. _super.call(this, name, position, scene);
  33671. this._hmdDevice = null;
  33672. this._sensorDevice = null;
  33673. this._cacheState = null;
  33674. this._cacheQuaternion = new BABYLON.Quaternion();
  33675. this._cacheRotation = BABYLON.Vector3.Zero();
  33676. this._vrEnabled = false;
  33677. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33678. metrics.compensateDistortion = compensateDistortion;
  33679. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33680. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33681. }
  33682. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33683. var size = devices.length;
  33684. var i = 0;
  33685. // Reset devices.
  33686. this._sensorDevice = null;
  33687. this._hmdDevice = null;
  33688. // Search for a HmdDevice.
  33689. while (i < size && this._hmdDevice === null) {
  33690. if (devices[i] instanceof HMDVRDevice) {
  33691. this._hmdDevice = devices[i];
  33692. }
  33693. i++;
  33694. }
  33695. i = 0;
  33696. while (i < size && this._sensorDevice === null) {
  33697. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33698. this._sensorDevice = devices[i];
  33699. }
  33700. i++;
  33701. }
  33702. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33703. };
  33704. WebVRFreeCamera.prototype._checkInputs = function () {
  33705. if (this._vrEnabled) {
  33706. this._cacheState = this._sensorDevice.getState();
  33707. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33708. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33709. this.rotation.x = -this._cacheRotation.z;
  33710. this.rotation.y = -this._cacheRotation.y;
  33711. this.rotation.z = this._cacheRotation.x;
  33712. }
  33713. _super.prototype._checkInputs.call(this);
  33714. };
  33715. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33716. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33717. if (navigator.getVRDevices) {
  33718. navigator.getVRDevices().then(this._getWebVRDevices);
  33719. }
  33720. else if (navigator.mozGetVRDevices) {
  33721. navigator.mozGetVRDevices(this._getWebVRDevices);
  33722. }
  33723. };
  33724. WebVRFreeCamera.prototype.detachControl = function (element) {
  33725. _super.prototype.detachControl.call(this, element);
  33726. this._vrEnabled = false;
  33727. };
  33728. WebVRFreeCamera.prototype.getTypeName = function () {
  33729. return "WebVRFreeCamera";
  33730. };
  33731. return WebVRFreeCamera;
  33732. })(BABYLON.FreeCamera);
  33733. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33734. })(BABYLON || (BABYLON = {}));
  33735. var BABYLON;
  33736. (function (BABYLON) {
  33737. // Standard optimizations
  33738. var SceneOptimization = (function () {
  33739. function SceneOptimization(priority) {
  33740. if (priority === void 0) { priority = 0; }
  33741. this.priority = priority;
  33742. this.apply = function (scene) {
  33743. return true; // Return true if everything that can be done was applied
  33744. };
  33745. }
  33746. return SceneOptimization;
  33747. })();
  33748. BABYLON.SceneOptimization = SceneOptimization;
  33749. var TextureOptimization = (function (_super) {
  33750. __extends(TextureOptimization, _super);
  33751. function TextureOptimization(priority, maximumSize) {
  33752. var _this = this;
  33753. if (priority === void 0) { priority = 0; }
  33754. if (maximumSize === void 0) { maximumSize = 1024; }
  33755. _super.call(this, priority);
  33756. this.priority = priority;
  33757. this.maximumSize = maximumSize;
  33758. this.apply = function (scene) {
  33759. var allDone = true;
  33760. for (var index = 0; index < scene.textures.length; index++) {
  33761. var texture = scene.textures[index];
  33762. if (!texture.canRescale) {
  33763. continue;
  33764. }
  33765. var currentSize = texture.getSize();
  33766. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33767. if (maxDimension > _this.maximumSize) {
  33768. texture.scale(0.5);
  33769. allDone = false;
  33770. }
  33771. }
  33772. return allDone;
  33773. };
  33774. }
  33775. return TextureOptimization;
  33776. })(SceneOptimization);
  33777. BABYLON.TextureOptimization = TextureOptimization;
  33778. var HardwareScalingOptimization = (function (_super) {
  33779. __extends(HardwareScalingOptimization, _super);
  33780. function HardwareScalingOptimization(priority, maximumScale) {
  33781. var _this = this;
  33782. if (priority === void 0) { priority = 0; }
  33783. if (maximumScale === void 0) { maximumScale = 2; }
  33784. _super.call(this, priority);
  33785. this.priority = priority;
  33786. this.maximumScale = maximumScale;
  33787. this._currentScale = 1;
  33788. this.apply = function (scene) {
  33789. _this._currentScale++;
  33790. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33791. return _this._currentScale >= _this.maximumScale;
  33792. };
  33793. }
  33794. return HardwareScalingOptimization;
  33795. })(SceneOptimization);
  33796. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33797. var ShadowsOptimization = (function (_super) {
  33798. __extends(ShadowsOptimization, _super);
  33799. function ShadowsOptimization() {
  33800. _super.apply(this, arguments);
  33801. this.apply = function (scene) {
  33802. scene.shadowsEnabled = false;
  33803. return true;
  33804. };
  33805. }
  33806. return ShadowsOptimization;
  33807. })(SceneOptimization);
  33808. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33809. var PostProcessesOptimization = (function (_super) {
  33810. __extends(PostProcessesOptimization, _super);
  33811. function PostProcessesOptimization() {
  33812. _super.apply(this, arguments);
  33813. this.apply = function (scene) {
  33814. scene.postProcessesEnabled = false;
  33815. return true;
  33816. };
  33817. }
  33818. return PostProcessesOptimization;
  33819. })(SceneOptimization);
  33820. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33821. var LensFlaresOptimization = (function (_super) {
  33822. __extends(LensFlaresOptimization, _super);
  33823. function LensFlaresOptimization() {
  33824. _super.apply(this, arguments);
  33825. this.apply = function (scene) {
  33826. scene.lensFlaresEnabled = false;
  33827. return true;
  33828. };
  33829. }
  33830. return LensFlaresOptimization;
  33831. })(SceneOptimization);
  33832. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33833. var ParticlesOptimization = (function (_super) {
  33834. __extends(ParticlesOptimization, _super);
  33835. function ParticlesOptimization() {
  33836. _super.apply(this, arguments);
  33837. this.apply = function (scene) {
  33838. scene.particlesEnabled = false;
  33839. return true;
  33840. };
  33841. }
  33842. return ParticlesOptimization;
  33843. })(SceneOptimization);
  33844. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33845. var RenderTargetsOptimization = (function (_super) {
  33846. __extends(RenderTargetsOptimization, _super);
  33847. function RenderTargetsOptimization() {
  33848. _super.apply(this, arguments);
  33849. this.apply = function (scene) {
  33850. scene.renderTargetsEnabled = false;
  33851. return true;
  33852. };
  33853. }
  33854. return RenderTargetsOptimization;
  33855. })(SceneOptimization);
  33856. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33857. var MergeMeshesOptimization = (function (_super) {
  33858. __extends(MergeMeshesOptimization, _super);
  33859. function MergeMeshesOptimization() {
  33860. var _this = this;
  33861. _super.apply(this, arguments);
  33862. this._canBeMerged = function (abstractMesh) {
  33863. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33864. return false;
  33865. }
  33866. var mesh = abstractMesh;
  33867. if (!mesh.isVisible || !mesh.isEnabled()) {
  33868. return false;
  33869. }
  33870. if (mesh.instances.length > 0) {
  33871. return false;
  33872. }
  33873. if (mesh.skeleton || mesh.hasLODLevels) {
  33874. return false;
  33875. }
  33876. if (mesh.parent) {
  33877. return false;
  33878. }
  33879. return true;
  33880. };
  33881. this.apply = function (scene, updateSelectionTree) {
  33882. var globalPool = scene.meshes.slice(0);
  33883. var globalLength = globalPool.length;
  33884. for (var index = 0; index < globalLength; index++) {
  33885. var currentPool = new Array();
  33886. var current = globalPool[index];
  33887. // Checks
  33888. if (!_this._canBeMerged(current)) {
  33889. continue;
  33890. }
  33891. currentPool.push(current);
  33892. // Find compatible meshes
  33893. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33894. var otherMesh = globalPool[subIndex];
  33895. if (!_this._canBeMerged(otherMesh)) {
  33896. continue;
  33897. }
  33898. if (otherMesh.material !== current.material) {
  33899. continue;
  33900. }
  33901. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33902. continue;
  33903. }
  33904. currentPool.push(otherMesh);
  33905. globalLength--;
  33906. globalPool.splice(subIndex, 1);
  33907. subIndex--;
  33908. }
  33909. if (currentPool.length < 2) {
  33910. continue;
  33911. }
  33912. // Merge meshes
  33913. BABYLON.Mesh.MergeMeshes(currentPool);
  33914. }
  33915. if (updateSelectionTree != undefined) {
  33916. if (updateSelectionTree) {
  33917. scene.createOrUpdateSelectionOctree();
  33918. }
  33919. }
  33920. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33921. scene.createOrUpdateSelectionOctree();
  33922. }
  33923. return true;
  33924. };
  33925. }
  33926. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33927. get: function () {
  33928. return MergeMeshesOptimization._UpdateSelectionTree;
  33929. },
  33930. set: function (value) {
  33931. MergeMeshesOptimization._UpdateSelectionTree = value;
  33932. },
  33933. enumerable: true,
  33934. configurable: true
  33935. });
  33936. MergeMeshesOptimization._UpdateSelectionTree = false;
  33937. return MergeMeshesOptimization;
  33938. })(SceneOptimization);
  33939. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33940. // Options
  33941. var SceneOptimizerOptions = (function () {
  33942. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33943. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33944. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33945. this.targetFrameRate = targetFrameRate;
  33946. this.trackerDuration = trackerDuration;
  33947. this.optimizations = new Array();
  33948. }
  33949. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33950. var result = new SceneOptimizerOptions(targetFrameRate);
  33951. var priority = 0;
  33952. result.optimizations.push(new MergeMeshesOptimization(priority));
  33953. result.optimizations.push(new ShadowsOptimization(priority));
  33954. result.optimizations.push(new LensFlaresOptimization(priority));
  33955. // Next priority
  33956. priority++;
  33957. result.optimizations.push(new PostProcessesOptimization(priority));
  33958. result.optimizations.push(new ParticlesOptimization(priority));
  33959. // Next priority
  33960. priority++;
  33961. result.optimizations.push(new TextureOptimization(priority, 1024));
  33962. return result;
  33963. };
  33964. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33965. var result = new SceneOptimizerOptions(targetFrameRate);
  33966. var priority = 0;
  33967. result.optimizations.push(new MergeMeshesOptimization(priority));
  33968. result.optimizations.push(new ShadowsOptimization(priority));
  33969. result.optimizations.push(new LensFlaresOptimization(priority));
  33970. // Next priority
  33971. priority++;
  33972. result.optimizations.push(new PostProcessesOptimization(priority));
  33973. result.optimizations.push(new ParticlesOptimization(priority));
  33974. // Next priority
  33975. priority++;
  33976. result.optimizations.push(new TextureOptimization(priority, 512));
  33977. // Next priority
  33978. priority++;
  33979. result.optimizations.push(new RenderTargetsOptimization(priority));
  33980. // Next priority
  33981. priority++;
  33982. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33983. return result;
  33984. };
  33985. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33986. var result = new SceneOptimizerOptions(targetFrameRate);
  33987. var priority = 0;
  33988. result.optimizations.push(new MergeMeshesOptimization(priority));
  33989. result.optimizations.push(new ShadowsOptimization(priority));
  33990. result.optimizations.push(new LensFlaresOptimization(priority));
  33991. // Next priority
  33992. priority++;
  33993. result.optimizations.push(new PostProcessesOptimization(priority));
  33994. result.optimizations.push(new ParticlesOptimization(priority));
  33995. // Next priority
  33996. priority++;
  33997. result.optimizations.push(new TextureOptimization(priority, 256));
  33998. // Next priority
  33999. priority++;
  34000. result.optimizations.push(new RenderTargetsOptimization(priority));
  34001. // Next priority
  34002. priority++;
  34003. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34004. return result;
  34005. };
  34006. return SceneOptimizerOptions;
  34007. })();
  34008. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34009. // Scene optimizer tool
  34010. var SceneOptimizer = (function () {
  34011. function SceneOptimizer() {
  34012. }
  34013. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34014. // TODO: add an epsilon
  34015. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34016. if (onSuccess) {
  34017. onSuccess();
  34018. }
  34019. return;
  34020. }
  34021. // Apply current level of optimizations
  34022. var allDone = true;
  34023. var noOptimizationApplied = true;
  34024. for (var index = 0; index < options.optimizations.length; index++) {
  34025. var optimization = options.optimizations[index];
  34026. if (optimization.priority === currentPriorityLevel) {
  34027. noOptimizationApplied = false;
  34028. allDone = allDone && optimization.apply(scene);
  34029. }
  34030. }
  34031. // If no optimization was applied, this is a failure :(
  34032. if (noOptimizationApplied) {
  34033. if (onFailure) {
  34034. onFailure();
  34035. }
  34036. return;
  34037. }
  34038. // If all optimizations were done, move to next level
  34039. if (allDone) {
  34040. currentPriorityLevel++;
  34041. }
  34042. // Let's the system running for a specific amount of time before checking FPS
  34043. scene.executeWhenReady(function () {
  34044. setTimeout(function () {
  34045. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34046. }, options.trackerDuration);
  34047. });
  34048. };
  34049. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34050. if (!options) {
  34051. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34052. }
  34053. // Let's the system running for a specific amount of time before checking FPS
  34054. scene.executeWhenReady(function () {
  34055. setTimeout(function () {
  34056. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34057. }, options.trackerDuration);
  34058. });
  34059. };
  34060. return SceneOptimizer;
  34061. })();
  34062. BABYLON.SceneOptimizer = SceneOptimizer;
  34063. })(BABYLON || (BABYLON = {}));
  34064. var BABYLON;
  34065. (function (BABYLON) {
  34066. var Internals;
  34067. (function (Internals) {
  34068. var MeshLODLevel = (function () {
  34069. function MeshLODLevel(distance, mesh) {
  34070. this.distance = distance;
  34071. this.mesh = mesh;
  34072. }
  34073. return MeshLODLevel;
  34074. })();
  34075. Internals.MeshLODLevel = MeshLODLevel;
  34076. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34077. })(BABYLON || (BABYLON = {}));
  34078. var BABYLON;
  34079. (function (BABYLON) {
  34080. var RawTexture = (function (_super) {
  34081. __extends(RawTexture, _super);
  34082. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34084. if (invertY === void 0) { invertY = false; }
  34085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34086. _super.call(this, null, scene, !generateMipMaps, invertY);
  34087. this.format = format;
  34088. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34089. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34090. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34091. }
  34092. RawTexture.prototype.update = function (data) {
  34093. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34094. };
  34095. // Statics
  34096. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34097. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34098. if (invertY === void 0) { invertY = false; }
  34099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34101. };
  34102. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34104. if (invertY === void 0) { invertY = false; }
  34105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34106. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34107. };
  34108. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34109. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34110. if (invertY === void 0) { invertY = false; }
  34111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34112. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34113. };
  34114. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34115. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34116. if (invertY === void 0) { invertY = false; }
  34117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34118. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34119. };
  34120. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34121. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34122. if (invertY === void 0) { invertY = false; }
  34123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34124. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34125. };
  34126. return RawTexture;
  34127. })(BABYLON.Texture);
  34128. BABYLON.RawTexture = RawTexture;
  34129. })(BABYLON || (BABYLON = {}));
  34130. var BABYLON;
  34131. (function (BABYLON) {
  34132. var IndexedVector2 = (function (_super) {
  34133. __extends(IndexedVector2, _super);
  34134. function IndexedVector2(original, index) {
  34135. _super.call(this, original.x, original.y);
  34136. this.index = index;
  34137. }
  34138. return IndexedVector2;
  34139. })(BABYLON.Vector2);
  34140. var PolygonPoints = (function () {
  34141. function PolygonPoints() {
  34142. this.elements = new Array();
  34143. }
  34144. PolygonPoints.prototype.add = function (originalPoints) {
  34145. var _this = this;
  34146. var result = new Array();
  34147. originalPoints.forEach(function (point) {
  34148. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34149. var newPoint = new IndexedVector2(point, _this.elements.length);
  34150. result.push(newPoint);
  34151. _this.elements.push(newPoint);
  34152. }
  34153. });
  34154. return result;
  34155. };
  34156. PolygonPoints.prototype.computeBounds = function () {
  34157. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34158. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34159. this.elements.forEach(function (point) {
  34160. // x
  34161. if (point.x < lmin.x) {
  34162. lmin.x = point.x;
  34163. }
  34164. else if (point.x > lmax.x) {
  34165. lmax.x = point.x;
  34166. }
  34167. // y
  34168. if (point.y < lmin.y) {
  34169. lmin.y = point.y;
  34170. }
  34171. else if (point.y > lmax.y) {
  34172. lmax.y = point.y;
  34173. }
  34174. });
  34175. return {
  34176. min: lmin,
  34177. max: lmax,
  34178. width: lmax.x - lmin.x,
  34179. height: lmax.y - lmin.y
  34180. };
  34181. };
  34182. return PolygonPoints;
  34183. })();
  34184. var Polygon = (function () {
  34185. function Polygon() {
  34186. }
  34187. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34188. return [
  34189. new BABYLON.Vector2(xmin, ymin),
  34190. new BABYLON.Vector2(xmax, ymin),
  34191. new BABYLON.Vector2(xmax, ymax),
  34192. new BABYLON.Vector2(xmin, ymax)
  34193. ];
  34194. };
  34195. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34196. if (cx === void 0) { cx = 0; }
  34197. if (cy === void 0) { cy = 0; }
  34198. if (numberOfSides === void 0) { numberOfSides = 32; }
  34199. var result = new Array();
  34200. var angle = 0;
  34201. var increment = (Math.PI * 2) / numberOfSides;
  34202. for (var i = 0; i < numberOfSides; i++) {
  34203. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34204. angle -= increment;
  34205. }
  34206. return result;
  34207. };
  34208. Polygon.Parse = function (input) {
  34209. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34210. var i, result = [];
  34211. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34212. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34213. }
  34214. return result;
  34215. };
  34216. Polygon.StartingAt = function (x, y) {
  34217. return BABYLON.Path2.StartingAt(x, y);
  34218. };
  34219. return Polygon;
  34220. })();
  34221. BABYLON.Polygon = Polygon;
  34222. var PolygonMeshBuilder = (function () {
  34223. function PolygonMeshBuilder(name, contours, scene) {
  34224. this._points = new PolygonPoints();
  34225. this._outlinepoints = new PolygonPoints();
  34226. this._holes = [];
  34227. if (!("poly2tri" in window)) {
  34228. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34229. }
  34230. this._name = name;
  34231. this._scene = scene;
  34232. var points;
  34233. if (contours instanceof BABYLON.Path2) {
  34234. points = contours.getPoints();
  34235. }
  34236. else {
  34237. points = contours;
  34238. }
  34239. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34240. this._outlinepoints.add(points);
  34241. }
  34242. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34243. this._swctx.addHole(this._points.add(hole));
  34244. var holepoints = new PolygonPoints();
  34245. holepoints.add(hole);
  34246. this._holes.push(holepoints);
  34247. return this;
  34248. };
  34249. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34250. var _this = this;
  34251. if (updatable === void 0) { updatable = false; }
  34252. var result = new BABYLON.Mesh(this._name, this._scene);
  34253. var normals = [];
  34254. var positions = [];
  34255. var uvs = [];
  34256. var bounds = this._points.computeBounds();
  34257. this._points.elements.forEach(function (p) {
  34258. normals.push(0, 1.0, 0);
  34259. positions.push(p.x, 0, p.y);
  34260. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34261. });
  34262. var indices = [];
  34263. this._swctx.triangulate();
  34264. this._swctx.getTriangles().forEach(function (triangle) {
  34265. triangle.getPoints().forEach(function (point) {
  34266. indices.push(point.index);
  34267. });
  34268. });
  34269. if (depth > 0) {
  34270. var positionscount = (positions.length / 3); //get the current pointcount
  34271. this._points.elements.forEach(function (p) {
  34272. normals.push(0, -1.0, 0);
  34273. positions.push(p.x, -depth, p.y);
  34274. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34275. });
  34276. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34277. var p2;
  34278. var poscounter = 0;
  34279. this._swctx.getTriangles().forEach(function (triangle) {
  34280. triangle.getPoints().forEach(function (point) {
  34281. switch (poscounter) {
  34282. case 0:
  34283. p1 = point;
  34284. break;
  34285. case 1:
  34286. p2 = point;
  34287. break;
  34288. case 2:
  34289. indices.push(point.index + positionscount);
  34290. indices.push(p2.index + positionscount);
  34291. indices.push(p1.index + positionscount);
  34292. poscounter = -1;
  34293. break;
  34294. }
  34295. poscounter++;
  34296. //indices.push((<IndexedVector2>point).index + positionscount);
  34297. });
  34298. });
  34299. //Add the sides
  34300. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34301. this._holes.forEach(function (hole) {
  34302. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34303. });
  34304. }
  34305. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34306. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34307. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34308. result.setIndices(indices);
  34309. return result;
  34310. };
  34311. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34312. var StartIndex = positions.length / 3;
  34313. var ulength = 0;
  34314. for (var i = 0; i < points.elements.length; i++) {
  34315. var p = points.elements[i];
  34316. var p1;
  34317. if ((i + 1) > points.elements.length - 1) {
  34318. p1 = points.elements[0];
  34319. }
  34320. else {
  34321. p1 = points.elements[i + 1];
  34322. }
  34323. positions.push(p.x, 0, p.y);
  34324. positions.push(p.x, -depth, p.y);
  34325. positions.push(p1.x, 0, p1.y);
  34326. positions.push(p1.x, -depth, p1.y);
  34327. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34328. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34329. var v3 = v2.subtract(v1);
  34330. var v4 = new BABYLON.Vector3(0, 1, 0);
  34331. var vn = BABYLON.Vector3.Cross(v3, v4);
  34332. vn = vn.normalize();
  34333. uvs.push(ulength / bounds.width, 0);
  34334. uvs.push(ulength / bounds.width, 1);
  34335. ulength += v3.length();
  34336. uvs.push((ulength / bounds.width), 0);
  34337. uvs.push((ulength / bounds.width), 1);
  34338. if (!flip) {
  34339. normals.push(-vn.x, -vn.y, -vn.z);
  34340. normals.push(-vn.x, -vn.y, -vn.z);
  34341. normals.push(-vn.x, -vn.y, -vn.z);
  34342. normals.push(-vn.x, -vn.y, -vn.z);
  34343. indices.push(StartIndex);
  34344. indices.push(StartIndex + 1);
  34345. indices.push(StartIndex + 2);
  34346. indices.push(StartIndex + 1);
  34347. indices.push(StartIndex + 3);
  34348. indices.push(StartIndex + 2);
  34349. }
  34350. else {
  34351. normals.push(vn.x, vn.y, vn.z);
  34352. normals.push(vn.x, vn.y, vn.z);
  34353. normals.push(vn.x, vn.y, vn.z);
  34354. normals.push(vn.x, vn.y, vn.z);
  34355. indices.push(StartIndex);
  34356. indices.push(StartIndex + 2);
  34357. indices.push(StartIndex + 1);
  34358. indices.push(StartIndex + 1);
  34359. indices.push(StartIndex + 2);
  34360. indices.push(StartIndex + 3);
  34361. }
  34362. StartIndex += 4;
  34363. }
  34364. ;
  34365. };
  34366. return PolygonMeshBuilder;
  34367. })();
  34368. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34369. })(BABYLON || (BABYLON = {}));
  34370. var BABYLON;
  34371. (function (BABYLON) {
  34372. var Octree = (function () {
  34373. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34374. if (maxDepth === void 0) { maxDepth = 2; }
  34375. this.maxDepth = maxDepth;
  34376. this.dynamicContent = new Array();
  34377. this._maxBlockCapacity = maxBlockCapacity || 64;
  34378. this._selectionContent = new BABYLON.SmartArray(1024);
  34379. this._creationFunc = creationFunc;
  34380. }
  34381. // Methods
  34382. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34383. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34384. };
  34385. Octree.prototype.addMesh = function (entry) {
  34386. for (var index = 0; index < this.blocks.length; index++) {
  34387. var block = this.blocks[index];
  34388. block.addEntry(entry);
  34389. }
  34390. };
  34391. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34392. this._selectionContent.reset();
  34393. for (var index = 0; index < this.blocks.length; index++) {
  34394. var block = this.blocks[index];
  34395. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34396. }
  34397. if (allowDuplicate) {
  34398. this._selectionContent.concat(this.dynamicContent);
  34399. }
  34400. else {
  34401. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34402. }
  34403. return this._selectionContent;
  34404. };
  34405. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34406. this._selectionContent.reset();
  34407. for (var index = 0; index < this.blocks.length; index++) {
  34408. var block = this.blocks[index];
  34409. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34410. }
  34411. if (allowDuplicate) {
  34412. this._selectionContent.concat(this.dynamicContent);
  34413. }
  34414. else {
  34415. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34416. }
  34417. return this._selectionContent;
  34418. };
  34419. Octree.prototype.intersectsRay = function (ray) {
  34420. this._selectionContent.reset();
  34421. for (var index = 0; index < this.blocks.length; index++) {
  34422. var block = this.blocks[index];
  34423. block.intersectsRay(ray, this._selectionContent);
  34424. }
  34425. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34426. return this._selectionContent;
  34427. };
  34428. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34429. target.blocks = new Array();
  34430. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34431. // Segmenting space
  34432. for (var x = 0; x < 2; x++) {
  34433. for (var y = 0; y < 2; y++) {
  34434. for (var z = 0; z < 2; z++) {
  34435. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34436. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34437. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34438. block.addEntries(entries);
  34439. target.blocks.push(block);
  34440. }
  34441. }
  34442. }
  34443. };
  34444. Octree.CreationFuncForMeshes = function (entry, block) {
  34445. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34446. block.entries.push(entry);
  34447. }
  34448. };
  34449. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34450. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34451. block.entries.push(entry);
  34452. }
  34453. };
  34454. return Octree;
  34455. })();
  34456. BABYLON.Octree = Octree;
  34457. })(BABYLON || (BABYLON = {}));
  34458. var BABYLON;
  34459. (function (BABYLON) {
  34460. var OctreeBlock = (function () {
  34461. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34462. this.entries = new Array();
  34463. this._boundingVectors = new Array();
  34464. this._capacity = capacity;
  34465. this._depth = depth;
  34466. this._maxDepth = maxDepth;
  34467. this._creationFunc = creationFunc;
  34468. this._minPoint = minPoint;
  34469. this._maxPoint = maxPoint;
  34470. this._boundingVectors.push(minPoint.clone());
  34471. this._boundingVectors.push(maxPoint.clone());
  34472. this._boundingVectors.push(minPoint.clone());
  34473. this._boundingVectors[2].x = maxPoint.x;
  34474. this._boundingVectors.push(minPoint.clone());
  34475. this._boundingVectors[3].y = maxPoint.y;
  34476. this._boundingVectors.push(minPoint.clone());
  34477. this._boundingVectors[4].z = maxPoint.z;
  34478. this._boundingVectors.push(maxPoint.clone());
  34479. this._boundingVectors[5].z = minPoint.z;
  34480. this._boundingVectors.push(maxPoint.clone());
  34481. this._boundingVectors[6].x = minPoint.x;
  34482. this._boundingVectors.push(maxPoint.clone());
  34483. this._boundingVectors[7].y = minPoint.y;
  34484. }
  34485. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34486. // Property
  34487. get: function () {
  34488. return this._capacity;
  34489. },
  34490. enumerable: true,
  34491. configurable: true
  34492. });
  34493. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34494. get: function () {
  34495. return this._minPoint;
  34496. },
  34497. enumerable: true,
  34498. configurable: true
  34499. });
  34500. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34501. get: function () {
  34502. return this._maxPoint;
  34503. },
  34504. enumerable: true,
  34505. configurable: true
  34506. });
  34507. // Methods
  34508. OctreeBlock.prototype.addEntry = function (entry) {
  34509. if (this.blocks) {
  34510. for (var index = 0; index < this.blocks.length; index++) {
  34511. var block = this.blocks[index];
  34512. block.addEntry(entry);
  34513. }
  34514. return;
  34515. }
  34516. this._creationFunc(entry, this);
  34517. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34518. this.createInnerBlocks();
  34519. }
  34520. };
  34521. OctreeBlock.prototype.addEntries = function (entries) {
  34522. for (var index = 0; index < entries.length; index++) {
  34523. var mesh = entries[index];
  34524. this.addEntry(mesh);
  34525. }
  34526. };
  34527. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34528. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34529. if (this.blocks) {
  34530. for (var index = 0; index < this.blocks.length; index++) {
  34531. var block = this.blocks[index];
  34532. block.select(frustumPlanes, selection, allowDuplicate);
  34533. }
  34534. return;
  34535. }
  34536. if (allowDuplicate) {
  34537. selection.concat(this.entries);
  34538. }
  34539. else {
  34540. selection.concatWithNoDuplicate(this.entries);
  34541. }
  34542. }
  34543. };
  34544. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34545. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34546. if (this.blocks) {
  34547. for (var index = 0; index < this.blocks.length; index++) {
  34548. var block = this.blocks[index];
  34549. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34550. }
  34551. return;
  34552. }
  34553. if (allowDuplicate) {
  34554. selection.concat(this.entries);
  34555. }
  34556. else {
  34557. selection.concatWithNoDuplicate(this.entries);
  34558. }
  34559. }
  34560. };
  34561. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34562. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34563. if (this.blocks) {
  34564. for (var index = 0; index < this.blocks.length; index++) {
  34565. var block = this.blocks[index];
  34566. block.intersectsRay(ray, selection);
  34567. }
  34568. return;
  34569. }
  34570. selection.concatWithNoDuplicate(this.entries);
  34571. }
  34572. };
  34573. OctreeBlock.prototype.createInnerBlocks = function () {
  34574. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34575. };
  34576. return OctreeBlock;
  34577. })();
  34578. BABYLON.OctreeBlock = OctreeBlock;
  34579. })(BABYLON || (BABYLON = {}));
  34580. var BABYLON;
  34581. (function (BABYLON) {
  34582. var BlurPostProcess = (function (_super) {
  34583. __extends(BlurPostProcess, _super);
  34584. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34585. var _this = this;
  34586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34587. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34588. this.direction = direction;
  34589. this.blurWidth = blurWidth;
  34590. this.onApply = function (effect) {
  34591. effect.setFloat2("screenSize", _this.width, _this.height);
  34592. effect.setVector2("direction", _this.direction);
  34593. effect.setFloat("blurWidth", _this.blurWidth);
  34594. };
  34595. }
  34596. return BlurPostProcess;
  34597. })(BABYLON.PostProcess);
  34598. BABYLON.BlurPostProcess = BlurPostProcess;
  34599. })(BABYLON || (BABYLON = {}));
  34600. var BABYLON;
  34601. (function (BABYLON) {
  34602. var RefractionPostProcess = (function (_super) {
  34603. __extends(RefractionPostProcess, _super);
  34604. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34605. var _this = this;
  34606. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34607. this.color = color;
  34608. this.depth = depth;
  34609. this.colorLevel = colorLevel;
  34610. this.onActivate = function (cam) {
  34611. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34612. };
  34613. this.onApply = function (effect) {
  34614. effect.setColor3("baseColor", _this.color);
  34615. effect.setFloat("depth", _this.depth);
  34616. effect.setFloat("colorLevel", _this.colorLevel);
  34617. effect.setTexture("refractionSampler", _this._refRexture);
  34618. };
  34619. }
  34620. // Methods
  34621. RefractionPostProcess.prototype.dispose = function (camera) {
  34622. if (this._refRexture) {
  34623. this._refRexture.dispose();
  34624. }
  34625. _super.prototype.dispose.call(this, camera);
  34626. };
  34627. return RefractionPostProcess;
  34628. })(BABYLON.PostProcess);
  34629. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34630. })(BABYLON || (BABYLON = {}));
  34631. var BABYLON;
  34632. (function (BABYLON) {
  34633. var BlackAndWhitePostProcess = (function (_super) {
  34634. __extends(BlackAndWhitePostProcess, _super);
  34635. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34636. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34637. }
  34638. return BlackAndWhitePostProcess;
  34639. })(BABYLON.PostProcess);
  34640. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34641. })(BABYLON || (BABYLON = {}));
  34642. var BABYLON;
  34643. (function (BABYLON) {
  34644. var ConvolutionPostProcess = (function (_super) {
  34645. __extends(ConvolutionPostProcess, _super);
  34646. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34647. var _this = this;
  34648. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34649. this.kernel = kernel;
  34650. this.onApply = function (effect) {
  34651. effect.setFloat2("screenSize", _this.width, _this.height);
  34652. effect.setArray("kernel", _this.kernel);
  34653. };
  34654. }
  34655. // Statics
  34656. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34657. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34658. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34659. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34660. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34661. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34662. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34663. return ConvolutionPostProcess;
  34664. })(BABYLON.PostProcess);
  34665. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34666. })(BABYLON || (BABYLON = {}));
  34667. var BABYLON;
  34668. (function (BABYLON) {
  34669. var FilterPostProcess = (function (_super) {
  34670. __extends(FilterPostProcess, _super);
  34671. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34672. var _this = this;
  34673. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34674. this.kernelMatrix = kernelMatrix;
  34675. this.onApply = function (effect) {
  34676. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34677. };
  34678. }
  34679. return FilterPostProcess;
  34680. })(BABYLON.PostProcess);
  34681. BABYLON.FilterPostProcess = FilterPostProcess;
  34682. })(BABYLON || (BABYLON = {}));
  34683. var BABYLON;
  34684. (function (BABYLON) {
  34685. var FxaaPostProcess = (function (_super) {
  34686. __extends(FxaaPostProcess, _super);
  34687. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34688. var _this = this;
  34689. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34690. this.onSizeChanged = function () {
  34691. _this.texelWidth = 1.0 / _this.width;
  34692. _this.texelHeight = 1.0 / _this.height;
  34693. };
  34694. this.onApply = function (effect) {
  34695. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34696. };
  34697. }
  34698. return FxaaPostProcess;
  34699. })(BABYLON.PostProcess);
  34700. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34701. })(BABYLON || (BABYLON = {}));
  34702. var BABYLON;
  34703. (function (BABYLON) {
  34704. var StereoscopicInterlacePostProcess = (function (_super) {
  34705. __extends(StereoscopicInterlacePostProcess, _super);
  34706. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34707. var _this = this;
  34708. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34709. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34710. this.onSizeChanged = function () {
  34711. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34712. };
  34713. this.onApply = function (effect) {
  34714. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34715. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34716. };
  34717. }
  34718. return StereoscopicInterlacePostProcess;
  34719. })(BABYLON.PostProcess);
  34720. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34721. })(BABYLON || (BABYLON = {}));
  34722. var BABYLON;
  34723. (function (BABYLON) {
  34724. var LensFlare = (function () {
  34725. function LensFlare(size, position, color, imgUrl, system) {
  34726. this.size = size;
  34727. this.position = position;
  34728. this.dispose = function () {
  34729. if (this.texture) {
  34730. this.texture.dispose();
  34731. }
  34732. // Remove from scene
  34733. var index = this._system.lensFlares.indexOf(this);
  34734. this._system.lensFlares.splice(index, 1);
  34735. };
  34736. this.color = color || new BABYLON.Color3(1, 1, 1);
  34737. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34738. this._system = system;
  34739. system.lensFlares.push(this);
  34740. }
  34741. return LensFlare;
  34742. })();
  34743. BABYLON.LensFlare = LensFlare;
  34744. })(BABYLON || (BABYLON = {}));
  34745. var BABYLON;
  34746. (function (BABYLON) {
  34747. var LensFlareSystem = (function () {
  34748. function LensFlareSystem(name, emitter, scene) {
  34749. this.name = name;
  34750. this.lensFlares = new Array();
  34751. this.borderLimit = 300;
  34752. this.layerMask = 0x0FFFFFFF;
  34753. this._vertexDeclaration = [2];
  34754. this._vertexStrideSize = 2 * 4;
  34755. this._isEnabled = true;
  34756. this._scene = scene;
  34757. this._emitter = emitter;
  34758. scene.lensFlareSystems.push(this);
  34759. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34760. // VBO
  34761. var vertices = [];
  34762. vertices.push(1, 1);
  34763. vertices.push(-1, 1);
  34764. vertices.push(-1, -1);
  34765. vertices.push(1, -1);
  34766. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34767. // Indices
  34768. var indices = [];
  34769. indices.push(0);
  34770. indices.push(1);
  34771. indices.push(2);
  34772. indices.push(0);
  34773. indices.push(2);
  34774. indices.push(3);
  34775. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34776. // Effects
  34777. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34778. }
  34779. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34780. get: function () {
  34781. return this._isEnabled;
  34782. },
  34783. set: function (value) {
  34784. this._isEnabled = value;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. LensFlareSystem.prototype.getScene = function () {
  34790. return this._scene;
  34791. };
  34792. LensFlareSystem.prototype.getEmitter = function () {
  34793. return this._emitter;
  34794. };
  34795. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34796. this._emitter = newEmitter;
  34797. };
  34798. LensFlareSystem.prototype.getEmitterPosition = function () {
  34799. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34800. };
  34801. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34802. var position = this.getEmitterPosition();
  34803. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34804. this._positionX = position.x;
  34805. this._positionY = position.y;
  34806. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34807. if (position.z > 0) {
  34808. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34809. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34810. return true;
  34811. }
  34812. }
  34813. return false;
  34814. };
  34815. LensFlareSystem.prototype._isVisible = function () {
  34816. if (!this._isEnabled) {
  34817. return false;
  34818. }
  34819. var emitterPosition = this.getEmitterPosition();
  34820. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34821. var distance = direction.length();
  34822. direction.normalize();
  34823. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34824. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34825. return !pickInfo.hit || pickInfo.distance > distance;
  34826. };
  34827. LensFlareSystem.prototype.render = function () {
  34828. if (!this._effect.isReady())
  34829. return false;
  34830. var engine = this._scene.getEngine();
  34831. var viewport = this._scene.activeCamera.viewport;
  34832. var globalViewport = viewport.toScreenGlobal(engine);
  34833. // Position
  34834. if (!this.computeEffectivePosition(globalViewport)) {
  34835. return false;
  34836. }
  34837. // Visibility
  34838. if (!this._isVisible()) {
  34839. return false;
  34840. }
  34841. // Intensity
  34842. var awayX;
  34843. var awayY;
  34844. if (this._positionX < this.borderLimit + globalViewport.x) {
  34845. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34846. }
  34847. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34848. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34849. }
  34850. else {
  34851. awayX = 0;
  34852. }
  34853. if (this._positionY < this.borderLimit + globalViewport.y) {
  34854. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34855. }
  34856. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34857. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34858. }
  34859. else {
  34860. awayY = 0;
  34861. }
  34862. var away = (awayX > awayY) ? awayX : awayY;
  34863. if (away > this.borderLimit) {
  34864. away = this.borderLimit;
  34865. }
  34866. var intensity = 1.0 - (away / this.borderLimit);
  34867. if (intensity < 0) {
  34868. return false;
  34869. }
  34870. if (intensity > 1.0) {
  34871. intensity = 1.0;
  34872. }
  34873. // Position
  34874. var centerX = globalViewport.x + globalViewport.width / 2;
  34875. var centerY = globalViewport.y + globalViewport.height / 2;
  34876. var distX = centerX - this._positionX;
  34877. var distY = centerY - this._positionY;
  34878. // Effects
  34879. engine.enableEffect(this._effect);
  34880. engine.setState(false);
  34881. engine.setDepthBuffer(false);
  34882. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34883. // VBOs
  34884. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34885. // Flares
  34886. for (var index = 0; index < this.lensFlares.length; index++) {
  34887. var flare = this.lensFlares[index];
  34888. var x = centerX - (distX * flare.position);
  34889. var y = centerY - (distY * flare.position);
  34890. var cw = flare.size;
  34891. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34892. var cx = 2 * (x / globalViewport.width) - 1.0;
  34893. var cy = 1.0 - 2 * (y / globalViewport.height);
  34894. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34895. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34896. // Texture
  34897. this._effect.setTexture("textureSampler", flare.texture);
  34898. // Color
  34899. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34900. // Draw order
  34901. engine.draw(true, 0, 6);
  34902. }
  34903. engine.setDepthBuffer(true);
  34904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34905. return true;
  34906. };
  34907. LensFlareSystem.prototype.dispose = function () {
  34908. if (this._vertexBuffer) {
  34909. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34910. this._vertexBuffer = null;
  34911. }
  34912. if (this._indexBuffer) {
  34913. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34914. this._indexBuffer = null;
  34915. }
  34916. while (this.lensFlares.length) {
  34917. this.lensFlares[0].dispose();
  34918. }
  34919. // Remove from scene
  34920. var index = this._scene.lensFlareSystems.indexOf(this);
  34921. this._scene.lensFlareSystems.splice(index, 1);
  34922. };
  34923. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34924. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34925. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34926. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34927. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34928. var parsedFlare = parsedLensFlareSystem.flares[index];
  34929. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34930. }
  34931. return lensFlareSystem;
  34932. };
  34933. LensFlareSystem.prototype.serialize = function () {
  34934. var serializationObject = {};
  34935. serializationObject.emitterId = this.getEmitter().id;
  34936. serializationObject.borderLimit = this.borderLimit;
  34937. serializationObject.flares = [];
  34938. for (var index = 0; index < this.lensFlares.length; index++) {
  34939. var flare = this.lensFlares[index];
  34940. serializationObject.flares.push({
  34941. size: flare.size,
  34942. position: flare.position,
  34943. color: flare.color.asArray(),
  34944. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34945. });
  34946. }
  34947. return serializationObject;
  34948. };
  34949. return LensFlareSystem;
  34950. })();
  34951. BABYLON.LensFlareSystem = LensFlareSystem;
  34952. })(BABYLON || (BABYLON = {}));
  34953. var BABYLON;
  34954. (function (BABYLON) {
  34955. // We're mainly based on the logic defined into the FreeCamera code
  34956. var DeviceOrientationCamera = (function (_super) {
  34957. __extends(DeviceOrientationCamera, _super);
  34958. function DeviceOrientationCamera(name, position, scene) {
  34959. var _this = this;
  34960. _super.call(this, name, position, scene);
  34961. this._offsetX = null;
  34962. this._offsetY = null;
  34963. this._orientationGamma = 0;
  34964. this._orientationBeta = 0;
  34965. this._initialOrientationGamma = 0;
  34966. this._initialOrientationBeta = 0;
  34967. this.angularSensibility = 10000.0;
  34968. this.moveSensibility = 50.0;
  34969. window.addEventListener("resize", function () {
  34970. _this._initialOrientationGamma = null;
  34971. }, false);
  34972. }
  34973. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34974. var _this = this;
  34975. if (this._attachedCanvas) {
  34976. return;
  34977. }
  34978. this._attachedCanvas = canvas;
  34979. if (!this._orientationChanged) {
  34980. this._orientationChanged = function (evt) {
  34981. if (!_this._initialOrientationGamma) {
  34982. _this._initialOrientationGamma = evt.gamma;
  34983. _this._initialOrientationBeta = evt.beta;
  34984. }
  34985. _this._orientationGamma = evt.gamma;
  34986. _this._orientationBeta = evt.beta;
  34987. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34988. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34989. };
  34990. }
  34991. window.addEventListener("deviceorientation", this._orientationChanged);
  34992. };
  34993. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34994. if (this._attachedCanvas !== canvas) {
  34995. return;
  34996. }
  34997. window.removeEventListener("deviceorientation", this._orientationChanged);
  34998. this._attachedCanvas = null;
  34999. this._orientationGamma = 0;
  35000. this._orientationBeta = 0;
  35001. this._initialOrientationGamma = 0;
  35002. this._initialOrientationBeta = 0;
  35003. };
  35004. DeviceOrientationCamera.prototype._checkInputs = function () {
  35005. if (!this._offsetX) {
  35006. return;
  35007. }
  35008. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35009. var speed = this._computeLocalCameraSpeed();
  35010. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35011. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35012. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35013. _super.prototype._checkInputs.call(this);
  35014. };
  35015. DeviceOrientationCamera.prototype.getTypeName = function () {
  35016. return "DeviceOrientationCamera";
  35017. };
  35018. __decorate([
  35019. BABYLON.serialize()
  35020. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35021. __decorate([
  35022. BABYLON.serialize()
  35023. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35024. return DeviceOrientationCamera;
  35025. })(BABYLON.FreeCamera);
  35026. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35027. })(BABYLON || (BABYLON = {}));
  35028. var BABYLON;
  35029. (function (BABYLON) {
  35030. var Analyser = (function () {
  35031. function Analyser(scene) {
  35032. this.SMOOTHING = 0.75;
  35033. this.FFT_SIZE = 512;
  35034. this.BARGRAPHAMPLITUDE = 256;
  35035. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35036. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35037. this._scene = scene;
  35038. this._audioEngine = BABYLON.Engine.audioEngine;
  35039. if (this._audioEngine.canUseWebAudio) {
  35040. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35041. this._webAudioAnalyser.minDecibels = -140;
  35042. this._webAudioAnalyser.maxDecibels = 0;
  35043. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35044. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35045. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35046. }
  35047. }
  35048. Analyser.prototype.getFrequencyBinCount = function () {
  35049. if (this._audioEngine.canUseWebAudio) {
  35050. return this._webAudioAnalyser.frequencyBinCount;
  35051. }
  35052. else {
  35053. return 0;
  35054. }
  35055. };
  35056. Analyser.prototype.getByteFrequencyData = function () {
  35057. if (this._audioEngine.canUseWebAudio) {
  35058. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35059. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35060. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35061. }
  35062. return this._byteFreqs;
  35063. };
  35064. Analyser.prototype.getByteTimeDomainData = function () {
  35065. if (this._audioEngine.canUseWebAudio) {
  35066. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35067. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35068. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35069. }
  35070. return this._byteTime;
  35071. };
  35072. Analyser.prototype.getFloatFrequencyData = function () {
  35073. if (this._audioEngine.canUseWebAudio) {
  35074. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35075. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35076. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35077. }
  35078. return this._floatFreqs;
  35079. };
  35080. Analyser.prototype.drawDebugCanvas = function () {
  35081. var _this = this;
  35082. if (this._audioEngine.canUseWebAudio) {
  35083. if (!this._debugCanvas) {
  35084. this._debugCanvas = document.createElement("canvas");
  35085. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35086. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35087. this._debugCanvas.style.position = "absolute";
  35088. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35089. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35090. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35091. document.body.appendChild(this._debugCanvas);
  35092. this._registerFunc = function () {
  35093. _this.drawDebugCanvas();
  35094. };
  35095. this._scene.registerBeforeRender(this._registerFunc);
  35096. }
  35097. if (this._registerFunc) {
  35098. var workingArray = this.getByteFrequencyData();
  35099. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35100. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35101. // Draw the frequency domain chart.
  35102. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35103. var value = workingArray[i];
  35104. var percent = value / this.BARGRAPHAMPLITUDE;
  35105. var height = this.DEBUGCANVASSIZE.height * percent;
  35106. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35107. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35108. var hue = i / this.getFrequencyBinCount() * 360;
  35109. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35110. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35111. }
  35112. }
  35113. }
  35114. };
  35115. Analyser.prototype.stopDebugCanvas = function () {
  35116. if (this._debugCanvas) {
  35117. this._scene.unregisterBeforeRender(this._registerFunc);
  35118. this._registerFunc = null;
  35119. document.body.removeChild(this._debugCanvas);
  35120. this._debugCanvas = null;
  35121. this._debugCanvasContext = null;
  35122. }
  35123. };
  35124. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35125. if (this._audioEngine.canUseWebAudio) {
  35126. inputAudioNode.connect(this._webAudioAnalyser);
  35127. this._webAudioAnalyser.connect(outputAudioNode);
  35128. }
  35129. };
  35130. Analyser.prototype.dispose = function () {
  35131. if (this._audioEngine.canUseWebAudio) {
  35132. this._webAudioAnalyser.disconnect();
  35133. }
  35134. };
  35135. return Analyser;
  35136. })();
  35137. BABYLON.Analyser = Analyser;
  35138. })(BABYLON || (BABYLON = {}));
  35139. var BABYLON;
  35140. (function (BABYLON) {
  35141. var AudioEngine = (function () {
  35142. function AudioEngine() {
  35143. this._audioContext = null;
  35144. this._audioContextInitialized = false;
  35145. this.canUseWebAudio = false;
  35146. this.WarnedWebAudioUnsupported = false;
  35147. this.unlocked = false;
  35148. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35149. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35150. this.canUseWebAudio = true;
  35151. }
  35152. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35153. this._unlockiOSaudio();
  35154. }
  35155. else {
  35156. this.unlocked = true;
  35157. }
  35158. }
  35159. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35160. get: function () {
  35161. if (!this._audioContextInitialized) {
  35162. this._initializeAudioContext();
  35163. }
  35164. return this._audioContext;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. AudioEngine.prototype._unlockiOSaudio = function () {
  35170. var _this = this;
  35171. var unlockaudio = function () {
  35172. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35173. var source = _this.audioContext.createBufferSource();
  35174. source.buffer = buffer;
  35175. source.connect(_this.audioContext.destination);
  35176. source.start(0);
  35177. setTimeout(function () {
  35178. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35179. _this.unlocked = true;
  35180. window.removeEventListener('touchend', unlockaudio, false);
  35181. if (_this.onAudioUnlocked) {
  35182. _this.onAudioUnlocked();
  35183. }
  35184. }
  35185. }, 0);
  35186. };
  35187. window.addEventListener('touchend', unlockaudio, false);
  35188. };
  35189. AudioEngine.prototype._initializeAudioContext = function () {
  35190. try {
  35191. if (this.canUseWebAudio) {
  35192. this._audioContext = new AudioContext();
  35193. // create a global volume gain node
  35194. this.masterGain = this._audioContext.createGain();
  35195. this.masterGain.gain.value = 1;
  35196. this.masterGain.connect(this._audioContext.destination);
  35197. this._audioContextInitialized = true;
  35198. }
  35199. }
  35200. catch (e) {
  35201. this.canUseWebAudio = false;
  35202. BABYLON.Tools.Error("Web Audio: " + e.message);
  35203. }
  35204. };
  35205. AudioEngine.prototype.dispose = function () {
  35206. if (this.canUseWebAudio && this._audioContextInitialized) {
  35207. if (this._connectedAnalyser) {
  35208. this._connectedAnalyser.stopDebugCanvas();
  35209. this._connectedAnalyser.dispose();
  35210. this.masterGain.disconnect();
  35211. this.masterGain.connect(this._audioContext.destination);
  35212. this._connectedAnalyser = null;
  35213. }
  35214. this.masterGain.gain.value = 1;
  35215. }
  35216. this.WarnedWebAudioUnsupported = false;
  35217. };
  35218. AudioEngine.prototype.getGlobalVolume = function () {
  35219. if (this.canUseWebAudio && this._audioContextInitialized) {
  35220. return this.masterGain.gain.value;
  35221. }
  35222. else {
  35223. return -1;
  35224. }
  35225. };
  35226. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35227. if (this.canUseWebAudio && this._audioContextInitialized) {
  35228. this.masterGain.gain.value = newVolume;
  35229. }
  35230. };
  35231. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35232. if (this._connectedAnalyser) {
  35233. this._connectedAnalyser.stopDebugCanvas();
  35234. }
  35235. if (this.canUseWebAudio && this._audioContextInitialized) {
  35236. this._connectedAnalyser = analyser;
  35237. this.masterGain.disconnect();
  35238. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35239. }
  35240. };
  35241. return AudioEngine;
  35242. })();
  35243. BABYLON.AudioEngine = AudioEngine;
  35244. })(BABYLON || (BABYLON = {}));
  35245. var BABYLON;
  35246. (function (BABYLON) {
  35247. var Sound = (function () {
  35248. /**
  35249. * Create a sound and attach it to a scene
  35250. * @param name Name of your sound
  35251. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35252. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35253. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35254. */
  35255. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35256. var _this = this;
  35257. this.autoplay = false;
  35258. this.loop = false;
  35259. this.useCustomAttenuation = false;
  35260. this.spatialSound = false;
  35261. this.refDistance = 1;
  35262. this.rolloffFactor = 1;
  35263. this.maxDistance = 100;
  35264. this.distanceModel = "linear";
  35265. this._panningModel = "equalpower";
  35266. this._playbackRate = 1;
  35267. this._streaming = false;
  35268. this._startTime = 0;
  35269. this._startOffset = 0;
  35270. this._position = BABYLON.Vector3.Zero();
  35271. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35272. this._volume = 1;
  35273. this._isLoaded = false;
  35274. this._isReadyToPlay = false;
  35275. this.isPlaying = false;
  35276. this.isPaused = false;
  35277. this._isDirectional = false;
  35278. // Used if you'd like to create a directional sound.
  35279. // If not set, the sound will be omnidirectional
  35280. this._coneInnerAngle = 360;
  35281. this._coneOuterAngle = 360;
  35282. this._coneOuterGain = 0;
  35283. this._isOutputConnected = false;
  35284. this.name = name;
  35285. this._scene = scene;
  35286. this._readyToPlayCallback = readyToPlayCallback;
  35287. // Default custom attenuation function is a linear attenuation
  35288. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35289. if (currentDistance < maxDistance) {
  35290. return currentVolume * (1 - currentDistance / maxDistance);
  35291. }
  35292. else {
  35293. return 0;
  35294. }
  35295. };
  35296. if (options) {
  35297. this.autoplay = options.autoplay || false;
  35298. this.loop = options.loop || false;
  35299. // if volume === 0, we need another way to check this option
  35300. if (options.volume !== undefined) {
  35301. this._volume = options.volume;
  35302. }
  35303. this.spatialSound = options.spatialSound || false;
  35304. this.maxDistance = options.maxDistance || 100;
  35305. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35306. this.rolloffFactor = options.rolloffFactor || 1;
  35307. this.refDistance = options.refDistance || 1;
  35308. this.distanceModel = options.distanceModel || "linear";
  35309. this._playbackRate = options.playbackRate || 1;
  35310. this._streaming = options.streaming || false;
  35311. }
  35312. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35313. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35314. this._soundGain.gain.value = this._volume;
  35315. this._inputAudioNode = this._soundGain;
  35316. this._ouputAudioNode = this._soundGain;
  35317. if (this.spatialSound) {
  35318. this._createSpatialParameters();
  35319. }
  35320. this._scene.mainSoundTrack.AddSound(this);
  35321. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35322. if (urlOrArrayBuffer) {
  35323. // If it's an URL
  35324. if (typeof (urlOrArrayBuffer) === "string") {
  35325. // Loading sound using XHR2
  35326. if (!this._streaming) {
  35327. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35328. }
  35329. else {
  35330. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35331. this._htmlAudioElement.controls = false;
  35332. this._htmlAudioElement.loop = this.loop;
  35333. this._htmlAudioElement.crossOrigin = "anonymous";
  35334. this._htmlAudioElement.preload = "auto";
  35335. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35336. _this._isReadyToPlay = true;
  35337. if (_this.autoplay) {
  35338. _this.play();
  35339. }
  35340. if (_this._readyToPlayCallback) {
  35341. _this._readyToPlayCallback();
  35342. }
  35343. });
  35344. document.body.appendChild(this._htmlAudioElement);
  35345. }
  35346. }
  35347. else {
  35348. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35349. if (urlOrArrayBuffer.byteLength > 0) {
  35350. this._soundLoaded(urlOrArrayBuffer);
  35351. }
  35352. }
  35353. else {
  35354. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35355. }
  35356. }
  35357. }
  35358. }
  35359. else {
  35360. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35361. this._scene.mainSoundTrack.AddSound(this);
  35362. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35363. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35364. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35365. }
  35366. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35367. if (this._readyToPlayCallback) {
  35368. window.setTimeout(function () {
  35369. _this._readyToPlayCallback();
  35370. }, 1000);
  35371. }
  35372. }
  35373. }
  35374. Sound.prototype.dispose = function () {
  35375. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35376. if (this.isPlaying) {
  35377. this.stop();
  35378. }
  35379. this._isReadyToPlay = false;
  35380. if (this.soundTrackId === -1) {
  35381. this._scene.mainSoundTrack.RemoveSound(this);
  35382. }
  35383. else {
  35384. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35385. }
  35386. if (this._soundGain) {
  35387. this._soundGain.disconnect();
  35388. this._soundGain = null;
  35389. }
  35390. if (this._soundPanner) {
  35391. this._soundPanner.disconnect();
  35392. this._soundPanner = null;
  35393. }
  35394. if (this._soundSource) {
  35395. this._soundSource.disconnect();
  35396. this._soundSource = null;
  35397. }
  35398. this._audioBuffer = null;
  35399. if (this._htmlAudioElement) {
  35400. this._htmlAudioElement.pause();
  35401. this._htmlAudioElement.src = "";
  35402. document.body.removeChild(this._htmlAudioElement);
  35403. }
  35404. if (this._connectedMesh) {
  35405. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35406. this._connectedMesh = null;
  35407. }
  35408. }
  35409. };
  35410. Sound.prototype._soundLoaded = function (audioData) {
  35411. var _this = this;
  35412. this._isLoaded = true;
  35413. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35414. _this._audioBuffer = buffer;
  35415. _this._isReadyToPlay = true;
  35416. if (_this.autoplay) {
  35417. _this.play();
  35418. }
  35419. if (_this._readyToPlayCallback) {
  35420. _this._readyToPlayCallback();
  35421. }
  35422. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35423. };
  35424. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35425. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35426. this._audioBuffer = audioBuffer;
  35427. this._isReadyToPlay = true;
  35428. }
  35429. };
  35430. Sound.prototype.updateOptions = function (options) {
  35431. if (options) {
  35432. this.loop = options.loop || this.loop;
  35433. this.maxDistance = options.maxDistance || this.maxDistance;
  35434. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35435. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35436. this.refDistance = options.refDistance || this.refDistance;
  35437. this.distanceModel = options.distanceModel || this.distanceModel;
  35438. this._playbackRate = options.playbackRate || this._playbackRate;
  35439. this._updateSpatialParameters();
  35440. if (this.isPlaying) {
  35441. if (this._streaming) {
  35442. this._htmlAudioElement.playbackRate = this._playbackRate;
  35443. }
  35444. else {
  35445. this._soundSource.playbackRate.value = this._playbackRate;
  35446. }
  35447. }
  35448. }
  35449. };
  35450. Sound.prototype._createSpatialParameters = function () {
  35451. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35452. if (this._scene.headphone) {
  35453. this._panningModel = "HRTF";
  35454. }
  35455. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35456. this._updateSpatialParameters();
  35457. this._soundPanner.connect(this._ouputAudioNode);
  35458. this._inputAudioNode = this._soundPanner;
  35459. }
  35460. };
  35461. Sound.prototype._updateSpatialParameters = function () {
  35462. if (this.spatialSound) {
  35463. if (this.useCustomAttenuation) {
  35464. // Tricks to disable in a way embedded Web Audio attenuation
  35465. this._soundPanner.distanceModel = "linear";
  35466. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35467. this._soundPanner.refDistance = 1;
  35468. this._soundPanner.rolloffFactor = 1;
  35469. this._soundPanner.panningModel = this._panningModel;
  35470. }
  35471. else {
  35472. this._soundPanner.distanceModel = this.distanceModel;
  35473. this._soundPanner.maxDistance = this.maxDistance;
  35474. this._soundPanner.refDistance = this.refDistance;
  35475. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35476. this._soundPanner.panningModel = this._panningModel;
  35477. }
  35478. }
  35479. };
  35480. Sound.prototype.switchPanningModelToHRTF = function () {
  35481. this._panningModel = "HRTF";
  35482. this._switchPanningModel();
  35483. };
  35484. Sound.prototype.switchPanningModelToEqualPower = function () {
  35485. this._panningModel = "equalpower";
  35486. this._switchPanningModel();
  35487. };
  35488. Sound.prototype._switchPanningModel = function () {
  35489. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35490. this._soundPanner.panningModel = this._panningModel;
  35491. }
  35492. };
  35493. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35494. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35495. if (this._isOutputConnected) {
  35496. this._ouputAudioNode.disconnect();
  35497. }
  35498. this._ouputAudioNode.connect(soundTrackAudioNode);
  35499. this._isOutputConnected = true;
  35500. }
  35501. };
  35502. /**
  35503. * Transform this sound into a directional source
  35504. * @param coneInnerAngle Size of the inner cone in degree
  35505. * @param coneOuterAngle Size of the outer cone in degree
  35506. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35507. */
  35508. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35509. if (coneOuterAngle < coneInnerAngle) {
  35510. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35511. return;
  35512. }
  35513. this._coneInnerAngle = coneInnerAngle;
  35514. this._coneOuterAngle = coneOuterAngle;
  35515. this._coneOuterGain = coneOuterGain;
  35516. this._isDirectional = true;
  35517. if (this.isPlaying && this.loop) {
  35518. this.stop();
  35519. this.play();
  35520. }
  35521. };
  35522. Sound.prototype.setPosition = function (newPosition) {
  35523. this._position = newPosition;
  35524. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35525. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35526. }
  35527. };
  35528. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35529. this._localDirection = newLocalDirection;
  35530. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35531. this._updateDirection();
  35532. }
  35533. };
  35534. Sound.prototype._updateDirection = function () {
  35535. var mat = this._connectedMesh.getWorldMatrix();
  35536. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35537. direction.normalize();
  35538. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35539. };
  35540. Sound.prototype.updateDistanceFromListener = function () {
  35541. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35542. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35543. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35544. }
  35545. };
  35546. Sound.prototype.setAttenuationFunction = function (callback) {
  35547. this._customAttenuationFunction = callback;
  35548. };
  35549. /**
  35550. * Play the sound
  35551. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35552. */
  35553. Sound.prototype.play = function (time) {
  35554. var _this = this;
  35555. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35556. try {
  35557. if (this._startOffset < 0) {
  35558. time = -this._startOffset;
  35559. this._startOffset = 0;
  35560. }
  35561. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35562. if (!this._soundSource || !this._streamingSource) {
  35563. if (this.spatialSound) {
  35564. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35565. if (this._isDirectional) {
  35566. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35567. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35568. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35569. if (this._connectedMesh) {
  35570. this._updateDirection();
  35571. }
  35572. else {
  35573. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35574. }
  35575. }
  35576. }
  35577. }
  35578. if (this._streaming) {
  35579. if (!this._streamingSource) {
  35580. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35581. this._htmlAudioElement.onended = function () { _this._onended(); };
  35582. this._htmlAudioElement.playbackRate = this._playbackRate;
  35583. }
  35584. this._streamingSource.disconnect();
  35585. this._streamingSource.connect(this._inputAudioNode);
  35586. this._htmlAudioElement.play();
  35587. }
  35588. else {
  35589. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35590. this._soundSource.buffer = this._audioBuffer;
  35591. this._soundSource.connect(this._inputAudioNode);
  35592. this._soundSource.loop = this.loop;
  35593. this._soundSource.playbackRate.value = this._playbackRate;
  35594. this._soundSource.onended = function () { _this._onended(); };
  35595. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35596. }
  35597. this._startTime = startTime;
  35598. this.isPlaying = true;
  35599. this.isPaused = false;
  35600. }
  35601. catch (ex) {
  35602. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35603. }
  35604. }
  35605. };
  35606. Sound.prototype._onended = function () {
  35607. this.isPlaying = false;
  35608. if (this.onended) {
  35609. this.onended();
  35610. }
  35611. };
  35612. /**
  35613. * Stop the sound
  35614. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35615. */
  35616. Sound.prototype.stop = function (time) {
  35617. if (this.isPlaying) {
  35618. if (this._streaming) {
  35619. this._htmlAudioElement.pause();
  35620. // Test needed for Firefox or it will generate an Invalid State Error
  35621. if (this._htmlAudioElement.currentTime > 0) {
  35622. this._htmlAudioElement.currentTime = 0;
  35623. }
  35624. }
  35625. else {
  35626. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35627. this._soundSource.stop(stopTime);
  35628. if (!this.isPaused) {
  35629. this._startOffset = 0;
  35630. }
  35631. }
  35632. this.isPlaying = false;
  35633. }
  35634. };
  35635. Sound.prototype.pause = function () {
  35636. if (this.isPlaying) {
  35637. this.isPaused = true;
  35638. if (this._streaming) {
  35639. this._htmlAudioElement.pause();
  35640. }
  35641. else {
  35642. this.stop(0);
  35643. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35644. }
  35645. }
  35646. };
  35647. Sound.prototype.setVolume = function (newVolume, time) {
  35648. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35649. if (time) {
  35650. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35651. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35652. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35653. }
  35654. else {
  35655. this._soundGain.gain.value = newVolume;
  35656. }
  35657. }
  35658. this._volume = newVolume;
  35659. };
  35660. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35661. this._playbackRate = newPlaybackRate;
  35662. if (this.isPlaying) {
  35663. if (this._streaming) {
  35664. this._htmlAudioElement.playbackRate = this._playbackRate;
  35665. }
  35666. else {
  35667. this._soundSource.playbackRate.value = this._playbackRate;
  35668. }
  35669. }
  35670. };
  35671. Sound.prototype.getVolume = function () {
  35672. return this._volume;
  35673. };
  35674. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35675. var _this = this;
  35676. if (this._connectedMesh) {
  35677. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35678. this._registerFunc = null;
  35679. }
  35680. this._connectedMesh = meshToConnectTo;
  35681. if (!this.spatialSound) {
  35682. this.spatialSound = true;
  35683. this._createSpatialParameters();
  35684. if (this.isPlaying && this.loop) {
  35685. this.stop();
  35686. this.play();
  35687. }
  35688. }
  35689. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35690. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35691. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35692. };
  35693. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35694. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35695. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35696. this._updateDirection();
  35697. }
  35698. };
  35699. Sound.prototype.clone = function () {
  35700. var _this = this;
  35701. if (!this._streaming) {
  35702. var setBufferAndRun = function () {
  35703. if (_this._isReadyToPlay) {
  35704. clonedSound._audioBuffer = _this.getAudioBuffer();
  35705. clonedSound._isReadyToPlay = true;
  35706. if (clonedSound.autoplay) {
  35707. clonedSound.play();
  35708. }
  35709. }
  35710. else {
  35711. window.setTimeout(setBufferAndRun, 300);
  35712. }
  35713. };
  35714. var currentOptions = {
  35715. autoplay: this.autoplay, loop: this.loop,
  35716. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35717. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35718. refDistance: this.refDistance, distanceModel: this.distanceModel
  35719. };
  35720. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35721. if (this.useCustomAttenuation) {
  35722. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35723. }
  35724. clonedSound.setPosition(this._position);
  35725. clonedSound.setPlaybackRate(this._playbackRate);
  35726. setBufferAndRun();
  35727. return clonedSound;
  35728. }
  35729. else {
  35730. return null;
  35731. }
  35732. };
  35733. Sound.prototype.getAudioBuffer = function () {
  35734. return this._audioBuffer;
  35735. };
  35736. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35737. var soundName = parsedSound.name;
  35738. var soundUrl;
  35739. if (parsedSound.url) {
  35740. soundUrl = rootUrl + parsedSound.url;
  35741. }
  35742. else {
  35743. soundUrl = rootUrl + soundName;
  35744. }
  35745. var options = {
  35746. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35747. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35748. rolloffFactor: parsedSound.rolloffFactor,
  35749. refDistance: parsedSound.refDistance,
  35750. distanceModel: parsedSound.distanceModel,
  35751. playbackRate: parsedSound.playbackRate
  35752. };
  35753. var newSound;
  35754. if (!sourceSound) {
  35755. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35756. scene._addPendingData(newSound);
  35757. }
  35758. else {
  35759. var setBufferAndRun = function () {
  35760. if (sourceSound._isReadyToPlay) {
  35761. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35762. newSound._isReadyToPlay = true;
  35763. if (newSound.autoplay) {
  35764. newSound.play();
  35765. }
  35766. }
  35767. else {
  35768. window.setTimeout(setBufferAndRun, 300);
  35769. }
  35770. };
  35771. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35772. setBufferAndRun();
  35773. }
  35774. if (parsedSound.position) {
  35775. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35776. newSound.setPosition(soundPosition);
  35777. }
  35778. if (parsedSound.isDirectional) {
  35779. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35780. if (parsedSound.localDirectionToMesh) {
  35781. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35782. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35783. }
  35784. }
  35785. if (parsedSound.connectedMeshId) {
  35786. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35787. if (connectedMesh) {
  35788. newSound.attachToMesh(connectedMesh);
  35789. }
  35790. }
  35791. return newSound;
  35792. };
  35793. return Sound;
  35794. })();
  35795. BABYLON.Sound = Sound;
  35796. })(BABYLON || (BABYLON = {}));
  35797. var BABYLON;
  35798. (function (BABYLON) {
  35799. var SoundTrack = (function () {
  35800. function SoundTrack(scene, options) {
  35801. this.id = -1;
  35802. this._isMainTrack = false;
  35803. this._isInitialized = false;
  35804. this._scene = scene;
  35805. this.soundCollection = new Array();
  35806. this._options = options;
  35807. if (!this._isMainTrack) {
  35808. this._scene.soundTracks.push(this);
  35809. this.id = this._scene.soundTracks.length - 1;
  35810. }
  35811. }
  35812. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35813. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35814. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35815. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35816. if (this._options) {
  35817. if (this._options.volume) {
  35818. this._outputAudioNode.gain.value = this._options.volume;
  35819. }
  35820. if (this._options.mainTrack) {
  35821. this._isMainTrack = this._options.mainTrack;
  35822. }
  35823. }
  35824. this._isInitialized = true;
  35825. }
  35826. };
  35827. SoundTrack.prototype.dispose = function () {
  35828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35829. if (this._connectedAnalyser) {
  35830. this._connectedAnalyser.stopDebugCanvas();
  35831. }
  35832. while (this.soundCollection.length) {
  35833. this.soundCollection[0].dispose();
  35834. }
  35835. if (this._outputAudioNode) {
  35836. this._outputAudioNode.disconnect();
  35837. }
  35838. this._outputAudioNode = null;
  35839. }
  35840. };
  35841. SoundTrack.prototype.AddSound = function (sound) {
  35842. if (!this._isInitialized) {
  35843. this._initializeSoundTrackAudioGraph();
  35844. }
  35845. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35846. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35847. }
  35848. if (sound.soundTrackId) {
  35849. if (sound.soundTrackId === -1) {
  35850. this._scene.mainSoundTrack.RemoveSound(sound);
  35851. }
  35852. else {
  35853. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35854. }
  35855. }
  35856. this.soundCollection.push(sound);
  35857. sound.soundTrackId = this.id;
  35858. };
  35859. SoundTrack.prototype.RemoveSound = function (sound) {
  35860. var index = this.soundCollection.indexOf(sound);
  35861. if (index !== -1) {
  35862. this.soundCollection.splice(index, 1);
  35863. }
  35864. };
  35865. SoundTrack.prototype.setVolume = function (newVolume) {
  35866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35867. this._outputAudioNode.gain.value = newVolume;
  35868. }
  35869. };
  35870. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35871. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35872. for (var i = 0; i < this.soundCollection.length; i++) {
  35873. this.soundCollection[i].switchPanningModelToHRTF();
  35874. }
  35875. }
  35876. };
  35877. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35878. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35879. for (var i = 0; i < this.soundCollection.length; i++) {
  35880. this.soundCollection[i].switchPanningModelToEqualPower();
  35881. }
  35882. }
  35883. };
  35884. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35885. if (this._connectedAnalyser) {
  35886. this._connectedAnalyser.stopDebugCanvas();
  35887. }
  35888. this._connectedAnalyser = analyser;
  35889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35890. this._outputAudioNode.disconnect();
  35891. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35892. }
  35893. };
  35894. return SoundTrack;
  35895. })();
  35896. BABYLON.SoundTrack = SoundTrack;
  35897. })(BABYLON || (BABYLON = {}));
  35898. var BABYLON;
  35899. (function (BABYLON) {
  35900. var DepthRenderer = (function () {
  35901. function DepthRenderer(scene, type) {
  35902. var _this = this;
  35903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35904. this._viewMatrix = BABYLON.Matrix.Zero();
  35905. this._projectionMatrix = BABYLON.Matrix.Zero();
  35906. this._transformMatrix = BABYLON.Matrix.Zero();
  35907. this._worldViewProjection = BABYLON.Matrix.Zero();
  35908. this._scene = scene;
  35909. var engine = scene.getEngine();
  35910. // Render target
  35911. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35912. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35913. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35914. this._depthMap.refreshRate = 1;
  35915. this._depthMap.renderParticles = false;
  35916. this._depthMap.renderList = null;
  35917. // set default depth value to 1.0 (far away)
  35918. this._depthMap.onClear = function (engine) {
  35919. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35920. };
  35921. // Custom render function
  35922. var renderSubMesh = function (subMesh) {
  35923. var mesh = subMesh.getRenderingMesh();
  35924. var scene = _this._scene;
  35925. var engine = scene.getEngine();
  35926. // Culling
  35927. engine.setState(subMesh.getMaterial().backFaceCulling);
  35928. // Managing instances
  35929. var batch = mesh._getInstancesRenderList(subMesh._id);
  35930. if (batch.mustReturn) {
  35931. return;
  35932. }
  35933. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35934. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35935. engine.enableEffect(_this._effect);
  35936. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35937. var material = subMesh.getMaterial();
  35938. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35939. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35940. // Alpha test
  35941. if (material && material.needAlphaTesting()) {
  35942. var alphaTexture = material.getAlphaTestTexture();
  35943. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35944. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35945. }
  35946. // Bones
  35947. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35948. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35949. }
  35950. // Draw
  35951. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35952. }
  35953. };
  35954. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35955. var index;
  35956. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35957. renderSubMesh(opaqueSubMeshes.data[index]);
  35958. }
  35959. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35960. renderSubMesh(alphaTestSubMeshes.data[index]);
  35961. }
  35962. };
  35963. }
  35964. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35965. var defines = [];
  35966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35967. var mesh = subMesh.getMesh();
  35968. var scene = mesh.getScene();
  35969. var material = subMesh.getMaterial();
  35970. // Alpha test
  35971. if (material && material.needAlphaTesting()) {
  35972. defines.push("#define ALPHATEST");
  35973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35974. attribs.push(BABYLON.VertexBuffer.UVKind);
  35975. defines.push("#define UV1");
  35976. }
  35977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35979. defines.push("#define UV2");
  35980. }
  35981. }
  35982. // Bones
  35983. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35986. if (mesh.numBoneInfluencers > 4) {
  35987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35989. }
  35990. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35991. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35992. }
  35993. else {
  35994. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35995. }
  35996. // Instances
  35997. if (useInstances) {
  35998. defines.push("#define INSTANCES");
  35999. attribs.push("world0");
  36000. attribs.push("world1");
  36001. attribs.push("world2");
  36002. attribs.push("world3");
  36003. }
  36004. // Get correct effect
  36005. var join = defines.join("\n");
  36006. if (this._cachedDefines !== join) {
  36007. this._cachedDefines = join;
  36008. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36009. }
  36010. return this._effect.isReady();
  36011. };
  36012. DepthRenderer.prototype.getDepthMap = function () {
  36013. return this._depthMap;
  36014. };
  36015. // Methods
  36016. DepthRenderer.prototype.dispose = function () {
  36017. this._depthMap.dispose();
  36018. };
  36019. return DepthRenderer;
  36020. })();
  36021. BABYLON.DepthRenderer = DepthRenderer;
  36022. })(BABYLON || (BABYLON = {}));
  36023. var BABYLON;
  36024. (function (BABYLON) {
  36025. var SSAORenderingPipeline = (function (_super) {
  36026. __extends(SSAORenderingPipeline, _super);
  36027. /**
  36028. * @constructor
  36029. * @param {string} name - The rendering pipeline name
  36030. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36031. * @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 }
  36032. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36033. */
  36034. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36035. var _this = this;
  36036. _super.call(this, scene.getEngine(), name);
  36037. // Members
  36038. /**
  36039. * The PassPostProcess id in the pipeline that contains the original scene color
  36040. * @type {string}
  36041. */
  36042. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36043. /**
  36044. * The SSAO PostProcess id in the pipeline
  36045. * @type {string}
  36046. */
  36047. this.SSAORenderEffect = "SSAORenderEffect";
  36048. /**
  36049. * The horizontal blur PostProcess id in the pipeline
  36050. * @type {string}
  36051. */
  36052. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36053. /**
  36054. * The vertical blur PostProcess id in the pipeline
  36055. * @type {string}
  36056. */
  36057. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36058. /**
  36059. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36060. * @type {string}
  36061. */
  36062. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36063. /**
  36064. * The output strength of the SSAO post-process. Default value is 1.0.
  36065. * @type {number}
  36066. */
  36067. this.totalStrength = 1.0;
  36068. /**
  36069. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36070. * @type {number}
  36071. */
  36072. this.radius = 0.0001;
  36073. /**
  36074. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36075. * Must not be equal to fallOff and superior to fallOff.
  36076. * Default value is 0.975
  36077. * @type {number}
  36078. */
  36079. this.area = 0.0075;
  36080. /**
  36081. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36082. * Must not be equal to area and inferior to area.
  36083. * Default value is 0.0
  36084. * @type {number}
  36085. */
  36086. this.fallOff = 0.000001;
  36087. /**
  36088. * The base color of the SSAO post-process
  36089. * The final result is "base + ssao" between [0, 1]
  36090. * @type {number}
  36091. */
  36092. this.base = 0.5;
  36093. this._firstUpdate = true;
  36094. this._scene = scene;
  36095. // Set up assets
  36096. this._createRandomTexture();
  36097. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36098. var ssaoRatio = ratio.ssaoRatio || ratio;
  36099. var combineRatio = ratio.combineRatio || ratio;
  36100. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36101. this._createSSAOPostProcess(ssaoRatio);
  36102. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36103. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36104. this._createSSAOCombinePostProcess(combineRatio);
  36105. // Set up pipeline
  36106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36107. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36111. // Finish
  36112. scene.postProcessRenderPipelineManager.addPipeline(this);
  36113. if (cameras)
  36114. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36115. }
  36116. // Public Methods
  36117. /**
  36118. * Returns the horizontal blur PostProcess
  36119. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36120. */
  36121. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36122. return this._blurHPostProcess;
  36123. };
  36124. /**
  36125. * Returns the vertical blur PostProcess
  36126. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36127. */
  36128. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36129. return this._blurVPostProcess;
  36130. };
  36131. /**
  36132. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36133. */
  36134. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36135. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36136. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36137. this._originalColorPostProcess = undefined;
  36138. this._ssaoPostProcess = undefined;
  36139. this._blurHPostProcess = undefined;
  36140. this._blurVPostProcess = undefined;
  36141. this._ssaoCombinePostProcess = undefined;
  36142. this._randomTexture.dispose();
  36143. if (disableDepthRender)
  36144. this._scene.disableDepthRenderer();
  36145. };
  36146. // Private Methods
  36147. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36148. var _this = this;
  36149. var numSamples = 16;
  36150. var sampleSphere = [
  36151. 0.5381, 0.1856, -0.4319,
  36152. 0.1379, 0.2486, 0.4430,
  36153. 0.3371, 0.5679, -0.0057,
  36154. -0.6999, -0.0451, -0.0019,
  36155. 0.0689, -0.1598, -0.8547,
  36156. 0.0560, 0.0069, -0.1843,
  36157. -0.0146, 0.1402, 0.0762,
  36158. 0.0100, -0.1924, -0.0344,
  36159. -0.3577, -0.5301, -0.4358,
  36160. -0.3169, 0.1063, 0.0158,
  36161. 0.0103, -0.5869, 0.0046,
  36162. -0.0897, -0.4940, 0.3287,
  36163. 0.7119, -0.0154, -0.0918,
  36164. -0.0533, 0.0596, -0.5411,
  36165. 0.0352, -0.0631, 0.5460,
  36166. -0.4776, 0.2847, -0.0271
  36167. ];
  36168. var samplesFactor = 1.0 / numSamples;
  36169. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36170. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36171. "area", "fallOff", "base"
  36172. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36173. this._ssaoPostProcess.onApply = function (effect) {
  36174. if (_this._firstUpdate) {
  36175. effect.setArray3("sampleSphere", sampleSphere);
  36176. effect.setFloat("samplesFactor", samplesFactor);
  36177. effect.setFloat("randTextureTiles", 4.0);
  36178. _this._firstUpdate = false;
  36179. }
  36180. effect.setFloat("totalStrength", _this.totalStrength);
  36181. effect.setFloat("radius", _this.radius);
  36182. effect.setFloat("area", _this.area);
  36183. effect.setFloat("fallOff", _this.fallOff);
  36184. effect.setFloat("base", _this.base);
  36185. effect.setTexture("textureSampler", _this._depthTexture);
  36186. effect.setTexture("randomSampler", _this._randomTexture);
  36187. };
  36188. };
  36189. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36190. var _this = this;
  36191. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36192. this._ssaoCombinePostProcess.onApply = function (effect) {
  36193. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36194. };
  36195. };
  36196. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36197. var size = 512;
  36198. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36199. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36200. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36201. var context = this._randomTexture.getContext();
  36202. var rand = function (min, max) {
  36203. return Math.random() * (max - min) + min;
  36204. };
  36205. var randVector = BABYLON.Vector3.Zero();
  36206. for (var x = 0; x < size; x++) {
  36207. for (var y = 0; y < size; y++) {
  36208. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36209. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36210. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36211. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36212. context.fillRect(x, y, 1, 1);
  36213. }
  36214. }
  36215. this._randomTexture.update(false);
  36216. };
  36217. return SSAORenderingPipeline;
  36218. })(BABYLON.PostProcessRenderPipeline);
  36219. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36220. })(BABYLON || (BABYLON = {}));
  36221. var BABYLON;
  36222. (function (BABYLON) {
  36223. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36224. var VolumetricLightScatteringPostProcess = (function (_super) {
  36225. __extends(VolumetricLightScatteringPostProcess, _super);
  36226. /**
  36227. * @constructor
  36228. * @param {string} name - The post-process name
  36229. * @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)
  36230. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36231. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36232. * @param {number} samples - The post-process quality, default 100
  36233. * @param {number} samplingMode - The post-process filtering mode
  36234. * @param {BABYLON.Engine} engine - The babylon engine
  36235. * @param {boolean} reusable - If the post-process is reusable
  36236. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36237. */
  36238. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36239. var _this = this;
  36240. if (samples === void 0) { samples = 100; }
  36241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36242. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36243. this._screenCoordinates = BABYLON.Vector2.Zero();
  36244. /**
  36245. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36246. * @type {boolean}
  36247. */
  36248. this.useCustomMeshPosition = false;
  36249. /**
  36250. * If the post-process should inverse the light scattering direction
  36251. * @type {boolean}
  36252. */
  36253. this.invert = true;
  36254. /**
  36255. * Set to true to use the diffuseColor instead of the diffuseTexture
  36256. * @type {boolean}
  36257. */
  36258. this.useDiffuseColor = false;
  36259. /**
  36260. * Array containing the excluded meshes not rendered in the internal pass
  36261. */
  36262. this.excludedMeshes = new Array();
  36263. /**
  36264. * Controls the overall intensity of the post-process
  36265. * @type {number}
  36266. */
  36267. this.exposure = 0.3;
  36268. /**
  36269. * Dissipates each sample's contribution in range [0, 1]
  36270. * @type {number}
  36271. */
  36272. this.decay = 0.96815;
  36273. /**
  36274. * Controls the overall intensity of each sample
  36275. * @type {number}
  36276. */
  36277. this.weight = 0.58767;
  36278. /**
  36279. * Controls the density of each sample
  36280. * @type {number}
  36281. */
  36282. this.density = 0.926;
  36283. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36284. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  36285. // Configure mesh
  36286. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36287. // Configure
  36288. this._createPass(scene, ratio.passRatio || ratio);
  36289. this.onActivate = function (camera) {
  36290. if (!_this.isSupported) {
  36291. _this.dispose(camera);
  36292. }
  36293. _this.onActivate = null;
  36294. };
  36295. this.onApply = function (effect) {
  36296. _this._updateMeshScreenCoordinates(scene);
  36297. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36298. effect.setFloat("exposure", _this.exposure);
  36299. effect.setFloat("decay", _this.decay);
  36300. effect.setFloat("weight", _this.weight);
  36301. effect.setFloat("density", _this.density);
  36302. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36303. };
  36304. }
  36305. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36306. var mesh = subMesh.getMesh();
  36307. var defines = [];
  36308. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36309. var material = subMesh.getMaterial();
  36310. var needUV = false;
  36311. // Render this.mesh as default
  36312. if (mesh === this.mesh) {
  36313. if (this.useDiffuseColor) {
  36314. defines.push("#define DIFFUSE_COLOR_RENDER");
  36315. }
  36316. else if (material) {
  36317. if (material.diffuseTexture !== undefined) {
  36318. defines.push("#define BASIC_RENDER");
  36319. }
  36320. else {
  36321. defines.push("#define DIFFUSE_COLOR_RENDER");
  36322. }
  36323. }
  36324. defines.push("#define NEED_UV");
  36325. needUV = true;
  36326. }
  36327. // Alpha test
  36328. if (material) {
  36329. if (material.needAlphaTesting()) {
  36330. defines.push("#define ALPHATEST");
  36331. }
  36332. if (material.opacityTexture !== undefined) {
  36333. defines.push("#define OPACITY");
  36334. if (material.opacityTexture.getAlphaFromRGB) {
  36335. defines.push("#define OPACITYRGB");
  36336. }
  36337. if (!needUV) {
  36338. defines.push("#define NEED_UV");
  36339. }
  36340. }
  36341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36342. attribs.push(BABYLON.VertexBuffer.UVKind);
  36343. defines.push("#define UV1");
  36344. }
  36345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36346. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36347. defines.push("#define UV2");
  36348. }
  36349. }
  36350. // Bones
  36351. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36354. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36355. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36356. }
  36357. else {
  36358. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36359. }
  36360. // Instances
  36361. if (useInstances) {
  36362. defines.push("#define INSTANCES");
  36363. attribs.push("world0");
  36364. attribs.push("world1");
  36365. attribs.push("world2");
  36366. attribs.push("world3");
  36367. }
  36368. // Get correct effect
  36369. var join = defines.join("\n");
  36370. if (this._cachedDefines !== join) {
  36371. this._cachedDefines = join;
  36372. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36373. }
  36374. return this._volumetricLightScatteringPass.isReady();
  36375. };
  36376. /**
  36377. * Sets the new light position for light scattering effect
  36378. * @param {BABYLON.Vector3} The new custom light position
  36379. */
  36380. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36381. this._customMeshPosition = position;
  36382. };
  36383. /**
  36384. * Returns the light position for light scattering effect
  36385. * @return {BABYLON.Vector3} The custom light position
  36386. */
  36387. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36388. return this._customMeshPosition;
  36389. };
  36390. /**
  36391. * Disposes the internal assets and detaches the post-process from the camera
  36392. */
  36393. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36394. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36395. if (rttIndex !== -1) {
  36396. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36397. }
  36398. this._volumetricLightScatteringRTT.dispose();
  36399. _super.prototype.dispose.call(this, camera);
  36400. };
  36401. /**
  36402. * Returns the render target texture used by the post-process
  36403. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36404. */
  36405. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36406. return this._volumetricLightScatteringRTT;
  36407. };
  36408. // Private methods
  36409. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36410. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36411. return true;
  36412. }
  36413. return false;
  36414. };
  36415. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36416. var _this = this;
  36417. var engine = scene.getEngine();
  36418. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36419. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36420. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36421. this._volumetricLightScatteringRTT.renderList = null;
  36422. this._volumetricLightScatteringRTT.renderParticles = false;
  36423. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36424. // Custom render function for submeshes
  36425. var renderSubMesh = function (subMesh) {
  36426. var mesh = subMesh.getRenderingMesh();
  36427. if (_this._meshExcluded(mesh)) {
  36428. return;
  36429. }
  36430. var scene = mesh.getScene();
  36431. var engine = scene.getEngine();
  36432. // Culling
  36433. engine.setState(subMesh.getMaterial().backFaceCulling);
  36434. // Managing instances
  36435. var batch = mesh._getInstancesRenderList(subMesh._id);
  36436. if (batch.mustReturn) {
  36437. return;
  36438. }
  36439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36440. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36441. engine.enableEffect(_this._volumetricLightScatteringPass);
  36442. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36443. var material = subMesh.getMaterial();
  36444. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36445. // Alpha test
  36446. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36447. var alphaTexture = material.getAlphaTestTexture();
  36448. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36449. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36450. }
  36451. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36452. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36453. if (alphaTexture) {
  36454. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36455. }
  36456. }
  36457. if (material.opacityTexture !== undefined) {
  36458. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36459. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36460. }
  36461. }
  36462. // Bones
  36463. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36464. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36465. }
  36466. // Draw
  36467. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36468. }
  36469. };
  36470. // Render target texture callbacks
  36471. var savedSceneClearColor;
  36472. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36473. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36474. savedSceneClearColor = scene.clearColor;
  36475. scene.clearColor = sceneClearColor;
  36476. };
  36477. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36478. scene.clearColor = savedSceneClearColor;
  36479. };
  36480. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36481. var engine = scene.getEngine();
  36482. var index;
  36483. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36484. renderSubMesh(opaqueSubMeshes.data[index]);
  36485. }
  36486. engine.setAlphaTesting(true);
  36487. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36488. renderSubMesh(alphaTestSubMeshes.data[index]);
  36489. }
  36490. engine.setAlphaTesting(false);
  36491. if (transparentSubMeshes.length) {
  36492. // Sort sub meshes
  36493. for (index = 0; index < transparentSubMeshes.length; index++) {
  36494. var submesh = transparentSubMeshes.data[index];
  36495. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36496. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36497. }
  36498. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36499. sortedArray.sort(function (a, b) {
  36500. // Alpha index first
  36501. if (a._alphaIndex > b._alphaIndex) {
  36502. return 1;
  36503. }
  36504. if (a._alphaIndex < b._alphaIndex) {
  36505. return -1;
  36506. }
  36507. // Then distance to camera
  36508. if (a._distanceToCamera < b._distanceToCamera) {
  36509. return 1;
  36510. }
  36511. if (a._distanceToCamera > b._distanceToCamera) {
  36512. return -1;
  36513. }
  36514. return 0;
  36515. });
  36516. // Render sub meshes
  36517. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36518. for (index = 0; index < sortedArray.length; index++) {
  36519. renderSubMesh(sortedArray[index]);
  36520. }
  36521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36522. }
  36523. };
  36524. };
  36525. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36526. var transform = scene.getTransformMatrix();
  36527. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36528. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36529. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36530. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36531. if (this.invert)
  36532. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36533. };
  36534. // Static methods
  36535. /**
  36536. * Creates a default mesh for the Volumeric Light Scattering post-process
  36537. * @param {string} The mesh name
  36538. * @param {BABYLON.Scene} The scene where to create the mesh
  36539. * @return {BABYLON.Mesh} the default mesh
  36540. */
  36541. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36542. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36543. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36544. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36545. return mesh;
  36546. };
  36547. return VolumetricLightScatteringPostProcess;
  36548. })(BABYLON.PostProcess);
  36549. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36550. })(BABYLON || (BABYLON = {}));
  36551. // BABYLON.JS Chromatic Aberration GLSL Shader
  36552. // Author: Olivier Guyot
  36553. // Separates very slightly R, G and B colors on the edges of the screen
  36554. // Inspired by Francois Tarlier & Martins Upitis
  36555. var BABYLON;
  36556. (function (BABYLON) {
  36557. var LensRenderingPipeline = (function (_super) {
  36558. __extends(LensRenderingPipeline, _super);
  36559. /**
  36560. * @constructor
  36561. *
  36562. * Effect parameters are as follow:
  36563. * {
  36564. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36565. * edge_blur: number; // from 0 to x (1 for realism)
  36566. * distortion: number; // from 0 to x (1 for realism)
  36567. * grain_amount: number; // from 0 to 1
  36568. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36569. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36570. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36571. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36572. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36573. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36574. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36575. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36576. * }
  36577. * Note: if an effect parameter is unset, effect is disabled
  36578. *
  36579. * @param {string} name - The rendering pipeline name
  36580. * @param {object} parameters - An object containing all parameters (see above)
  36581. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36582. * @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)
  36583. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36584. */
  36585. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36586. var _this = this;
  36587. if (ratio === void 0) { ratio = 1.0; }
  36588. _super.call(this, scene.getEngine(), name);
  36589. // Lens effects can be of the following:
  36590. // - chromatic aberration (slight shift of RGB colors)
  36591. // - blur on the edge of the lens
  36592. // - lens distortion
  36593. // - depth-of-field blur & highlights enhancing
  36594. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36595. // - grain effect (noise or custom texture)
  36596. // Two additional texture samplers are needed:
  36597. // - depth map (for depth-of-field)
  36598. // - grain texture
  36599. /**
  36600. * The chromatic aberration PostProcess id in the pipeline
  36601. * @type {string}
  36602. */
  36603. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36604. /**
  36605. * The highlights enhancing PostProcess id in the pipeline
  36606. * @type {string}
  36607. */
  36608. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36609. /**
  36610. * The depth-of-field PostProcess id in the pipeline
  36611. * @type {string}
  36612. */
  36613. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36614. this._scene = scene;
  36615. // Fetch texture samplers
  36616. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36617. if (parameters.grain_texture) {
  36618. this._grainTexture = parameters.grain_texture;
  36619. }
  36620. else {
  36621. this._createGrainTexture();
  36622. }
  36623. // save parameters
  36624. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36625. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36626. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36627. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36628. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36629. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36630. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36631. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36632. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36633. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36634. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36635. // Create effects
  36636. this._createChromaticAberrationPostProcess(ratio);
  36637. this._createHighlightsPostProcess(ratio);
  36638. this._createDepthOfFieldPostProcess(ratio / 4);
  36639. // Set up pipeline
  36640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36643. if (this._highlightsGain === -1) {
  36644. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36645. }
  36646. // Finish
  36647. scene.postProcessRenderPipelineManager.addPipeline(this);
  36648. if (cameras) {
  36649. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36650. }
  36651. }
  36652. // public methods (self explanatory)
  36653. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36654. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36655. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36656. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36657. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36658. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36659. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36660. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36661. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36662. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36663. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36664. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36665. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36666. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36667. };
  36668. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36669. this._highlightsPostProcess.updateEffect();
  36670. };
  36671. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36672. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36673. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36674. this._highlightsGain = amount;
  36675. };
  36676. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36677. if (this._highlightsGain === -1) {
  36678. this._highlightsGain = 1.0;
  36679. }
  36680. this._highlightsThreshold = amount;
  36681. };
  36682. LensRenderingPipeline.prototype.disableHighlights = function () {
  36683. this._highlightsGain = -1;
  36684. };
  36685. /**
  36686. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36687. */
  36688. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36689. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36690. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36691. this._chromaticAberrationPostProcess = undefined;
  36692. this._highlightsPostProcess = undefined;
  36693. this._depthOfFieldPostProcess = undefined;
  36694. this._grainTexture.dispose();
  36695. if (disableDepthRender)
  36696. this._scene.disableDepthRenderer();
  36697. };
  36698. // colors shifting and distortion
  36699. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36700. var _this = this;
  36701. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36702. [], // samplers
  36703. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36704. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36705. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36706. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36707. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36708. };
  36709. };
  36710. // highlights enhancing
  36711. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36712. var _this = this;
  36713. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36714. [], // samplers
  36715. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36716. this._highlightsPostProcess.onApply = function (effect) {
  36717. effect.setFloat('gain', _this._highlightsGain);
  36718. effect.setFloat('threshold', _this._highlightsThreshold);
  36719. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36720. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36721. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36722. };
  36723. };
  36724. // colors shifting and distortion
  36725. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36726. var _this = this;
  36727. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36728. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36729. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36730. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36731. this._depthOfFieldPostProcess.onApply = function (effect) {
  36732. effect.setTexture("depthSampler", _this._depthTexture);
  36733. effect.setTexture("grainSampler", _this._grainTexture);
  36734. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36735. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36736. effect.setFloat('grain_amount', _this._grainAmount);
  36737. effect.setBool('blur_noise', _this._blurNoise);
  36738. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36739. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36740. effect.setFloat('distortion', _this._distortion);
  36741. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36742. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36743. effect.setFloat('aperture', _this._dofAperture);
  36744. effect.setFloat('darken', _this._dofDarken);
  36745. effect.setFloat('edge_blur', _this._edgeBlur);
  36746. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36747. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36748. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36749. };
  36750. };
  36751. // creates a black and white random noise texture, 512x512
  36752. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36753. var size = 512;
  36754. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36755. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36756. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36757. var context = this._grainTexture.getContext();
  36758. var rand = function (min, max) {
  36759. return Math.random() * (max - min) + min;
  36760. };
  36761. var value;
  36762. for (var x = 0; x < size; x++) {
  36763. for (var y = 0; y < size; y++) {
  36764. value = Math.floor(rand(0.42, 0.58) * 255);
  36765. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36766. context.fillRect(x, y, 1, 1);
  36767. }
  36768. }
  36769. this._grainTexture.update(false);
  36770. };
  36771. return LensRenderingPipeline;
  36772. })(BABYLON.PostProcessRenderPipeline);
  36773. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36774. })(BABYLON || (BABYLON = {}));
  36775. //
  36776. // This post-process allows the modification of rendered colors by using
  36777. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36778. //
  36779. // The object needs to be provided an url to a texture containing the color
  36780. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36781. // Use an image editing software to tweak the LUT to match your needs.
  36782. //
  36783. // For an example of a color LUT, see here:
  36784. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36785. // For explanations on color grading, see here:
  36786. // http://udn.epicgames.com/Three/ColorGrading.html
  36787. //
  36788. var BABYLON;
  36789. (function (BABYLON) {
  36790. var ColorCorrectionPostProcess = (function (_super) {
  36791. __extends(ColorCorrectionPostProcess, _super);
  36792. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36793. var _this = this;
  36794. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36795. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36796. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36797. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36798. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36799. this.onApply = function (effect) {
  36800. effect.setTexture("colorTable", _this._colorTableTexture);
  36801. };
  36802. }
  36803. return ColorCorrectionPostProcess;
  36804. })(BABYLON.PostProcess);
  36805. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36806. })(BABYLON || (BABYLON = {}));
  36807. var BABYLON;
  36808. (function (BABYLON) {
  36809. var HDRRenderingPipeline = (function (_super) {
  36810. __extends(HDRRenderingPipeline, _super);
  36811. /**
  36812. * @constructor
  36813. * @param {string} name - The rendering pipeline name
  36814. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36815. * @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)
  36816. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36817. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36818. */
  36819. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36820. var _this = this;
  36821. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36822. _super.call(this, scene.getEngine(), name);
  36823. /**
  36824. * Public members
  36825. */
  36826. // Gaussian Blur
  36827. /**
  36828. * Gaussian blur coefficient
  36829. * @type {number}
  36830. */
  36831. this.gaussCoeff = 0.3;
  36832. /**
  36833. * Gaussian blur mean
  36834. * @type {number}
  36835. */
  36836. this.gaussMean = 1.0;
  36837. /**
  36838. * Gaussian blur standard deviation
  36839. * @type {number}
  36840. */
  36841. this.gaussStandDev = 0.8;
  36842. /**
  36843. * Gaussian blur multiplier. Multiplies the blur effect
  36844. * @type {number}
  36845. */
  36846. this.gaussMultiplier = 4.0;
  36847. // HDR
  36848. /**
  36849. * Exposure, controls the overall intensity of the pipeline
  36850. * @type {number}
  36851. */
  36852. this.exposure = 1.0;
  36853. /**
  36854. * Minimum luminance that the post-process can output. Luminance is >= 0
  36855. * @type {number}
  36856. */
  36857. this.minimumLuminance = 1.0;
  36858. /**
  36859. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36860. * @type {number}
  36861. */
  36862. this.maximumLuminance = 1e20;
  36863. /**
  36864. * Increase rate for luminance: eye adaptation speed to dark
  36865. * @type {number}
  36866. */
  36867. this.luminanceIncreaserate = 0.5;
  36868. /**
  36869. * Decrease rate for luminance: eye adaptation speed to bright
  36870. * @type {number}
  36871. */
  36872. this.luminanceDecreaseRate = 0.5;
  36873. // Bright pass
  36874. /**
  36875. * Minimum luminance needed to compute HDR
  36876. * @type {number}
  36877. */
  36878. this.brightThreshold = 0.8;
  36879. this._needUpdate = true;
  36880. this._scene = scene;
  36881. // Bright pass
  36882. this._createBrightPassPostProcess(scene, ratio);
  36883. // Down sample X4
  36884. this._createDownSampleX4PostProcess(scene, ratio);
  36885. // Create gaussian blur post-processes
  36886. this._createGaussianBlurPostProcess(scene, ratio);
  36887. // Texture adder
  36888. this._createTextureAdderPostProcess(scene, ratio);
  36889. // Luminance generator
  36890. this._createLuminanceGeneratorPostProcess(scene);
  36891. // HDR
  36892. this._createHDRPostProcess(scene, ratio);
  36893. // Pass postprocess
  36894. if (originalPostProcess === null) {
  36895. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36896. }
  36897. else {
  36898. this._originalPostProcess = originalPostProcess;
  36899. }
  36900. // Configure pipeline
  36901. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36905. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36907. var addDownSamplerPostProcess = function (id) {
  36908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36909. };
  36910. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36911. addDownSamplerPostProcess(i);
  36912. }
  36913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36914. // Finish
  36915. scene.postProcessRenderPipelineManager.addPipeline(this);
  36916. if (cameras !== null) {
  36917. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36918. }
  36919. this.update();
  36920. }
  36921. /**
  36922. * Tells the pipeline to update its post-processes
  36923. */
  36924. HDRRenderingPipeline.prototype.update = function () {
  36925. this._needUpdate = true;
  36926. };
  36927. /**
  36928. * Returns the current calculated luminance
  36929. */
  36930. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36931. return this._hdrCurrentLuminance;
  36932. };
  36933. /**
  36934. * Returns the currently drawn luminance
  36935. */
  36936. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36937. return this._hdrOutputLuminance;
  36938. };
  36939. /**
  36940. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36941. */
  36942. HDRRenderingPipeline.prototype.dispose = function () {
  36943. this._originalPostProcess = undefined;
  36944. this._brightPassPostProcess = undefined;
  36945. this._downSampleX4PostProcess = undefined;
  36946. this._guassianBlurHPostProcess = undefined;
  36947. this._guassianBlurVPostProcess = undefined;
  36948. this._textureAdderPostProcess = undefined;
  36949. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36950. this._downSamplePostProcesses[i] = undefined;
  36951. }
  36952. this._hdrPostProcess = undefined;
  36953. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36954. };
  36955. /**
  36956. * Creates the HDR post-process and computes the luminance adaptation
  36957. */
  36958. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36959. var _this = this;
  36960. var hdrLastLuminance = 0.0;
  36961. this._hdrOutputLuminance = -1.0;
  36962. this._hdrCurrentLuminance = 1.0;
  36963. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36964. this._hdrPostProcess.onApply = function (effect) {
  36965. if (_this._hdrOutputLuminance < 0.0) {
  36966. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36967. }
  36968. else {
  36969. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36970. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36971. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36972. }
  36973. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36974. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36975. }
  36976. else {
  36977. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36978. }
  36979. }
  36980. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36981. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36982. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36983. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36984. effect.setFloat("exposure", _this.exposure);
  36985. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36986. _this._needUpdate = false;
  36987. };
  36988. };
  36989. /**
  36990. * Texture Adder post-process
  36991. */
  36992. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36993. var _this = this;
  36994. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36995. this._textureAdderPostProcess.onApply = function (effect) {
  36996. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36997. };
  36998. };
  36999. /**
  37000. * Down sample X4 post-process
  37001. */
  37002. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37003. var _this = this;
  37004. var downSampleX4Offsets = new Array(32);
  37005. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37006. this._downSampleX4PostProcess.onApply = function (effect) {
  37007. if (_this._needUpdate) {
  37008. var id = 0;
  37009. for (var i = -2; i < 2; i++) {
  37010. for (var j = -2; j < 2; j++) {
  37011. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37012. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37013. id += 2;
  37014. }
  37015. }
  37016. }
  37017. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37018. };
  37019. };
  37020. /**
  37021. * Bright pass post-process
  37022. */
  37023. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37024. var _this = this;
  37025. var brightOffsets = new Array(8);
  37026. var brightPassCallback = function (effect) {
  37027. if (_this._needUpdate) {
  37028. var sU = (1.0 / _this._brightPassPostProcess.width);
  37029. var sV = (1.0 / _this._brightPassPostProcess.height);
  37030. brightOffsets[0] = -0.5 * sU;
  37031. brightOffsets[1] = 0.5 * sV;
  37032. brightOffsets[2] = 0.5 * sU;
  37033. brightOffsets[3] = 0.5 * sV;
  37034. brightOffsets[4] = -0.5 * sU;
  37035. brightOffsets[5] = -0.5 * sV;
  37036. brightOffsets[6] = 0.5 * sU;
  37037. brightOffsets[7] = -0.5 * sV;
  37038. }
  37039. effect.setArray2("dsOffsets", brightOffsets);
  37040. effect.setFloat("brightThreshold", _this.brightThreshold);
  37041. };
  37042. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37043. this._brightPassPostProcess.onApply = brightPassCallback;
  37044. };
  37045. /**
  37046. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37047. */
  37048. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37049. var _this = this;
  37050. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37051. var luminanceOffsets = new Array(8);
  37052. var downSampleOffsets = new Array(18);
  37053. var halfDestPixelSize;
  37054. this._downSamplePostProcesses = new Array(lumSteps);
  37055. // Utils for luminance
  37056. var luminanceUpdateSourceOffsets = function (width, height) {
  37057. var sU = (1.0 / width);
  37058. var sV = (1.0 / height);
  37059. luminanceOffsets[0] = -0.5 * sU;
  37060. luminanceOffsets[1] = 0.5 * sV;
  37061. luminanceOffsets[2] = 0.5 * sU;
  37062. luminanceOffsets[3] = 0.5 * sV;
  37063. luminanceOffsets[4] = -0.5 * sU;
  37064. luminanceOffsets[5] = -0.5 * sV;
  37065. luminanceOffsets[6] = 0.5 * sU;
  37066. luminanceOffsets[7] = -0.5 * sV;
  37067. };
  37068. var luminanceUpdateDestOffsets = function (width, height) {
  37069. var id = 0;
  37070. for (var x = -1; x < 2; x++) {
  37071. for (var y = -1; y < 2; y++) {
  37072. downSampleOffsets[id] = (x) / width;
  37073. downSampleOffsets[id + 1] = (y) / height;
  37074. id += 2;
  37075. }
  37076. }
  37077. };
  37078. // Luminance callback
  37079. var luminanceCallback = function (effect) {
  37080. if (_this._needUpdate) {
  37081. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37082. }
  37083. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37084. effect.setArray2("lumOffsets", luminanceOffsets);
  37085. };
  37086. // Down sample callbacks
  37087. var downSampleCallback = function (indice) {
  37088. var i = indice;
  37089. return function (effect) {
  37090. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37091. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37092. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37093. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37094. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37095. effect.setArray2("dsOffsets", downSampleOffsets);
  37096. };
  37097. };
  37098. var downSampleAfterRenderCallback = function (effect) {
  37099. // Unpack result
  37100. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37101. 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);
  37102. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37103. };
  37104. // Create luminance post-process
  37105. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37106. 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);
  37107. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37108. // Create down sample post-processes
  37109. for (var i = lumSteps - 2; i >= 0; i--) {
  37110. var length = Math.pow(3, i);
  37111. ratio = { width: length, height: length };
  37112. var defines = "#define DOWN_SAMPLE\n";
  37113. if (i === 0) {
  37114. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37115. }
  37116. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37117. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37118. if (i === 0) {
  37119. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37120. }
  37121. }
  37122. };
  37123. /**
  37124. * Gaussian blur post-processes. Horizontal and Vertical
  37125. */
  37126. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37127. var _this = this;
  37128. var blurOffsetsW = new Array(9);
  37129. var blurOffsetsH = new Array(9);
  37130. var blurWeights = new Array(9);
  37131. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37132. // Utils for gaussian blur
  37133. var calculateBlurOffsets = function (height) {
  37134. var lastOutputDimensions = {
  37135. width: scene.getEngine().getRenderWidth(),
  37136. height: scene.getEngine().getRenderHeight()
  37137. };
  37138. for (var i = 0; i < 9; i++) {
  37139. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37140. if (height) {
  37141. blurOffsetsH[i] = value;
  37142. }
  37143. else {
  37144. blurOffsetsW[i] = value;
  37145. }
  37146. }
  37147. };
  37148. var calculateWeights = function () {
  37149. var x = 0.0;
  37150. for (var i = 0; i < 9; i++) {
  37151. x = (i - 4.0) / 4.0;
  37152. 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));
  37153. }
  37154. };
  37155. // Callback
  37156. var gaussianBlurCallback = function (height) {
  37157. return function (effect) {
  37158. if (_this._needUpdate) {
  37159. calculateWeights();
  37160. calculateBlurOffsets(height);
  37161. }
  37162. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37163. effect.setArray("blurWeights", blurWeights);
  37164. effect.setFloat("multiplier", _this.gaussMultiplier);
  37165. };
  37166. };
  37167. // Create horizontal gaussian blur post-processes
  37168. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37169. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37170. // Create vertical gaussian blur post-process
  37171. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37172. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37173. };
  37174. // Luminance generator
  37175. HDRRenderingPipeline.LUM_STEPS = 6;
  37176. return HDRRenderingPipeline;
  37177. })(BABYLON.PostProcessRenderPipeline);
  37178. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37179. })(BABYLON || (BABYLON = {}));
  37180. var BABYLON;
  37181. (function (BABYLON) {
  37182. var FaceAdjacencies = (function () {
  37183. function FaceAdjacencies() {
  37184. this.edges = new Array();
  37185. this.edgesConnectedCount = 0;
  37186. }
  37187. return FaceAdjacencies;
  37188. })();
  37189. var EdgesRenderer = (function () {
  37190. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37191. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37192. if (epsilon === void 0) { epsilon = 0.95; }
  37193. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37194. this.edgesWidthScalerForOrthographic = 1000.0;
  37195. this.edgesWidthScalerForPerspective = 50.0;
  37196. this._linesPositions = new Array();
  37197. this._linesNormals = new Array();
  37198. this._linesIndices = new Array();
  37199. this._buffers = new Array();
  37200. this._checkVerticesInsteadOfIndices = false;
  37201. this._source = source;
  37202. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37203. this._epsilon = epsilon;
  37204. this._prepareRessources();
  37205. this._generateEdgesLines();
  37206. }
  37207. EdgesRenderer.prototype._prepareRessources = function () {
  37208. if (this._lineShader) {
  37209. return;
  37210. }
  37211. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37212. attributes: ["position", "normal"],
  37213. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37214. });
  37215. this._lineShader.disableDepthWrite = true;
  37216. this._lineShader.backFaceCulling = false;
  37217. };
  37218. EdgesRenderer.prototype.dispose = function () {
  37219. this._vb0.dispose();
  37220. this._vb1.dispose();
  37221. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37222. this._lineShader.dispose();
  37223. };
  37224. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37225. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37226. return 0;
  37227. }
  37228. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37229. return 1;
  37230. }
  37231. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37232. return 2;
  37233. }
  37234. return -1;
  37235. };
  37236. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37237. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37238. return 0;
  37239. }
  37240. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37241. return 1;
  37242. }
  37243. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37244. return 2;
  37245. }
  37246. return -1;
  37247. };
  37248. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37249. var needToCreateLine;
  37250. if (edge === undefined) {
  37251. needToCreateLine = true;
  37252. }
  37253. else {
  37254. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37255. needToCreateLine = dotProduct < this._epsilon;
  37256. }
  37257. if (needToCreateLine) {
  37258. var offset = this._linesPositions.length / 3;
  37259. var normal = p0.subtract(p1);
  37260. normal.normalize();
  37261. // Positions
  37262. this._linesPositions.push(p0.x);
  37263. this._linesPositions.push(p0.y);
  37264. this._linesPositions.push(p0.z);
  37265. this._linesPositions.push(p0.x);
  37266. this._linesPositions.push(p0.y);
  37267. this._linesPositions.push(p0.z);
  37268. this._linesPositions.push(p1.x);
  37269. this._linesPositions.push(p1.y);
  37270. this._linesPositions.push(p1.z);
  37271. this._linesPositions.push(p1.x);
  37272. this._linesPositions.push(p1.y);
  37273. this._linesPositions.push(p1.z);
  37274. // Normals
  37275. this._linesNormals.push(p1.x);
  37276. this._linesNormals.push(p1.y);
  37277. this._linesNormals.push(p1.z);
  37278. this._linesNormals.push(-1);
  37279. this._linesNormals.push(p1.x);
  37280. this._linesNormals.push(p1.y);
  37281. this._linesNormals.push(p1.z);
  37282. this._linesNormals.push(1);
  37283. this._linesNormals.push(p0.x);
  37284. this._linesNormals.push(p0.y);
  37285. this._linesNormals.push(p0.z);
  37286. this._linesNormals.push(-1);
  37287. this._linesNormals.push(p0.x);
  37288. this._linesNormals.push(p0.y);
  37289. this._linesNormals.push(p0.z);
  37290. this._linesNormals.push(1);
  37291. // Indices
  37292. this._linesIndices.push(offset);
  37293. this._linesIndices.push(offset + 1);
  37294. this._linesIndices.push(offset + 2);
  37295. this._linesIndices.push(offset);
  37296. this._linesIndices.push(offset + 2);
  37297. this._linesIndices.push(offset + 3);
  37298. }
  37299. };
  37300. EdgesRenderer.prototype._generateEdgesLines = function () {
  37301. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37302. var indices = this._source.getIndices();
  37303. // First let's find adjacencies
  37304. var adjacencies = new Array();
  37305. var faceNormals = new Array();
  37306. var index;
  37307. var faceAdjacencies;
  37308. // Prepare faces
  37309. for (index = 0; index < indices.length; index += 3) {
  37310. faceAdjacencies = new FaceAdjacencies();
  37311. var p0Index = indices[index];
  37312. var p1Index = indices[index + 1];
  37313. var p2Index = indices[index + 2];
  37314. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37315. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37316. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37317. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37318. faceNormal.normalize();
  37319. faceNormals.push(faceNormal);
  37320. adjacencies.push(faceAdjacencies);
  37321. }
  37322. // Scan
  37323. for (index = 0; index < adjacencies.length; index++) {
  37324. faceAdjacencies = adjacencies[index];
  37325. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37326. var otherFaceAdjacencies = adjacencies[otherIndex];
  37327. if (faceAdjacencies.edgesConnectedCount === 3) {
  37328. break;
  37329. }
  37330. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37331. continue;
  37332. }
  37333. var otherP0 = indices[otherIndex * 3];
  37334. var otherP1 = indices[otherIndex * 3 + 1];
  37335. var otherP2 = indices[otherIndex * 3 + 2];
  37336. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37337. var otherEdgeIndex;
  37338. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37339. continue;
  37340. }
  37341. switch (edgeIndex) {
  37342. case 0:
  37343. if (this._checkVerticesInsteadOfIndices) {
  37344. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37345. }
  37346. else {
  37347. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37348. }
  37349. break;
  37350. case 1:
  37351. if (this._checkVerticesInsteadOfIndices) {
  37352. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37353. }
  37354. else {
  37355. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37356. }
  37357. break;
  37358. case 2:
  37359. if (this._checkVerticesInsteadOfIndices) {
  37360. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37361. }
  37362. else {
  37363. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37364. }
  37365. break;
  37366. }
  37367. if (otherEdgeIndex === -1) {
  37368. continue;
  37369. }
  37370. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37371. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37372. faceAdjacencies.edgesConnectedCount++;
  37373. otherFaceAdjacencies.edgesConnectedCount++;
  37374. if (faceAdjacencies.edgesConnectedCount === 3) {
  37375. break;
  37376. }
  37377. }
  37378. }
  37379. }
  37380. // Create lines
  37381. for (index = 0; index < adjacencies.length; index++) {
  37382. // 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
  37383. var current = adjacencies[index];
  37384. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37385. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37386. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37387. }
  37388. // Merge into a single mesh
  37389. var engine = this._source.getScene().getEngine();
  37390. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37391. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37392. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37393. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37394. this._ib = engine.createIndexBuffer(this._linesIndices);
  37395. this._indicesCount = this._linesIndices.length;
  37396. };
  37397. EdgesRenderer.prototype.render = function () {
  37398. if (!this._lineShader.isReady()) {
  37399. return;
  37400. }
  37401. var scene = this._source.getScene();
  37402. var engine = scene.getEngine();
  37403. this._lineShader._preBind();
  37404. // VBOs
  37405. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37406. scene.resetCachedMaterial();
  37407. this._lineShader.setColor4("color", this._source.edgesColor);
  37408. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37409. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37410. }
  37411. else {
  37412. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37413. }
  37414. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37415. this._lineShader.bind(this._source.getWorldMatrix());
  37416. // Draw order
  37417. engine.draw(true, 0, this._indicesCount);
  37418. this._lineShader.unbind();
  37419. engine.setDepthWrite(true);
  37420. };
  37421. return EdgesRenderer;
  37422. })();
  37423. BABYLON.EdgesRenderer = EdgesRenderer;
  37424. })(BABYLON || (BABYLON = {}));
  37425. var BABYLON;
  37426. (function (BABYLON) {
  37427. (function (TonemappingOperator) {
  37428. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37429. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37430. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37431. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37432. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37433. var TonemappingOperator = BABYLON.TonemappingOperator;
  37434. ;
  37435. var TonemapPostProcess = (function (_super) {
  37436. __extends(TonemapPostProcess, _super);
  37437. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37438. var _this = this;
  37439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37440. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37441. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37442. this._operator = _operator;
  37443. this.exposureAdjustment = exposureAdjustment;
  37444. var defines = "#define ";
  37445. if (this._operator === TonemappingOperator.Hable)
  37446. defines += "HABLE_TONEMAPPING";
  37447. else if (this._operator === TonemappingOperator.Reinhard)
  37448. defines += "REINHARD_TONEMAPPING";
  37449. else if (this._operator === TonemappingOperator.HejiDawson)
  37450. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37451. else if (this._operator === TonemappingOperator.Photographic)
  37452. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37453. //sadly a second call to create the effect.
  37454. this.updateEffect(defines);
  37455. this.onApply = function (effect) {
  37456. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37457. };
  37458. }
  37459. return TonemapPostProcess;
  37460. })(BABYLON.PostProcess);
  37461. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37462. })(BABYLON || (BABYLON = {}));
  37463. var BABYLON;
  37464. (function (BABYLON) {
  37465. var ReflectionProbe = (function () {
  37466. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37467. var _this = this;
  37468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37469. this.name = name;
  37470. this._viewMatrix = BABYLON.Matrix.Identity();
  37471. this._target = BABYLON.Vector3.Zero();
  37472. this._add = BABYLON.Vector3.Zero();
  37473. this.position = BABYLON.Vector3.Zero();
  37474. this._scene = scene;
  37475. this._scene.reflectionProbes.push(this);
  37476. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37477. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37478. switch (faceIndex) {
  37479. case 0:
  37480. _this._add.copyFromFloats(1, 0, 0);
  37481. break;
  37482. case 1:
  37483. _this._add.copyFromFloats(-1, 0, 0);
  37484. break;
  37485. case 2:
  37486. _this._add.copyFromFloats(0, -1, 0);
  37487. break;
  37488. case 3:
  37489. _this._add.copyFromFloats(0, 1, 0);
  37490. break;
  37491. case 4:
  37492. _this._add.copyFromFloats(0, 0, 1);
  37493. break;
  37494. case 5:
  37495. _this._add.copyFromFloats(0, 0, -1);
  37496. break;
  37497. }
  37498. if (_this._attachedMesh) {
  37499. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37500. }
  37501. _this.position.addToRef(_this._add, _this._target);
  37502. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37503. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37504. };
  37505. this._renderTargetTexture.onAfterUnbind = function () {
  37506. scene.updateTransformMatrix(true);
  37507. };
  37508. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37509. }
  37510. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37511. get: function () {
  37512. return this._renderTargetTexture.refreshRate;
  37513. },
  37514. set: function (value) {
  37515. this._renderTargetTexture.refreshRate = value;
  37516. },
  37517. enumerable: true,
  37518. configurable: true
  37519. });
  37520. ReflectionProbe.prototype.getScene = function () {
  37521. return this._scene;
  37522. };
  37523. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37524. get: function () {
  37525. return this._renderTargetTexture;
  37526. },
  37527. enumerable: true,
  37528. configurable: true
  37529. });
  37530. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37531. get: function () {
  37532. return this._renderTargetTexture.renderList;
  37533. },
  37534. enumerable: true,
  37535. configurable: true
  37536. });
  37537. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37538. this._attachedMesh = mesh;
  37539. };
  37540. ReflectionProbe.prototype.dispose = function () {
  37541. var index = this._scene.reflectionProbes.indexOf(this);
  37542. if (index !== -1) {
  37543. // Remove from the scene if found
  37544. this._scene.reflectionProbes.splice(index, 1);
  37545. }
  37546. if (this._renderTargetTexture) {
  37547. this._renderTargetTexture.dispose();
  37548. this._renderTargetTexture = null;
  37549. }
  37550. };
  37551. return ReflectionProbe;
  37552. })();
  37553. BABYLON.ReflectionProbe = ReflectionProbe;
  37554. })(BABYLON || (BABYLON = {}));
  37555. var BABYLON;
  37556. (function (BABYLON) {
  37557. var SolidParticle = (function () {
  37558. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37559. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37560. this.position = BABYLON.Vector3.Zero(); // position
  37561. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37562. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37563. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37564. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37565. this.alive = true; // alive
  37566. this.idx = particleIndex;
  37567. this._pos = positionIndex;
  37568. this._model = model;
  37569. this.shapeId = shapeId;
  37570. this.idxInShape = idxInShape;
  37571. }
  37572. return SolidParticle;
  37573. })();
  37574. BABYLON.SolidParticle = SolidParticle;
  37575. var ModelShape = (function () {
  37576. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37577. this.shapeID = id;
  37578. this._shape = shape;
  37579. this._shapeUV = shapeUV;
  37580. this._positionFunction = posFunction;
  37581. this._vertexFunction = vtxFunction;
  37582. }
  37583. return ModelShape;
  37584. })();
  37585. BABYLON.ModelShape = ModelShape;
  37586. })(BABYLON || (BABYLON = {}));
  37587. var BABYLON;
  37588. (function (BABYLON) {
  37589. /**
  37590. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37591. */
  37592. var SolidParticleSystem = (function () {
  37593. /**
  37594. * Creates a SPS (Solid Particle System) object.
  37595. * @param name the SPS name, this will be the underlying mesh name
  37596. * @param scene the scene in which the SPS is added
  37597. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37598. */
  37599. function SolidParticleSystem(name, scene, options) {
  37600. // public members
  37601. /**
  37602. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37603. * Example : var p = SPS.particles[i];
  37604. */
  37605. this.particles = new Array();
  37606. /**
  37607. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37608. */
  37609. this.nbParticles = 0;
  37610. /**
  37611. * If the particles must ever face the camera (default false). Useful for planar particles.
  37612. */
  37613. this.billboard = false;
  37614. /**
  37615. * This a counter ofr your own usage. It's not set by any SPS functions.
  37616. */
  37617. this.counter = 0;
  37618. /**
  37619. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37620. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37621. */
  37622. this.vars = {};
  37623. this._positions = new Array();
  37624. this._indices = new Array();
  37625. this._normals = new Array();
  37626. this._colors = new Array();
  37627. this._uvs = new Array();
  37628. this._index = 0; // indices index
  37629. this._updatable = true;
  37630. this._pickable = false;
  37631. this._isVisibilityBoxLocked = false;
  37632. this._alwaysVisible = false;
  37633. this._shapeCounter = 0;
  37634. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37635. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37636. this._computeParticleColor = true;
  37637. this._computeParticleTexture = true;
  37638. this._computeParticleRotation = true;
  37639. this._computeParticleVertex = false;
  37640. this._computeBoundingBox = false;
  37641. this._cam_axisZ = BABYLON.Vector3.Zero();
  37642. this._cam_axisY = BABYLON.Vector3.Zero();
  37643. this._cam_axisX = BABYLON.Vector3.Zero();
  37644. this._axisX = BABYLON.Axis.X;
  37645. this._axisY = BABYLON.Axis.Y;
  37646. this._axisZ = BABYLON.Axis.Z;
  37647. this._fakeCamPos = BABYLON.Vector3.Zero();
  37648. this._rotMatrix = new BABYLON.Matrix();
  37649. this._invertMatrix = new BABYLON.Matrix();
  37650. this._rotated = BABYLON.Vector3.Zero();
  37651. this._quaternion = new BABYLON.Quaternion();
  37652. this._vertex = BABYLON.Vector3.Zero();
  37653. this._normal = BABYLON.Vector3.Zero();
  37654. this._yaw = 0.0;
  37655. this._pitch = 0.0;
  37656. this._roll = 0.0;
  37657. this._halfroll = 0.0;
  37658. this._halfpitch = 0.0;
  37659. this._halfyaw = 0.0;
  37660. this._sinRoll = 0.0;
  37661. this._cosRoll = 0.0;
  37662. this._sinPitch = 0.0;
  37663. this._cosPitch = 0.0;
  37664. this._sinYaw = 0.0;
  37665. this._cosYaw = 0.0;
  37666. this._w = 0.0;
  37667. this._minimum = BABYLON.Tmp.Vector3[0];
  37668. this._maximum = BABYLON.Tmp.Vector3[1];
  37669. this.name = name;
  37670. this._scene = scene;
  37671. this._camera = scene.activeCamera;
  37672. this._pickable = options ? options.isPickable : false;
  37673. if (options && options.updatable) {
  37674. this._updatable = options.updatable;
  37675. }
  37676. else {
  37677. this._updatable = true;
  37678. }
  37679. if (this._pickable) {
  37680. this.pickedParticles = [];
  37681. }
  37682. }
  37683. /**
  37684. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37685. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37686. */
  37687. SolidParticleSystem.prototype.buildMesh = function () {
  37688. if (this.nbParticles === 0) {
  37689. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37690. this.addShape(triangle, 1);
  37691. triangle.dispose();
  37692. }
  37693. this._positions32 = new Float32Array(this._positions);
  37694. this._uvs32 = new Float32Array(this._uvs);
  37695. this._colors32 = new Float32Array(this._colors);
  37696. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37697. this._normals32 = new Float32Array(this._normals);
  37698. this._fixedNormal32 = new Float32Array(this._normals);
  37699. var vertexData = new BABYLON.VertexData();
  37700. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37701. vertexData.indices = this._indices;
  37702. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37703. if (this._uvs32) {
  37704. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37705. ;
  37706. }
  37707. if (this._colors32) {
  37708. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37709. }
  37710. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37711. vertexData.applyToMesh(mesh, this._updatable);
  37712. this.mesh = mesh;
  37713. this.mesh.isPickable = this._pickable;
  37714. // free memory
  37715. this._positions = null;
  37716. this._normals = null;
  37717. this._uvs = null;
  37718. this._colors = null;
  37719. if (!this._updatable) {
  37720. this.particles.length = 0;
  37721. }
  37722. return mesh;
  37723. };
  37724. /**
  37725. * Digests the mesh and generates as many solid particles in the system as wanted.
  37726. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37727. * Thus the particles generated from digest() have their property "positiion" yet set.
  37728. * @param mesh the mesh to be digested
  37729. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37730. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37731. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37732. */
  37733. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37734. var size = (options && options.facetNb) || 1;
  37735. var number = (options && options.number);
  37736. var delta = (options && options.delta) || 0;
  37737. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37738. var meshInd = mesh.getIndices();
  37739. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37740. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37741. var f = 0; // facet counter
  37742. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37743. // compute size from number
  37744. if (number) {
  37745. number = (number > totalFacets) ? totalFacets : number;
  37746. size = Math.round(totalFacets / number);
  37747. delta = 0;
  37748. }
  37749. else {
  37750. size = (size > totalFacets) ? totalFacets : size;
  37751. }
  37752. var facetPos = []; // submesh positions
  37753. var facetInd = []; // submesh indices
  37754. var facetUV = []; // submesh UV
  37755. var facetCol = []; // submesh colors
  37756. var barycenter = BABYLON.Tmp.Vector3[0];
  37757. var rand;
  37758. var sizeO = size;
  37759. while (f < totalFacets) {
  37760. size = sizeO + Math.floor((1 + delta) * Math.random());
  37761. if (f > totalFacets - size) {
  37762. size = totalFacets - f;
  37763. }
  37764. // reset temp arrays
  37765. facetPos.length = 0;
  37766. facetInd.length = 0;
  37767. facetUV.length = 0;
  37768. facetCol.length = 0;
  37769. // iterate over "size" facets
  37770. var fi = 0;
  37771. for (var j = f * 3; j < (f + size) * 3; j++) {
  37772. facetInd.push(fi);
  37773. var i = meshInd[j];
  37774. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37775. if (meshUV) {
  37776. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37777. }
  37778. if (meshCol) {
  37779. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37780. }
  37781. fi++;
  37782. }
  37783. // create a model shape for each single particle
  37784. var idx = this.nbParticles;
  37785. var shape = this._posToShape(facetPos);
  37786. var shapeUV = this._uvsToShapeUV(facetUV);
  37787. // compute the barycenter of the shape
  37788. var v;
  37789. for (v = 0; v < shape.length; v++) {
  37790. barycenter.addInPlace(shape[v]);
  37791. }
  37792. barycenter.scaleInPlace(1 / shape.length);
  37793. // shift the shape from its barycenter to the origin
  37794. for (v = 0; v < shape.length; v++) {
  37795. shape[v].subtractInPlace(barycenter);
  37796. }
  37797. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37798. // add the particle in the SPS
  37799. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37800. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37801. // initialize the particle position
  37802. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37803. this._index += shape.length;
  37804. idx++;
  37805. this.nbParticles++;
  37806. this._shapeCounter++;
  37807. f += size;
  37808. }
  37809. };
  37810. //reset copy
  37811. SolidParticleSystem.prototype._resetCopy = function () {
  37812. this._copy.position.x = 0;
  37813. this._copy.position.y = 0;
  37814. this._copy.position.z = 0;
  37815. this._copy.rotation.x = 0;
  37816. this._copy.rotation.y = 0;
  37817. this._copy.rotation.z = 0;
  37818. this._copy.quaternion = null;
  37819. this._copy.scale.x = 1;
  37820. this._copy.scale.y = 1;
  37821. this._copy.scale.z = 1;
  37822. this._copy.uvs.x = 0;
  37823. this._copy.uvs.y = 0;
  37824. this._copy.uvs.z = 1;
  37825. this._copy.uvs.w = 1;
  37826. this._copy.color = null;
  37827. };
  37828. // _meshBuilder : inserts the shape model in the global SPS mesh
  37829. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37830. var i;
  37831. var u = 0;
  37832. var c = 0;
  37833. this._resetCopy();
  37834. if (options && options.positionFunction) {
  37835. options.positionFunction(this._copy, idx, idxInShape);
  37836. }
  37837. if (this._copy.quaternion) {
  37838. this._quaternion.x = this._copy.quaternion.x;
  37839. this._quaternion.y = this._copy.quaternion.y;
  37840. this._quaternion.z = this._copy.quaternion.z;
  37841. this._quaternion.w = this._copy.quaternion.w;
  37842. }
  37843. else {
  37844. this._yaw = this._copy.rotation.y;
  37845. this._pitch = this._copy.rotation.x;
  37846. this._roll = this._copy.rotation.z;
  37847. this._quaternionRotationYPR();
  37848. }
  37849. this._quaternionToRotationMatrix();
  37850. for (i = 0; i < shape.length; i++) {
  37851. this._vertex.x = shape[i].x;
  37852. this._vertex.y = shape[i].y;
  37853. this._vertex.z = shape[i].z;
  37854. if (options && options.vertexFunction) {
  37855. options.vertexFunction(this._copy, this._vertex, i);
  37856. }
  37857. this._vertex.x *= this._copy.scale.x;
  37858. this._vertex.y *= this._copy.scale.y;
  37859. this._vertex.z *= this._copy.scale.z;
  37860. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37861. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37862. if (meshUV) {
  37863. 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);
  37864. u += 2;
  37865. }
  37866. if (this._copy.color) {
  37867. this._color = this._copy.color;
  37868. }
  37869. else if (meshCol && meshCol[c]) {
  37870. this._color.r = meshCol[c];
  37871. this._color.g = meshCol[c + 1];
  37872. this._color.b = meshCol[c + 2];
  37873. this._color.a = meshCol[c + 3];
  37874. }
  37875. else {
  37876. this._color.r = 1;
  37877. this._color.g = 1;
  37878. this._color.b = 1;
  37879. this._color.a = 1;
  37880. }
  37881. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37882. c += 4;
  37883. }
  37884. for (i = 0; i < meshInd.length; i++) {
  37885. indices.push(p + meshInd[i]);
  37886. }
  37887. if (this._pickable) {
  37888. var nbfaces = meshInd.length / 3;
  37889. for (i = 0; i < nbfaces; i++) {
  37890. this.pickedParticles.push({ idx: idx, faceId: i });
  37891. }
  37892. }
  37893. };
  37894. // returns a shape array from positions array
  37895. SolidParticleSystem.prototype._posToShape = function (positions) {
  37896. var shape = [];
  37897. for (var i = 0; i < positions.length; i += 3) {
  37898. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37899. }
  37900. return shape;
  37901. };
  37902. // returns a shapeUV array from a Vector4 uvs
  37903. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37904. var shapeUV = [];
  37905. if (uvs) {
  37906. for (var i = 0; i < uvs.length; i++)
  37907. shapeUV.push(uvs[i]);
  37908. }
  37909. return shapeUV;
  37910. };
  37911. // adds a new particle object in the particles array
  37912. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37913. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37914. };
  37915. /**
  37916. * Adds some particles to the SPS from the model shape.
  37917. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37918. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37919. * @param nb the number of particles to be created from this model
  37920. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37921. */
  37922. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37923. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37924. var meshInd = mesh.getIndices();
  37925. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37926. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37927. var shape = this._posToShape(meshPos);
  37928. var shapeUV = this._uvsToShapeUV(meshUV);
  37929. var posfunc = options ? options.positionFunction : null;
  37930. var vtxfunc = options ? options.vertexFunction : null;
  37931. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37932. // particles
  37933. var idx = this.nbParticles;
  37934. for (var i = 0; i < nb; i++) {
  37935. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37936. if (this._updatable) {
  37937. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37938. }
  37939. this._index += shape.length;
  37940. idx++;
  37941. }
  37942. this.nbParticles += nb;
  37943. this._shapeCounter++;
  37944. return this._shapeCounter - 1;
  37945. };
  37946. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37947. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37948. this._resetCopy();
  37949. if (particle._model._positionFunction) {
  37950. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37951. }
  37952. if (this._copy.quaternion) {
  37953. this._quaternion.x = this._copy.quaternion.x;
  37954. this._quaternion.y = this._copy.quaternion.y;
  37955. this._quaternion.z = this._copy.quaternion.z;
  37956. this._quaternion.w = this._copy.quaternion.w;
  37957. }
  37958. else {
  37959. this._yaw = this._copy.rotation.y;
  37960. this._pitch = this._copy.rotation.x;
  37961. this._roll = this._copy.rotation.z;
  37962. this._quaternionRotationYPR();
  37963. }
  37964. this._quaternionToRotationMatrix();
  37965. this._shape = particle._model._shape;
  37966. for (var pt = 0; pt < this._shape.length; pt++) {
  37967. this._vertex.x = this._shape[pt].x;
  37968. this._vertex.y = this._shape[pt].y;
  37969. this._vertex.z = this._shape[pt].z;
  37970. if (particle._model._vertexFunction) {
  37971. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37972. }
  37973. this._vertex.x *= this._copy.scale.x;
  37974. this._vertex.y *= this._copy.scale.y;
  37975. this._vertex.z *= this._copy.scale.z;
  37976. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37977. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37978. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37979. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37980. }
  37981. particle.position.x = 0;
  37982. particle.position.y = 0;
  37983. particle.position.z = 0;
  37984. particle.rotation.x = 0;
  37985. particle.rotation.y = 0;
  37986. particle.rotation.z = 0;
  37987. particle.quaternion = null;
  37988. particle.scale.x = 1;
  37989. particle.scale.y = 1;
  37990. particle.scale.z = 1;
  37991. };
  37992. /**
  37993. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37994. */
  37995. SolidParticleSystem.prototype.rebuildMesh = function () {
  37996. for (var p = 0; p < this.particles.length; p++) {
  37997. this._rebuildParticle(this.particles[p]);
  37998. }
  37999. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38000. };
  38001. /**
  38002. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38003. * This method calls updateParticle() for each particles of the SPS.
  38004. * For an animated SPS, it is usually called within the render loop.
  38005. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38006. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38007. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38008. */
  38009. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38010. if (start === void 0) { start = 0; }
  38011. if (end === void 0) { end = this.nbParticles - 1; }
  38012. if (update === void 0) { update = true; }
  38013. if (!this._updatable) {
  38014. return;
  38015. }
  38016. // custom beforeUpdate
  38017. this.beforeUpdateParticles(start, end, update);
  38018. this._cam_axisX.x = 1;
  38019. this._cam_axisX.y = 0;
  38020. this._cam_axisX.z = 0;
  38021. this._cam_axisY.x = 0;
  38022. this._cam_axisY.y = 1;
  38023. this._cam_axisY.z = 0;
  38024. this._cam_axisZ.x = 0;
  38025. this._cam_axisZ.y = 0;
  38026. this._cam_axisZ.z = 1;
  38027. // if the particles will always face the camera
  38028. if (this.billboard) {
  38029. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38030. this._yaw = this.mesh.rotation.y;
  38031. this._pitch = this.mesh.rotation.x;
  38032. this._roll = this.mesh.rotation.z;
  38033. this._quaternionRotationYPR();
  38034. this._quaternionToRotationMatrix();
  38035. this._rotMatrix.invertToRef(this._invertMatrix);
  38036. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38037. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38038. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38039. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38040. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38041. this._cam_axisY.normalize();
  38042. this._cam_axisX.normalize();
  38043. this._cam_axisZ.normalize();
  38044. }
  38045. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38046. var idx = 0;
  38047. var index = 0;
  38048. var colidx = 0;
  38049. var colorIndex = 0;
  38050. var uvidx = 0;
  38051. var uvIndex = 0;
  38052. if (this._computeBoundingBox) {
  38053. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38054. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38055. }
  38056. // particle loop
  38057. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38058. for (var p = start; p <= end; p++) {
  38059. this._particle = this.particles[p];
  38060. this._shape = this._particle._model._shape;
  38061. this._shapeUV = this._particle._model._shapeUV;
  38062. // call to custom user function to update the particle properties
  38063. this.updateParticle(this._particle);
  38064. // particle rotation matrix
  38065. if (this.billboard) {
  38066. this._particle.rotation.x = 0.0;
  38067. this._particle.rotation.y = 0.0;
  38068. }
  38069. if (this._computeParticleRotation) {
  38070. if (this._particle.quaternion) {
  38071. this._quaternion.x = this._particle.quaternion.x;
  38072. this._quaternion.y = this._particle.quaternion.y;
  38073. this._quaternion.z = this._particle.quaternion.z;
  38074. this._quaternion.w = this._particle.quaternion.w;
  38075. }
  38076. else {
  38077. this._yaw = this._particle.rotation.y;
  38078. this._pitch = this._particle.rotation.x;
  38079. this._roll = this._particle.rotation.z;
  38080. this._quaternionRotationYPR();
  38081. }
  38082. this._quaternionToRotationMatrix();
  38083. }
  38084. for (var pt = 0; pt < this._shape.length; pt++) {
  38085. idx = index + pt * 3;
  38086. colidx = colorIndex + pt * 4;
  38087. uvidx = uvIndex + pt * 2;
  38088. this._vertex.x = this._shape[pt].x;
  38089. this._vertex.y = this._shape[pt].y;
  38090. this._vertex.z = this._shape[pt].z;
  38091. if (this._computeParticleVertex) {
  38092. this.updateParticleVertex(this._particle, this._vertex, pt);
  38093. }
  38094. // positions
  38095. this._vertex.x *= this._particle.scale.x;
  38096. this._vertex.y *= this._particle.scale.y;
  38097. this._vertex.z *= this._particle.scale.z;
  38098. 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];
  38099. 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;
  38100. 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;
  38101. 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;
  38102. 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;
  38103. 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;
  38104. 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;
  38105. if (this._computeBoundingBox) {
  38106. if (this._positions32[idx] < this._minimum.x) {
  38107. this._minimum.x = this._positions32[idx];
  38108. }
  38109. if (this._positions32[idx] > this._maximum.x) {
  38110. this._maximum.x = this._positions32[idx];
  38111. }
  38112. if (this._positions32[idx + 1] < this._minimum.y) {
  38113. this._minimum.y = this._positions32[idx + 1];
  38114. }
  38115. if (this._positions32[idx + 1] > this._maximum.y) {
  38116. this._maximum.y = this._positions32[idx + 1];
  38117. }
  38118. if (this._positions32[idx + 2] < this._minimum.z) {
  38119. this._minimum.z = this._positions32[idx + 2];
  38120. }
  38121. if (this._positions32[idx + 2] > this._maximum.z) {
  38122. this._maximum.z = this._positions32[idx + 2];
  38123. }
  38124. }
  38125. // normals : if the particles can't be morphed then just rotate the normals
  38126. if (!this._computeParticleVertex && !this.billboard) {
  38127. this._normal.x = this._fixedNormal32[idx];
  38128. this._normal.y = this._fixedNormal32[idx + 1];
  38129. this._normal.z = this._fixedNormal32[idx + 2];
  38130. 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];
  38131. 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;
  38132. 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;
  38133. 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;
  38134. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38135. 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;
  38136. 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;
  38137. }
  38138. if (this._computeParticleColor) {
  38139. this._colors32[colidx] = this._particle.color.r;
  38140. this._colors32[colidx + 1] = this._particle.color.g;
  38141. this._colors32[colidx + 2] = this._particle.color.b;
  38142. this._colors32[colidx + 3] = this._particle.color.a;
  38143. }
  38144. if (this._computeParticleTexture) {
  38145. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38146. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38147. }
  38148. }
  38149. index = idx + 3;
  38150. colorIndex = colidx + 4;
  38151. uvIndex = uvidx + 2;
  38152. }
  38153. if (update) {
  38154. if (this._computeParticleColor) {
  38155. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38156. }
  38157. if (this._computeParticleTexture) {
  38158. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38159. }
  38160. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38161. if (!this.mesh.areNormalsFrozen) {
  38162. if (this._computeParticleVertex || this.billboard) {
  38163. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38164. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38165. for (var i = 0; i < this._normals32.length; i++) {
  38166. this._fixedNormal32[i] = this._normals32[i];
  38167. }
  38168. }
  38169. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38170. }
  38171. }
  38172. if (this._computeBoundingBox) {
  38173. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38174. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38175. }
  38176. this.afterUpdateParticles(start, end, update);
  38177. };
  38178. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38179. this._halfroll = this._roll * 0.5;
  38180. this._halfpitch = this._pitch * 0.5;
  38181. this._halfyaw = this._yaw * 0.5;
  38182. this._sinRoll = Math.sin(this._halfroll);
  38183. this._cosRoll = Math.cos(this._halfroll);
  38184. this._sinPitch = Math.sin(this._halfpitch);
  38185. this._cosPitch = Math.cos(this._halfpitch);
  38186. this._sinYaw = Math.sin(this._halfyaw);
  38187. this._cosYaw = Math.cos(this._halfyaw);
  38188. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38189. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38190. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38191. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38192. };
  38193. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38194. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38195. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38196. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38197. this._rotMatrix.m[3] = 0;
  38198. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38199. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38200. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38201. this._rotMatrix.m[7] = 0;
  38202. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38203. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38204. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38205. this._rotMatrix.m[11] = 0;
  38206. this._rotMatrix.m[12] = 0;
  38207. this._rotMatrix.m[13] = 0;
  38208. this._rotMatrix.m[14] = 0;
  38209. this._rotMatrix.m[15] = 1.0;
  38210. };
  38211. /**
  38212. * Disposes the SPS
  38213. */
  38214. SolidParticleSystem.prototype.dispose = function () {
  38215. this.mesh.dispose();
  38216. this.vars = null;
  38217. // drop references to internal big arrays for the GC
  38218. this._positions = null;
  38219. this._indices = null;
  38220. this._normals = null;
  38221. this._uvs = null;
  38222. this._colors = null;
  38223. this._positions32 = null;
  38224. this._normals32 = null;
  38225. this._fixedNormal32 = null;
  38226. this._uvs32 = null;
  38227. this._colors32 = null;
  38228. this.pickedParticles = null;
  38229. };
  38230. /**
  38231. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38232. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38233. */
  38234. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38235. if (!this._isVisibilityBoxLocked) {
  38236. this.mesh.refreshBoundingInfo();
  38237. }
  38238. };
  38239. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38240. * @param size the size (float) of the visibility box
  38241. * note : this doesn't lock the SPS mesh bounding box.
  38242. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38243. */
  38244. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38245. var vis = size / 2;
  38246. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38247. };
  38248. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38249. // getter and setter
  38250. /**
  38251. * True if the SPS is set as always visible
  38252. */
  38253. get: function () {
  38254. return this._alwaysVisible;
  38255. },
  38256. /**
  38257. * Sets the SPS as always visible or not
  38258. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38259. */
  38260. set: function (val) {
  38261. this._alwaysVisible = val;
  38262. this.mesh.alwaysSelectAsActiveMesh = val;
  38263. },
  38264. enumerable: true,
  38265. configurable: true
  38266. });
  38267. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38268. /**
  38269. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38270. */
  38271. get: function () {
  38272. return this._isVisibilityBoxLocked;
  38273. },
  38274. /**
  38275. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38276. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38277. */
  38278. set: function (val) {
  38279. this._isVisibilityBoxLocked = val;
  38280. this.mesh.getBoundingInfo().isLocked = val;
  38281. },
  38282. enumerable: true,
  38283. configurable: true
  38284. });
  38285. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38286. // getters
  38287. get: function () {
  38288. return this._computeParticleRotation;
  38289. },
  38290. // Optimizer setters
  38291. /**
  38292. * Tells to setParticles() to compute the particle rotations or not.
  38293. * Default value : true. The SPS is faster when it's set to false.
  38294. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38295. */
  38296. set: function (val) {
  38297. this._computeParticleRotation = val;
  38298. },
  38299. enumerable: true,
  38300. configurable: true
  38301. });
  38302. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38303. get: function () {
  38304. return this._computeParticleColor;
  38305. },
  38306. /**
  38307. * Tells to setParticles() to compute the particle colors or not.
  38308. * Default value : true. The SPS is faster when it's set to false.
  38309. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38310. */
  38311. set: function (val) {
  38312. this._computeParticleColor = val;
  38313. },
  38314. enumerable: true,
  38315. configurable: true
  38316. });
  38317. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38318. get: function () {
  38319. return this._computeParticleTexture;
  38320. },
  38321. /**
  38322. * Tells to setParticles() to compute the particle textures or not.
  38323. * Default value : true. The SPS is faster when it's set to false.
  38324. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38325. */
  38326. set: function (val) {
  38327. this._computeParticleTexture = val;
  38328. },
  38329. enumerable: true,
  38330. configurable: true
  38331. });
  38332. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38333. get: function () {
  38334. return this._computeParticleVertex;
  38335. },
  38336. /**
  38337. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38338. * Default value : false. The SPS is faster when it's set to false.
  38339. * Note : the particle custom vertex positions aren't stored values.
  38340. */
  38341. set: function (val) {
  38342. this._computeParticleVertex = val;
  38343. },
  38344. enumerable: true,
  38345. configurable: true
  38346. });
  38347. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38348. get: function () {
  38349. return this._computeBoundingBox;
  38350. },
  38351. /**
  38352. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38353. */
  38354. set: function (val) {
  38355. this._computeBoundingBox = val;
  38356. },
  38357. enumerable: true,
  38358. configurable: true
  38359. });
  38360. // =======================================================================
  38361. // Particle behavior logic
  38362. // these following methods may be overwritten by the user to fit his needs
  38363. /**
  38364. * This function does nothing. It may be overwritten to set all the particles first values.
  38365. * The SPS doesn't call this function, you may have to call it by your own.
  38366. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38367. */
  38368. SolidParticleSystem.prototype.initParticles = function () {
  38369. };
  38370. /**
  38371. * This function does nothing. It may be overwritten to recycle a particle.
  38372. * The SPS doesn't call this function, you may have to call it by your own.
  38373. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38374. */
  38375. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38376. return particle;
  38377. };
  38378. /**
  38379. * Updates a particle : this function should be overwritten by the user.
  38380. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38381. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38382. * ex : just set a particle position or velocity and recycle conditions
  38383. */
  38384. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38385. return particle;
  38386. };
  38387. /**
  38388. * Updates a vertex of a particle : it can be overwritten by the user.
  38389. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38390. * @param particle the current particle
  38391. * @param vertex the current index of the current particle
  38392. * @param pt the index of the current vertex in the particle shape
  38393. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38394. * ex : just set a vertex particle position
  38395. */
  38396. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38397. return vertex;
  38398. };
  38399. /**
  38400. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38401. * This does nothing and may be overwritten by the user.
  38402. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38403. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38404. * @param update the boolean update value actually passed to setParticles()
  38405. */
  38406. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38407. };
  38408. /**
  38409. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38410. * This will be passed three parameters.
  38411. * This does nothing and may be overwritten by the user.
  38412. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38413. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38414. * @param update the boolean update value actually passed to setParticles()
  38415. */
  38416. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38417. };
  38418. return SolidParticleSystem;
  38419. })();
  38420. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38421. })(BABYLON || (BABYLON = {}));
  38422. var BABYLON;
  38423. (function (BABYLON) {
  38424. // We're mainly based on the logic defined into the FreeCamera code
  38425. var UniversalCamera = (function (_super) {
  38426. __extends(UniversalCamera, _super);
  38427. function UniversalCamera(name, position, scene) {
  38428. var _this = this;
  38429. _super.call(this, name, position, scene);
  38430. this.gamepadAngularSensibility = 200;
  38431. this.gamepadMoveSensibility = 40;
  38432. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38433. }
  38434. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38435. // Only the first gamepad can control the camera
  38436. if (gamepad.index === 0) {
  38437. this.gamepad = gamepad;
  38438. }
  38439. };
  38440. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38441. _super.prototype.attachControl.call(this, canvas, false);
  38442. };
  38443. UniversalCamera.prototype.detachControl = function (canvas) {
  38444. _super.prototype.detachControl.call(this, canvas);
  38445. };
  38446. UniversalCamera.prototype._checkInputs = function () {
  38447. if (this.gamepad) {
  38448. var LSValues = this.gamepad.leftStick;
  38449. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38450. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38451. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38452. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38453. var RSValues = this.gamepad.rightStick;
  38454. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38455. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38456. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38457. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38459. var speed = this._computeLocalCameraSpeed() * 50.0;
  38460. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38461. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38462. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38463. }
  38464. _super.prototype._checkInputs.call(this);
  38465. };
  38466. UniversalCamera.prototype.dispose = function () {
  38467. this._gamepads.dispose();
  38468. _super.prototype.dispose.call(this);
  38469. };
  38470. UniversalCamera.prototype.getTypeName = function () {
  38471. return "UniversalCamera";
  38472. };
  38473. __decorate([
  38474. BABYLON.serialize()
  38475. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38476. __decorate([
  38477. BABYLON.serialize()
  38478. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38479. return UniversalCamera;
  38480. })(BABYLON.TouchCamera);
  38481. BABYLON.UniversalCamera = UniversalCamera;
  38482. })(BABYLON || (BABYLON = {}));
  38483. var BABYLON;
  38484. (function (BABYLON) {
  38485. var Gamepads = (function () {
  38486. function Gamepads(ongamedpadconnected) {
  38487. var _this = this;
  38488. this.babylonGamepads = [];
  38489. this.oneGamepadConnected = false;
  38490. this.isMonitoring = false;
  38491. this.gamepadEventSupported = 'GamepadEvent' in window;
  38492. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38493. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38494. this._callbackGamepadConnected = ongamedpadconnected;
  38495. if (this.gamepadSupportAvailable) {
  38496. // Checking if the gamepad connected event is supported (like in Firefox)
  38497. if (this.gamepadEventSupported) {
  38498. window.addEventListener('gamepadconnected', function (evt) {
  38499. _this._onGamepadConnected(evt);
  38500. }, false);
  38501. window.addEventListener('gamepaddisconnected', function (evt) {
  38502. _this._onGamepadDisconnected(evt);
  38503. }, false);
  38504. }
  38505. else {
  38506. this._startMonitoringGamepads();
  38507. }
  38508. }
  38509. }
  38510. Gamepads.prototype.dispose = function () {
  38511. if (Gamepads.gamepadDOMInfo) {
  38512. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38513. }
  38514. };
  38515. Gamepads.prototype._onGamepadConnected = function (evt) {
  38516. var newGamepad = this._addNewGamepad(evt.gamepad);
  38517. if (this._callbackGamepadConnected)
  38518. this._callbackGamepadConnected(newGamepad);
  38519. this._startMonitoringGamepads();
  38520. };
  38521. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38522. if (!this.oneGamepadConnected) {
  38523. this.oneGamepadConnected = true;
  38524. if (Gamepads.gamepadDOMInfo) {
  38525. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38526. Gamepads.gamepadDOMInfo = null;
  38527. }
  38528. }
  38529. var newGamepad;
  38530. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38531. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38532. }
  38533. else {
  38534. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38535. }
  38536. this.babylonGamepads.push(newGamepad);
  38537. return newGamepad;
  38538. };
  38539. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38540. // Remove the gamepad from the list of gamepads to monitor.
  38541. for (var i in this.babylonGamepads) {
  38542. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38543. this.babylonGamepads.splice(+i, 1);
  38544. break;
  38545. }
  38546. }
  38547. // If no gamepads are left, stop the polling loop.
  38548. if (this.babylonGamepads.length == 0) {
  38549. this._stopMonitoringGamepads();
  38550. }
  38551. };
  38552. Gamepads.prototype._startMonitoringGamepads = function () {
  38553. if (!this.isMonitoring) {
  38554. this.isMonitoring = true;
  38555. this._checkGamepadsStatus();
  38556. }
  38557. };
  38558. Gamepads.prototype._stopMonitoringGamepads = function () {
  38559. this.isMonitoring = false;
  38560. };
  38561. Gamepads.prototype._checkGamepadsStatus = function () {
  38562. var _this = this;
  38563. // updating gamepad objects
  38564. this._updateGamepadObjects();
  38565. for (var i in this.babylonGamepads) {
  38566. this.babylonGamepads[i].update();
  38567. }
  38568. if (this.isMonitoring) {
  38569. if (window.requestAnimationFrame) {
  38570. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38571. }
  38572. else if (window.mozRequestAnimationFrame) {
  38573. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38574. }
  38575. else if (window.webkitRequestAnimationFrame) {
  38576. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38577. }
  38578. }
  38579. };
  38580. // This function is called only on Chrome, which does not yet support
  38581. // connection/disconnection events, but requires you to monitor
  38582. // an array for changes.
  38583. Gamepads.prototype._updateGamepadObjects = function () {
  38584. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38585. for (var i = 0; i < gamepads.length; i++) {
  38586. if (gamepads[i]) {
  38587. if (!(gamepads[i].index in this.babylonGamepads)) {
  38588. var newGamepad = this._addNewGamepad(gamepads[i]);
  38589. if (this._callbackGamepadConnected) {
  38590. this._callbackGamepadConnected(newGamepad);
  38591. }
  38592. }
  38593. else {
  38594. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38595. }
  38596. }
  38597. }
  38598. };
  38599. return Gamepads;
  38600. })();
  38601. BABYLON.Gamepads = Gamepads;
  38602. var StickValues = (function () {
  38603. function StickValues(x, y) {
  38604. this.x = x;
  38605. this.y = y;
  38606. }
  38607. return StickValues;
  38608. })();
  38609. BABYLON.StickValues = StickValues;
  38610. var Gamepad = (function () {
  38611. function Gamepad(id, index, browserGamepad) {
  38612. this.id = id;
  38613. this.index = index;
  38614. this.browserGamepad = browserGamepad;
  38615. if (this.browserGamepad.axes.length >= 2) {
  38616. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38617. }
  38618. if (this.browserGamepad.axes.length >= 4) {
  38619. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38620. }
  38621. }
  38622. Gamepad.prototype.onleftstickchanged = function (callback) {
  38623. this._onleftstickchanged = callback;
  38624. };
  38625. Gamepad.prototype.onrightstickchanged = function (callback) {
  38626. this._onrightstickchanged = callback;
  38627. };
  38628. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38629. get: function () {
  38630. return this._leftStick;
  38631. },
  38632. set: function (newValues) {
  38633. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38634. this._onleftstickchanged(newValues);
  38635. }
  38636. this._leftStick = newValues;
  38637. },
  38638. enumerable: true,
  38639. configurable: true
  38640. });
  38641. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38642. get: function () {
  38643. return this._rightStick;
  38644. },
  38645. set: function (newValues) {
  38646. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38647. this._onrightstickchanged(newValues);
  38648. }
  38649. this._rightStick = newValues;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. Gamepad.prototype.update = function () {
  38655. if (this._leftStick) {
  38656. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38657. }
  38658. if (this._rightStick) {
  38659. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38660. }
  38661. };
  38662. return Gamepad;
  38663. })();
  38664. BABYLON.Gamepad = Gamepad;
  38665. var GenericPad = (function (_super) {
  38666. __extends(GenericPad, _super);
  38667. function GenericPad(id, index, gamepad) {
  38668. _super.call(this, id, index, gamepad);
  38669. this.id = id;
  38670. this.index = index;
  38671. this.gamepad = gamepad;
  38672. this._buttons = new Array(gamepad.buttons.length);
  38673. }
  38674. GenericPad.prototype.onbuttondown = function (callback) {
  38675. this._onbuttondown = callback;
  38676. };
  38677. GenericPad.prototype.onbuttonup = function (callback) {
  38678. this._onbuttonup = callback;
  38679. };
  38680. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38681. if (newValue !== currentValue) {
  38682. if (this._onbuttondown && newValue === 1) {
  38683. this._onbuttondown(buttonIndex);
  38684. }
  38685. if (this._onbuttonup && newValue === 0) {
  38686. this._onbuttonup(buttonIndex);
  38687. }
  38688. }
  38689. return newValue;
  38690. };
  38691. GenericPad.prototype.update = function () {
  38692. _super.prototype.update.call(this);
  38693. for (var index = 0; index < this._buttons.length; index++) {
  38694. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38695. }
  38696. };
  38697. return GenericPad;
  38698. })(Gamepad);
  38699. BABYLON.GenericPad = GenericPad;
  38700. (function (Xbox360Button) {
  38701. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38702. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38703. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38704. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38705. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38706. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38707. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38708. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38709. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38710. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38711. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38712. var Xbox360Button = BABYLON.Xbox360Button;
  38713. (function (Xbox360Dpad) {
  38714. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38715. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38716. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38717. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38718. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38719. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38720. var Xbox360Pad = (function (_super) {
  38721. __extends(Xbox360Pad, _super);
  38722. function Xbox360Pad() {
  38723. _super.apply(this, arguments);
  38724. this._leftTrigger = 0;
  38725. this._rightTrigger = 0;
  38726. this._buttonA = 0;
  38727. this._buttonB = 0;
  38728. this._buttonX = 0;
  38729. this._buttonY = 0;
  38730. this._buttonBack = 0;
  38731. this._buttonStart = 0;
  38732. this._buttonLB = 0;
  38733. this._buttonRB = 0;
  38734. this._buttonLeftStick = 0;
  38735. this._buttonRightStick = 0;
  38736. this._dPadUp = 0;
  38737. this._dPadDown = 0;
  38738. this._dPadLeft = 0;
  38739. this._dPadRight = 0;
  38740. }
  38741. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38742. this._onlefttriggerchanged = callback;
  38743. };
  38744. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38745. this._onrighttriggerchanged = callback;
  38746. };
  38747. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38748. get: function () {
  38749. return this._leftTrigger;
  38750. },
  38751. set: function (newValue) {
  38752. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38753. this._onlefttriggerchanged(newValue);
  38754. }
  38755. this._leftTrigger = newValue;
  38756. },
  38757. enumerable: true,
  38758. configurable: true
  38759. });
  38760. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38761. get: function () {
  38762. return this._rightTrigger;
  38763. },
  38764. set: function (newValue) {
  38765. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38766. this._onrighttriggerchanged(newValue);
  38767. }
  38768. this._rightTrigger = newValue;
  38769. },
  38770. enumerable: true,
  38771. configurable: true
  38772. });
  38773. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38774. this._onbuttondown = callback;
  38775. };
  38776. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38777. this._onbuttonup = callback;
  38778. };
  38779. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38780. this._ondpaddown = callback;
  38781. };
  38782. Xbox360Pad.prototype.ondpadup = function (callback) {
  38783. this._ondpadup = callback;
  38784. };
  38785. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38786. if (newValue !== currentValue) {
  38787. if (this._onbuttondown && newValue === 1) {
  38788. this._onbuttondown(buttonType);
  38789. }
  38790. if (this._onbuttonup && newValue === 0) {
  38791. this._onbuttonup(buttonType);
  38792. }
  38793. }
  38794. return newValue;
  38795. };
  38796. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38797. if (newValue !== currentValue) {
  38798. if (this._ondpaddown && newValue === 1) {
  38799. this._ondpaddown(buttonType);
  38800. }
  38801. if (this._ondpadup && newValue === 0) {
  38802. this._ondpadup(buttonType);
  38803. }
  38804. }
  38805. return newValue;
  38806. };
  38807. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38808. get: function () {
  38809. return this._buttonA;
  38810. },
  38811. set: function (value) {
  38812. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38813. },
  38814. enumerable: true,
  38815. configurable: true
  38816. });
  38817. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38818. get: function () {
  38819. return this._buttonB;
  38820. },
  38821. set: function (value) {
  38822. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38823. },
  38824. enumerable: true,
  38825. configurable: true
  38826. });
  38827. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38828. get: function () {
  38829. return this._buttonX;
  38830. },
  38831. set: function (value) {
  38832. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38833. },
  38834. enumerable: true,
  38835. configurable: true
  38836. });
  38837. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38838. get: function () {
  38839. return this._buttonY;
  38840. },
  38841. set: function (value) {
  38842. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38843. },
  38844. enumerable: true,
  38845. configurable: true
  38846. });
  38847. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38848. get: function () {
  38849. return this._buttonStart;
  38850. },
  38851. set: function (value) {
  38852. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38853. },
  38854. enumerable: true,
  38855. configurable: true
  38856. });
  38857. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38858. get: function () {
  38859. return this._buttonBack;
  38860. },
  38861. set: function (value) {
  38862. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38863. },
  38864. enumerable: true,
  38865. configurable: true
  38866. });
  38867. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38868. get: function () {
  38869. return this._buttonLB;
  38870. },
  38871. set: function (value) {
  38872. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38873. },
  38874. enumerable: true,
  38875. configurable: true
  38876. });
  38877. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38878. get: function () {
  38879. return this._buttonRB;
  38880. },
  38881. set: function (value) {
  38882. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38883. },
  38884. enumerable: true,
  38885. configurable: true
  38886. });
  38887. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38888. get: function () {
  38889. return this._buttonLeftStick;
  38890. },
  38891. set: function (value) {
  38892. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38893. },
  38894. enumerable: true,
  38895. configurable: true
  38896. });
  38897. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38898. get: function () {
  38899. return this._buttonRightStick;
  38900. },
  38901. set: function (value) {
  38902. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38903. },
  38904. enumerable: true,
  38905. configurable: true
  38906. });
  38907. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38908. get: function () {
  38909. return this._dPadUp;
  38910. },
  38911. set: function (value) {
  38912. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38913. },
  38914. enumerable: true,
  38915. configurable: true
  38916. });
  38917. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38918. get: function () {
  38919. return this._dPadDown;
  38920. },
  38921. set: function (value) {
  38922. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38923. },
  38924. enumerable: true,
  38925. configurable: true
  38926. });
  38927. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38928. get: function () {
  38929. return this._dPadLeft;
  38930. },
  38931. set: function (value) {
  38932. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38933. },
  38934. enumerable: true,
  38935. configurable: true
  38936. });
  38937. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38938. get: function () {
  38939. return this._dPadRight;
  38940. },
  38941. set: function (value) {
  38942. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38943. },
  38944. enumerable: true,
  38945. configurable: true
  38946. });
  38947. Xbox360Pad.prototype.update = function () {
  38948. _super.prototype.update.call(this);
  38949. this.buttonA = this.browserGamepad.buttons[0].value;
  38950. this.buttonB = this.browserGamepad.buttons[1].value;
  38951. this.buttonX = this.browserGamepad.buttons[2].value;
  38952. this.buttonY = this.browserGamepad.buttons[3].value;
  38953. this.buttonLB = this.browserGamepad.buttons[4].value;
  38954. this.buttonRB = this.browserGamepad.buttons[5].value;
  38955. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38956. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38957. this.buttonBack = this.browserGamepad.buttons[8].value;
  38958. this.buttonStart = this.browserGamepad.buttons[9].value;
  38959. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38960. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38961. this.dPadUp = this.browserGamepad.buttons[12].value;
  38962. this.dPadDown = this.browserGamepad.buttons[13].value;
  38963. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38964. this.dPadRight = this.browserGamepad.buttons[15].value;
  38965. };
  38966. return Xbox360Pad;
  38967. })(Gamepad);
  38968. BABYLON.Xbox360Pad = Xbox360Pad;
  38969. })(BABYLON || (BABYLON = {}));
  38970. var BABYLON;
  38971. (function (BABYLON) {
  38972. // We're mainly based on the logic defined into the FreeCamera code
  38973. var GamepadCamera = (function (_super) {
  38974. __extends(GamepadCamera, _super);
  38975. function GamepadCamera(name, position, scene) {
  38976. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38977. _super.call(this, name, position, scene);
  38978. }
  38979. GamepadCamera.prototype.getTypeName = function () {
  38980. return "GamepadCamera";
  38981. };
  38982. return GamepadCamera;
  38983. })(BABYLON.UniversalCamera);
  38984. BABYLON.GamepadCamera = GamepadCamera;
  38985. })(BABYLON || (BABYLON = {}));
  38986. var BABYLON;
  38987. (function (BABYLON) {
  38988. var AnaglyphFreeCamera = (function (_super) {
  38989. __extends(AnaglyphFreeCamera, _super);
  38990. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38991. _super.call(this, name, position, scene);
  38992. this.interaxialDistance = interaxialDistance;
  38993. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38994. }
  38995. AnaglyphFreeCamera.prototype.getTypeName = function () {
  38996. return "AnaglyphFreeCamera";
  38997. };
  38998. return AnaglyphFreeCamera;
  38999. })(BABYLON.FreeCamera);
  39000. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39001. var AnaglyphArcRotateCamera = (function (_super) {
  39002. __extends(AnaglyphArcRotateCamera, _super);
  39003. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39004. _super.call(this, name, alpha, beta, radius, target, scene);
  39005. this.interaxialDistance = interaxialDistance;
  39006. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39007. }
  39008. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39009. return "AnaglyphArcRotateCamera";
  39010. };
  39011. return AnaglyphArcRotateCamera;
  39012. })(BABYLON.ArcRotateCamera);
  39013. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39014. var AnaglyphGamepadCamera = (function (_super) {
  39015. __extends(AnaglyphGamepadCamera, _super);
  39016. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39017. _super.call(this, name, position, scene);
  39018. this.interaxialDistance = interaxialDistance;
  39019. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39020. }
  39021. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39022. return "AnaglyphGamepadCamera";
  39023. };
  39024. return AnaglyphGamepadCamera;
  39025. })(BABYLON.GamepadCamera);
  39026. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39027. var AnaglyphUniversalCamera = (function (_super) {
  39028. __extends(AnaglyphUniversalCamera, _super);
  39029. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39030. _super.call(this, name, position, scene);
  39031. this.interaxialDistance = interaxialDistance;
  39032. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39033. }
  39034. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39035. return "AnaglyphUniversalCamera";
  39036. };
  39037. return AnaglyphUniversalCamera;
  39038. })(BABYLON.UniversalCamera);
  39039. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39040. var StereoscopicFreeCamera = (function (_super) {
  39041. __extends(StereoscopicFreeCamera, _super);
  39042. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39043. _super.call(this, name, position, scene);
  39044. this.interaxialDistance = interaxialDistance;
  39045. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39046. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39047. }
  39048. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39049. return "StereoscopicFreeCamera";
  39050. };
  39051. return StereoscopicFreeCamera;
  39052. })(BABYLON.FreeCamera);
  39053. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39054. var StereoscopicArcRotateCamera = (function (_super) {
  39055. __extends(StereoscopicArcRotateCamera, _super);
  39056. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39057. _super.call(this, name, alpha, beta, radius, target, scene);
  39058. this.interaxialDistance = interaxialDistance;
  39059. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39060. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39061. }
  39062. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39063. return "StereoscopicArcRotateCamera";
  39064. };
  39065. return StereoscopicArcRotateCamera;
  39066. })(BABYLON.ArcRotateCamera);
  39067. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39068. var StereoscopicGamepadCamera = (function (_super) {
  39069. __extends(StereoscopicGamepadCamera, _super);
  39070. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39071. _super.call(this, name, position, scene);
  39072. this.interaxialDistance = interaxialDistance;
  39073. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39074. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39075. }
  39076. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39077. return "StereoscopicGamepadCamera";
  39078. };
  39079. return StereoscopicGamepadCamera;
  39080. })(BABYLON.GamepadCamera);
  39081. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39082. var StereoscopicUniversalCamera = (function (_super) {
  39083. __extends(StereoscopicUniversalCamera, _super);
  39084. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39085. _super.call(this, name, position, scene);
  39086. this.interaxialDistance = interaxialDistance;
  39087. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39088. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39089. }
  39090. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39091. return "StereoscopicUniversalCamera";
  39092. };
  39093. return StereoscopicUniversalCamera;
  39094. })(BABYLON.UniversalCamera);
  39095. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39096. })(BABYLON || (BABYLON = {}));
  39097. //_______________________________________________________________
  39098. // Extracted from CubeMapGen:
  39099. // https://code.google.com/archive/p/cubemapgen/
  39100. //
  39101. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39102. //_______________________________________________________________
  39103. var BABYLON;
  39104. (function (BABYLON) {
  39105. var Internals;
  39106. (function (Internals) {
  39107. var CMGBoundinBox = (function () {
  39108. function CMGBoundinBox() {
  39109. this.min = new BABYLON.Vector3(0, 0, 0);
  39110. this.max = new BABYLON.Vector3(0, 0, 0);
  39111. this.clear();
  39112. }
  39113. CMGBoundinBox.prototype.clear = function () {
  39114. this.min.x = CMGBoundinBox.MAX;
  39115. this.min.y = CMGBoundinBox.MAX;
  39116. this.min.z = CMGBoundinBox.MAX;
  39117. this.max.x = CMGBoundinBox.MIN;
  39118. this.max.y = CMGBoundinBox.MIN;
  39119. this.max.z = CMGBoundinBox.MIN;
  39120. };
  39121. CMGBoundinBox.prototype.augment = function (x, y, z) {
  39122. this.min.x = Math.min(this.min.x, x);
  39123. this.min.y = Math.min(this.min.y, y);
  39124. this.min.z = Math.min(this.min.z, z);
  39125. this.max.x = Math.max(this.max.x, x);
  39126. this.max.y = Math.max(this.max.y, y);
  39127. this.max.z = Math.max(this.max.z, z);
  39128. };
  39129. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  39130. this.min.x = Math.max(this.min.x, x);
  39131. this.min.y = Math.max(this.min.y, y);
  39132. this.min.z = Math.max(this.min.z, z);
  39133. };
  39134. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  39135. this.max.x = Math.min(this.max.x, x);
  39136. this.max.y = Math.min(this.max.y, y);
  39137. this.max.z = Math.min(this.max.z, z);
  39138. };
  39139. CMGBoundinBox.prototype.empty = function () {
  39140. if ((this.min.x > this.max.y) ||
  39141. (this.min.y > this.max.y) ||
  39142. (this.min.z > this.max.y)) {
  39143. return true;
  39144. }
  39145. else {
  39146. return false;
  39147. }
  39148. };
  39149. CMGBoundinBox.MAX = Number.MAX_VALUE;
  39150. CMGBoundinBox.MIN = Number.MIN_VALUE;
  39151. return CMGBoundinBox;
  39152. })();
  39153. var PMREMGenerator = (function () {
  39154. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  39155. this.input = input;
  39156. this.inputSize = inputSize;
  39157. this.outputSize = outputSize;
  39158. this.maxNumMipLevels = maxNumMipLevels;
  39159. this.numChannels = numChannels;
  39160. this.isFloat = isFloat;
  39161. this.specularPower = specularPower;
  39162. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  39163. this.excludeBase = excludeBase;
  39164. this.fixup = fixup;
  39165. this._outputSurface = [];
  39166. this._numMipLevels = 0;
  39167. }
  39168. PMREMGenerator.prototype.filterCubeMap = function () {
  39169. // Init cubemap processor
  39170. this.init();
  39171. // Filters the cubemap
  39172. this.filterCubeMapMipChain();
  39173. // Returns the filtered mips.
  39174. return this._outputSurface;
  39175. };
  39176. PMREMGenerator.prototype.init = function () {
  39177. var i;
  39178. var j;
  39179. var mipLevelSize;
  39180. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  39181. if (this.maxNumMipLevels == 0) {
  39182. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  39183. }
  39184. //first miplevel size
  39185. mipLevelSize = this.outputSize;
  39186. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  39187. for (j = 0; j < this.maxNumMipLevels; j++) {
  39188. this._outputSurface.length++;
  39189. this._outputSurface[j] = [];
  39190. //Iterate over faces for output images
  39191. for (i = 0; i < 6; i++) {
  39192. this._outputSurface[j].length++;
  39193. // Initializes a new array for the output.
  39194. if (this.isFloat) {
  39195. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39196. }
  39197. else {
  39198. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39199. }
  39200. }
  39201. //next mip level is half size
  39202. mipLevelSize >>= 1;
  39203. this._numMipLevels++;
  39204. //terminate if mip chain becomes too small
  39205. if (mipLevelSize == 0) {
  39206. this.maxNumMipLevels = j;
  39207. return;
  39208. }
  39209. }
  39210. };
  39211. //--------------------------------------------------------------------------------------
  39212. //Cube map filtering and mip chain generation.
  39213. // the cube map filtereing is specified using a number of parameters:
  39214. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  39215. // indicates the region of the hemisphere to filter over for each tap.
  39216. //
  39217. // Note that the top mip level is also a filtered version of the original input images
  39218. // as well in order to create mip chains for diffuse environment illumination.
  39219. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  39220. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  39221. //
  39222. // Then the mip angle used to genreate the next level of the mip chain from the first level
  39223. // is a_InitialMipAngle
  39224. //
  39225. // The angle for the subsequent levels of the mip chain are specified by their parents
  39226. // filtering angle and a per-level scale and bias
  39227. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  39228. //
  39229. //--------------------------------------------------------------------------------------
  39230. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  39231. // First, take count of the lighting model to modify SpecularPower
  39232. // 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;
  39233. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  39234. //Cone angle start (for generating subsequent mip levels)
  39235. var currentSpecularPower = this.specularPower;
  39236. //Build filter lookup tables based on the source miplevel size
  39237. this.precomputeFilterLookupTables(this.inputSize);
  39238. // Note that we need to filter the first level before generating mipmap
  39239. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  39240. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  39241. // TODO : Write a function to copy and scale the base mipmap in output
  39242. // I am just lazy here and just put a high specular power value, and do some if.
  39243. if (this.excludeBase && (levelIndex == 0)) {
  39244. // 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).
  39245. currentSpecularPower = 100000.0;
  39246. }
  39247. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  39248. var srcCubeImage = this.input;
  39249. var dstCubeImage = this._outputSurface[levelIndex];
  39250. var dstSize = this.outputSize >> levelIndex;
  39251. // Compute required angle.
  39252. var angle = this.getBaseFilterAngle(currentSpecularPower);
  39253. // filter cube surfaces
  39254. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  39255. // fix seams
  39256. if (this.fixup) {
  39257. this.fixupCubeEdges(dstCubeImage, dstSize);
  39258. }
  39259. // Decrease the specular power to generate the mipmap chain
  39260. // TODO : Use another method for Exclude (see first comment at start of the function
  39261. if (this.excludeBase && (levelIndex == 0)) {
  39262. currentSpecularPower = this.specularPower;
  39263. }
  39264. currentSpecularPower *= this.cosinePowerDropPerMip;
  39265. }
  39266. };
  39267. //--------------------------------------------------------------------------------------
  39268. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  39269. // It allow to optimize the texel to access base on the specular power.
  39270. //--------------------------------------------------------------------------------------
  39271. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  39272. // We want to find the alpha such that:
  39273. // cos(alpha)^cosinePower = epsilon
  39274. // That's: acos(epsilon^(1/cosinePower))
  39275. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  39276. var angle = 180.0;
  39277. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  39278. angle *= 180.0 / Math.PI; // Convert to degree
  39279. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  39280. return angle;
  39281. };
  39282. //--------------------------------------------------------------------------------------
  39283. //Builds the following lookup tables prior to filtering:
  39284. // -normalizer cube map
  39285. // -tap weight lookup table
  39286. //
  39287. //--------------------------------------------------------------------------------------
  39288. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  39289. var srcTexelAngle;
  39290. var iCubeFace;
  39291. //clear pre-existing normalizer cube map
  39292. this._normCubeMap = [];
  39293. //Normalized vectors per cubeface and per-texel solid angle
  39294. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  39295. };
  39296. //--------------------------------------------------------------------------------------
  39297. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  39298. //
  39299. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  39300. //
  39301. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  39302. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  39303. // below
  39304. //--------------------------------------------------------------------------------------
  39305. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  39306. var iCubeFace;
  39307. var u;
  39308. var v;
  39309. //iterate over cube faces
  39310. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39311. //First three channels for norm cube, and last channel for solid angle
  39312. this._normCubeMap.push(new Float32Array(size * size * 4));
  39313. //fast texture walk, build normalizer cube map
  39314. var facesData = this.input[iCubeFace];
  39315. for (v = 0; v < size; v++) {
  39316. for (u = 0; u < size; u++) {
  39317. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  39318. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  39319. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  39320. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  39321. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  39322. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  39323. }
  39324. }
  39325. }
  39326. };
  39327. //--------------------------------------------------------------------------------------
  39328. // Convert cubemap face texel coordinates and face idx to 3D vector
  39329. // note the U and V coords are integer coords and range from 0 to size-1
  39330. // this routine can be used to generate a normalizer cube map
  39331. //--------------------------------------------------------------------------------------
  39332. // SL BEGIN
  39333. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  39334. var nvcU;
  39335. var nvcV;
  39336. var tempVec;
  39337. // Change from original AMD code
  39338. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39339. // + 0.5f is for texel center addressing
  39340. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  39341. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  39342. // warp fixup
  39343. if (fixup && size > 1) {
  39344. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  39345. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  39346. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  39347. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  39348. }
  39349. // Get current vector
  39350. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  39351. // U contribution
  39352. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39353. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  39354. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  39355. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  39356. // V contribution and Sum
  39357. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39358. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  39359. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  39360. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  39361. //add face axis
  39362. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  39363. PMREMGenerator._vectorTemp.x += faceAxis[0];
  39364. PMREMGenerator._vectorTemp.y += faceAxis[1];
  39365. PMREMGenerator._vectorTemp.z += faceAxis[2];
  39366. //normalize vector
  39367. PMREMGenerator._vectorTemp.normalize();
  39368. return PMREMGenerator._vectorTemp;
  39369. };
  39370. //--------------------------------------------------------------------------------------
  39371. // Convert 3D vector to cubemap face texel coordinates and face idx
  39372. // note the U and V coords are integer coords and range from 0 to size-1
  39373. // this routine can be used to generate a normalizer cube map
  39374. //
  39375. // returns face IDX and texel coords
  39376. //--------------------------------------------------------------------------------------
  39377. // SL BEGIN
  39378. /*
  39379. Mapping Texture Coordinates to Cube Map Faces
  39380. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  39381. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  39382. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  39383. map arrangement in Pixar's RenderMan package.
  39384. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  39385. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  39386. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  39387. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  39388. the major axis direction). The target column in the table below explains how the major axis direction
  39389. maps to the 2D image of a particular cube map target.
  39390. major axis
  39391. direction target sc tc ma
  39392. ---------- --------------------------------- --- --- ---
  39393. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  39394. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  39395. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  39396. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  39397. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  39398. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  39399. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  39400. an updated (s,t) is calculated as follows
  39401. s = ( sc/|ma| + 1 ) / 2
  39402. t = ( tc/|ma| + 1 ) / 2
  39403. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  39404. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  39405. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  39406. */
  39407. // Note this method return U and V in range from 0 to size-1
  39408. // SL END
  39409. // Store the information in vector3 for convenience (faceindex, u, v)
  39410. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  39411. var maxCoord;
  39412. var faceIdx;
  39413. //absolute value 3
  39414. var absX = Math.abs(x);
  39415. var absY = Math.abs(y);
  39416. var absZ = Math.abs(z);
  39417. if (absX >= absY && absX >= absZ) {
  39418. maxCoord = absX;
  39419. if (x >= 0) {
  39420. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  39421. }
  39422. else {
  39423. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39424. }
  39425. }
  39426. else if (absY >= absX && absY >= absZ) {
  39427. maxCoord = absY;
  39428. if (y >= 0) {
  39429. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39430. }
  39431. else {
  39432. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39433. }
  39434. }
  39435. else {
  39436. maxCoord = absZ;
  39437. if (z >= 0) {
  39438. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39439. }
  39440. else {
  39441. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39442. }
  39443. }
  39444. //divide through by max coord so face vector lies on cube face
  39445. var scale = 1 / maxCoord;
  39446. x *= scale;
  39447. y *= scale;
  39448. z *= scale;
  39449. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39450. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  39451. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39452. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  39453. // Modify original AMD code to return value from 0 to Size - 1
  39454. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  39455. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  39456. PMREMGenerator._vectorTemp.x = faceIdx;
  39457. PMREMGenerator._vectorTemp.y = u;
  39458. PMREMGenerator._vectorTemp.z = v;
  39459. return PMREMGenerator._vectorTemp;
  39460. };
  39461. //--------------------------------------------------------------------------------------
  39462. //Original code from Ignacio CastaÒo
  39463. // This formula is from Manne ÷hrstrˆm's thesis.
  39464. // Take two coordiantes in the range [-1, 1] that define a portion of a
  39465. // cube face and return the area of the projection of that portion on the
  39466. // surface of the sphere.
  39467. //--------------------------------------------------------------------------------------
  39468. PMREMGenerator.prototype.areaElement = function (x, y) {
  39469. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  39470. };
  39471. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  39472. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39473. // (+ 0.5f is for texel center addressing)
  39474. u = (2.0 * (u + 0.5) / size) - 1.0;
  39475. v = (2.0 * (v + 0.5) / size) - 1.0;
  39476. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  39477. var invResolution = 1.0 / size;
  39478. // U and V are the -1..1 texture coordinate on the current face.
  39479. // Get projected area for this texel
  39480. var x0 = u - invResolution;
  39481. var y0 = v - invResolution;
  39482. var x1 = u + invResolution;
  39483. var y1 = v + invResolution;
  39484. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  39485. return solidAngle;
  39486. };
  39487. //--------------------------------------------------------------------------------------
  39488. //The key to the speed of these filtering routines is to quickly define a per-face
  39489. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  39490. // Later these pixels are selectively processed based on their dot products to see if
  39491. // they reside within the filtering cone.
  39492. //
  39493. //This is done by computing the smallest per-texel angle to get a conservative estimate
  39494. // of the number of texels needed to be covered in width and height order to filter the
  39495. // region. the bounding box for the center taps face is defined first, and if the
  39496. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  39497. // defined next
  39498. //--------------------------------------------------------------------------------------
  39499. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  39500. // note that pixels within these regions may be rejected
  39501. // based on the anlge
  39502. var iCubeFace;
  39503. var u;
  39504. var v;
  39505. // bounding box per face to specify region to process
  39506. var filterExtents = [];
  39507. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39508. filterExtents.push(new CMGBoundinBox());
  39509. }
  39510. // min angle a src texel can cover (in degrees)
  39511. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  39512. // angle about center tap to define filter cone
  39513. // filter angle is 1/2 the cone angle
  39514. var filterAngle = filterConeAngle / 2.0;
  39515. //ensure filter angle is larger than a texel
  39516. if (filterAngle < srcTexelAngle) {
  39517. filterAngle = srcTexelAngle;
  39518. }
  39519. //ensure filter cone is always smaller than the hemisphere
  39520. if (filterAngle > 90.0) {
  39521. filterAngle = 90.0;
  39522. }
  39523. // the maximum number of texels in 1D the filter cone angle will cover
  39524. // used to determine bounding box size for filter extents
  39525. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  39526. // ensure conservative region always covers at least one texel
  39527. if (filterSize < 1) {
  39528. filterSize = 1;
  39529. }
  39530. // dotProdThresh threshold based on cone angle to determine whether or not taps
  39531. // reside within the cone angle
  39532. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  39533. // process required faces
  39534. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39535. //iterate over dst cube map face texel
  39536. for (v = 0; v < dstSize; v++) {
  39537. for (u = 0; u < dstSize; u++) {
  39538. //get center tap direction
  39539. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  39540. //clear old per-face filter extents
  39541. this.clearFilterExtents(filterExtents);
  39542. //define per-face filter extents
  39543. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  39544. //perform filtering of src faces using filter extents
  39545. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  39546. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  39547. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  39548. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  39549. }
  39550. }
  39551. }
  39552. };
  39553. //--------------------------------------------------------------------------------------
  39554. //Clear filter extents for the 6 cube map faces
  39555. //--------------------------------------------------------------------------------------
  39556. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  39557. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  39558. filterExtents[iCubeFaces].clear();
  39559. }
  39560. };
  39561. //--------------------------------------------------------------------------------------
  39562. //Define per-face bounding box filter extents
  39563. //
  39564. // These define conservative texel regions in each of the faces the filter can possibly
  39565. // process. When the pixels in the regions are actually processed, the dot product
  39566. // between the tap vector and the center tap vector is used to determine the weight of
  39567. // the tap and whether or not the tap is within the cone.
  39568. //
  39569. //--------------------------------------------------------------------------------------
  39570. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  39571. //neighboring face and bleed over amount, and width of BBOX for
  39572. // left, right, top, and bottom edges of this face
  39573. var bleedOverAmount = [0, 0, 0, 0];
  39574. var bleedOverBBoxMin = [0, 0, 0, 0];
  39575. var bleedOverBBoxMax = [0, 0, 0, 0];
  39576. var neighborFace;
  39577. var neighborEdge;
  39578. var oppositeFaceIdx;
  39579. //get face idx, and u, v info from center tap dir
  39580. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  39581. var faceIdx = result.x;
  39582. var u = result.y;
  39583. var v = result.z;
  39584. //define bbox size within face
  39585. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  39586. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  39587. filterExtents[faceIdx].clampMin(0, 0, 0);
  39588. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  39589. //u and v extent in face corresponding to center tap
  39590. var minU = filterExtents[faceIdx].min.x;
  39591. var minV = filterExtents[faceIdx].min.y;
  39592. var maxU = filterExtents[faceIdx].max.x;
  39593. var maxV = filterExtents[faceIdx].max.y;
  39594. //bleed over amounts for face across u=0 edge (left)
  39595. bleedOverAmount[0] = (bboxSize - u);
  39596. bleedOverBBoxMin[0] = minV;
  39597. bleedOverBBoxMax[0] = maxV;
  39598. //bleed over amounts for face across u=1 edge (right)
  39599. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  39600. bleedOverBBoxMin[1] = minV;
  39601. bleedOverBBoxMax[1] = maxV;
  39602. //bleed over to face across v=0 edge (up)
  39603. bleedOverAmount[2] = (bboxSize - v);
  39604. bleedOverBBoxMin[2] = minU;
  39605. bleedOverBBoxMax[2] = maxU;
  39606. //bleed over to face across v=1 edge (down)
  39607. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  39608. bleedOverBBoxMin[3] = minU;
  39609. bleedOverBBoxMax[3] = maxU;
  39610. //compute bleed over regions in neighboring faces
  39611. for (var i = 0; i < 4; i++) {
  39612. if (bleedOverAmount[i] > 0) {
  39613. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  39614. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  39615. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  39616. // be flipped: the cases are
  39617. // if a left edge mates with a left or bottom edge on the neighbor
  39618. // if a top edge mates with a top or right edge on the neighbor
  39619. // if a right edge mates with a right or top edge on the neighbor
  39620. // if a bottom edge mates with a bottom or left edge on the neighbor
  39621. //Seeing as the edges are enumerated as follows
  39622. // left =0
  39623. // right =1
  39624. // top =2
  39625. // bottom =3
  39626. //
  39627. // so if the edge enums are the same, or the sum of the enums == 3,
  39628. // the bbox needs to be flipped
  39629. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  39630. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  39631. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  39632. }
  39633. //The way the bounding box is extended onto the neighboring face
  39634. // depends on which edge of neighboring face abuts with this one
  39635. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  39636. case PMREMGenerator.CP_EDGE_LEFT:
  39637. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  39638. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39639. break;
  39640. case PMREMGenerator.CP_EDGE_RIGHT:
  39641. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  39642. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39643. break;
  39644. case PMREMGenerator.CP_EDGE_TOP:
  39645. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  39646. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  39647. break;
  39648. case PMREMGenerator.CP_EDGE_BOTTOM:
  39649. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  39650. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  39651. break;
  39652. }
  39653. //clamp filter extents in non-center tap faces to remain within surface
  39654. filterExtents[neighborFace].clampMin(0, 0, 0);
  39655. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  39656. }
  39657. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  39658. // from the center tap face, then process the opposite face entirely for now.
  39659. //Note that the cases in which this happens, what usually happens is that
  39660. // more than one edge bleeds onto the opposite face, and the bounding box
  39661. // encompasses the entire cube map face.
  39662. if (bleedOverAmount[i] > srcSize) {
  39663. //determine opposite face
  39664. switch (faceIdx) {
  39665. case PMREMGenerator.CP_FACE_X_POS:
  39666. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39667. break;
  39668. case PMREMGenerator.CP_FACE_X_NEG:
  39669. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  39670. break;
  39671. case PMREMGenerator.CP_FACE_Y_POS:
  39672. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39673. break;
  39674. case PMREMGenerator.CP_FACE_Y_NEG:
  39675. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39676. break;
  39677. case PMREMGenerator.CP_FACE_Z_POS:
  39678. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39679. break;
  39680. case PMREMGenerator.CP_FACE_Z_NEG:
  39681. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39682. break;
  39683. default:
  39684. break;
  39685. }
  39686. //just encompass entire face for now
  39687. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  39688. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  39689. }
  39690. }
  39691. };
  39692. //--------------------------------------------------------------------------------------
  39693. //ProcessFilterExtents
  39694. // Process bounding box in each cube face
  39695. //
  39696. //--------------------------------------------------------------------------------------
  39697. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  39698. //accumulators are 64-bit floats in order to have the precision needed
  39699. // over a summation of a large number of pixels
  39700. var dstAccum = [0, 0, 0, 0];
  39701. var weightAccum = 0;
  39702. var k = 0;
  39703. var nSrcChannels = this.numChannels;
  39704. // norm cube map and srcCubeMap have same face width
  39705. var faceWidth = srcSize;
  39706. //amount to add to pointer to move to next scanline in images
  39707. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  39708. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  39709. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  39710. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  39711. // iterate over cubefaces
  39712. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  39713. //if bbox is non empty
  39714. if (!filterExtents[iFaceIdx].empty()) {
  39715. var uStart = filterExtents[iFaceIdx].min.x;
  39716. var vStart = filterExtents[iFaceIdx].min.y;
  39717. var uEnd = filterExtents[iFaceIdx].max.x;
  39718. var vEnd = filterExtents[iFaceIdx].max.y;
  39719. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  39720. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  39721. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  39722. for (var v = vStart; v <= vEnd; v++) {
  39723. var normCubeRowWalk = 0;
  39724. var srcCubeRowWalk = 0;
  39725. for (var u = uStart; u <= uEnd; u++) {
  39726. //pointer to direction in cube map associated with texel
  39727. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  39728. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  39729. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  39730. //check dot product to see if texel is within cone
  39731. var tapDotProd = texelVectX * centerTapDir.x +
  39732. texelVectY * centerTapDir.y +
  39733. texelVectZ * centerTapDir.z;
  39734. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  39735. //solid angle stored in 4th channel of normalizer/solid angle cube map
  39736. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  39737. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  39738. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  39739. // so just adding one to specularpower do the trick.
  39740. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  39741. //iterate over channels
  39742. for (k = 0; k < nSrcChannels; k++) {
  39743. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  39744. srcCubeRowWalk++;
  39745. }
  39746. weightAccum += weight; //accumulate weight
  39747. }
  39748. else {
  39749. //step across source pixel
  39750. srcCubeRowWalk += nSrcChannels;
  39751. }
  39752. normCubeRowWalk += 4; // 4 channels per norm cube map.
  39753. }
  39754. startIndexNormCubeMap += normCubePitch;
  39755. startIndexSrcCubeMap += srcCubePitch;
  39756. }
  39757. }
  39758. }
  39759. //divide through by weights if weight is non zero
  39760. if (weightAccum != 0.0) {
  39761. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  39762. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  39763. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  39764. if (this.numChannels > 3) {
  39765. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  39766. }
  39767. }
  39768. else {
  39769. // otherwise sample nearest
  39770. // get face idx and u, v texel coordinate in face
  39771. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  39772. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  39773. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  39774. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  39775. if (this.numChannels > 3) {
  39776. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  39777. }
  39778. }
  39779. return PMREMGenerator._vectorTemp;
  39780. };
  39781. //--------------------------------------------------------------------------------------
  39782. // Fixup cube edges
  39783. //
  39784. // average texels on cube map faces across the edges
  39785. // WARP/BENT Method Only.
  39786. //--------------------------------------------------------------------------------------
  39787. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  39788. var k;
  39789. var j;
  39790. var i;
  39791. var iFace;
  39792. var iCorner = 0;
  39793. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  39794. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  39795. // note that if functionality to filter across the three texels for each corner, then
  39796. //indexed by corner and face idx. the array contains the face the start points belongs to.
  39797. var cornerPtr = [
  39798. [[], [], []],
  39799. [[], [], []],
  39800. [[], [], []],
  39801. [[], [], []],
  39802. [[], [], []],
  39803. [[], [], []],
  39804. [[], [], []],
  39805. [[], [], []]
  39806. ];
  39807. //if there is no fixup, or fixup width = 0, do nothing
  39808. if (cubeMapSize < 1) {
  39809. return;
  39810. }
  39811. //special case 1x1 cubemap, average face colors
  39812. if (cubeMapSize == 1) {
  39813. //iterate over channels
  39814. for (k = 0; k < this.numChannels; k++) {
  39815. var accum = 0.0;
  39816. //iterate over faces to accumulate face colors
  39817. for (iFace = 0; iFace < 6; iFace++) {
  39818. accum += cubeMap[iFace][k];
  39819. }
  39820. //compute average over 6 face colors
  39821. accum /= 6.0;
  39822. //iterate over faces to distribute face colors
  39823. for (iFace = 0; iFace < 6; iFace++) {
  39824. cubeMap[iFace][k] = accum;
  39825. }
  39826. }
  39827. return;
  39828. }
  39829. //iterate over faces to collect list of corner texel pointers
  39830. for (iFace = 0; iFace < 6; iFace++) {
  39831. //the 4 corner pointers for this face
  39832. faceCornerStartIndicies[0] = [iFace, 0];
  39833. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  39834. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  39835. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  39836. //iterate over face corners to collect cube corner pointers
  39837. for (iCorner = 0; iCorner < 4; iCorner++) {
  39838. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  39839. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  39840. cornerNumPtrs[corner]++;
  39841. }
  39842. }
  39843. //iterate over corners to average across corner tap values
  39844. for (iCorner = 0; iCorner < 8; iCorner++) {
  39845. for (k = 0; k < this.numChannels; k++) {
  39846. var cornerTapAccum = 0.0;
  39847. //iterate over corner texels and average results
  39848. for (i = 0; i < 3; i++) {
  39849. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  39850. }
  39851. //divide by 3 to compute average of corner tap values
  39852. cornerTapAccum *= (1.0 / 3.0);
  39853. //iterate over corner texels and average results
  39854. for (i = 0; i < 3; i++) {
  39855. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  39856. }
  39857. }
  39858. }
  39859. //iterate over the twelve edges of the cube to average across edges
  39860. for (i = 0; i < 12; i++) {
  39861. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  39862. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  39863. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  39864. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  39865. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  39866. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  39867. var edgeWalk = 0;
  39868. var neighborEdgeWalk = 0;
  39869. //Determine walking pointers based on edge type
  39870. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  39871. switch (edge) {
  39872. case PMREMGenerator.CP_EDGE_LEFT:
  39873. // no change to faceEdgeStartPtr
  39874. edgeWalk = this.numChannels * cubeMapSize;
  39875. break;
  39876. case PMREMGenerator.CP_EDGE_RIGHT:
  39877. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39878. edgeWalk = this.numChannels * cubeMapSize;
  39879. break;
  39880. case PMREMGenerator.CP_EDGE_TOP:
  39881. // no change to faceEdgeStartPtr
  39882. edgeWalk = this.numChannels;
  39883. break;
  39884. case PMREMGenerator.CP_EDGE_BOTTOM:
  39885. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  39886. edgeWalk = this.numChannels;
  39887. break;
  39888. }
  39889. //For certain types of edge abutments, the neighbor edge walk needs to
  39890. // be flipped: the cases are
  39891. // if a left edge mates with a left or bottom edge on the neighbor
  39892. // if a top edge mates with a top or right edge on the neighbor
  39893. // if a right edge mates with a right or top edge on the neighbor
  39894. // if a bottom edge mates with a bottom or left edge on the neighbor
  39895. //Seeing as the edges are enumerated as follows
  39896. // left =0
  39897. // right =1
  39898. // top =2
  39899. // bottom =3
  39900. //
  39901. //If the edge enums are the same, or the sum of the enums == 3,
  39902. // the neighbor edge walk needs to be flipped
  39903. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  39904. switch (neighborEdge) {
  39905. case PMREMGenerator.CP_EDGE_LEFT:
  39906. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  39907. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  39908. break;
  39909. case PMREMGenerator.CP_EDGE_RIGHT:
  39910. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  39911. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  39912. break;
  39913. case PMREMGenerator.CP_EDGE_TOP:
  39914. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39915. neighborEdgeWalk = -this.numChannels;
  39916. break;
  39917. case PMREMGenerator.CP_EDGE_BOTTOM:
  39918. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  39919. neighborEdgeWalk = -this.numChannels;
  39920. break;
  39921. }
  39922. }
  39923. else {
  39924. //swapped direction neighbor edge walk
  39925. switch (neighborEdge) {
  39926. case PMREMGenerator.CP_EDGE_LEFT:
  39927. //no change to neighborEdgeStartPtr for this case since it points
  39928. // to the upper left corner already
  39929. neighborEdgeWalk = this.numChannels * cubeMapSize;
  39930. break;
  39931. case PMREMGenerator.CP_EDGE_RIGHT:
  39932. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39933. neighborEdgeWalk = this.numChannels * cubeMapSize;
  39934. break;
  39935. case PMREMGenerator.CP_EDGE_TOP:
  39936. //no change to neighborEdgeStartPtr for this case since it points
  39937. // to the upper left corner already
  39938. neighborEdgeWalk = this.numChannels;
  39939. break;
  39940. case PMREMGenerator.CP_EDGE_BOTTOM:
  39941. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  39942. neighborEdgeWalk = this.numChannels;
  39943. break;
  39944. }
  39945. }
  39946. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  39947. //nearby neighborhood
  39948. //step ahead one texel on edge
  39949. edgeStartIndex += edgeWalk;
  39950. neighborEdgeStartIndex += neighborEdgeWalk;
  39951. // note that this loop does not process the corner texels, since they have already been
  39952. // averaged across faces across earlier
  39953. for (j = 1; j < (cubeMapSize - 1); j++) {
  39954. //for each set of taps along edge, average them
  39955. // and rewrite the results into the edges
  39956. for (k = 0; k < this.numChannels; k++) {
  39957. var edgeTap = cubeMap[face][edgeStartIndex + k];
  39958. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  39959. //compute average of tap intensity values
  39960. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  39961. //propagate average of taps to edge taps
  39962. cubeMap[face][edgeStartIndex + k] = avgTap;
  39963. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  39964. }
  39965. edgeStartIndex += edgeWalk;
  39966. neighborEdgeStartIndex += neighborEdgeWalk;
  39967. }
  39968. }
  39969. };
  39970. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  39971. PMREMGenerator.CP_UDIR = 0;
  39972. PMREMGenerator.CP_VDIR = 1;
  39973. PMREMGenerator.CP_FACEAXIS = 2;
  39974. //used to index cube faces
  39975. PMREMGenerator.CP_FACE_X_POS = 0;
  39976. PMREMGenerator.CP_FACE_X_NEG = 1;
  39977. PMREMGenerator.CP_FACE_Y_POS = 2;
  39978. PMREMGenerator.CP_FACE_Y_NEG = 3;
  39979. PMREMGenerator.CP_FACE_Z_POS = 4;
  39980. PMREMGenerator.CP_FACE_Z_NEG = 5;
  39981. //used to index image edges
  39982. // NOTE.. the actual number corresponding to the edge is important
  39983. // do not change these, or the code will break
  39984. //
  39985. // CP_EDGE_LEFT is u = 0
  39986. // CP_EDGE_RIGHT is u = width-1
  39987. // CP_EDGE_TOP is v = 0
  39988. // CP_EDGE_BOTTOM is v = height-1
  39989. PMREMGenerator.CP_EDGE_LEFT = 0;
  39990. PMREMGenerator.CP_EDGE_RIGHT = 1;
  39991. PMREMGenerator.CP_EDGE_TOP = 2;
  39992. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  39993. //corners of CUBE map (P or N specifys if it corresponds to the
  39994. // positive or negative direction each of X, Y, and Z
  39995. PMREMGenerator.CP_CORNER_NNN = 0;
  39996. PMREMGenerator.CP_CORNER_NNP = 1;
  39997. PMREMGenerator.CP_CORNER_NPN = 2;
  39998. PMREMGenerator.CP_CORNER_NPP = 3;
  39999. PMREMGenerator.CP_CORNER_PNN = 4;
  40000. PMREMGenerator.CP_CORNER_PNP = 5;
  40001. PMREMGenerator.CP_CORNER_PPN = 6;
  40002. PMREMGenerator.CP_CORNER_PPP = 7;
  40003. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  40004. //3x2 matrices that map cube map indexing vectors in 3d
  40005. // (after face selection and divide through by the
  40006. // _ABSOLUTE VALUE_ of the max coord)
  40007. // into NVC space
  40008. //Note this currently assumes the D3D cube face ordering and orientation
  40009. PMREMGenerator._sgFace2DMapping = [
  40010. //XPOS face
  40011. [[0, 0, -1],
  40012. [0, -1, 0],
  40013. [1, 0, 0]],
  40014. //XNEG face
  40015. [[0, 0, 1],
  40016. [0, -1, 0],
  40017. [-1, 0, 0]],
  40018. //YPOS face
  40019. [[1, 0, 0],
  40020. [0, 0, 1],
  40021. [0, 1, 0]],
  40022. //YNEG face
  40023. [[1, 0, 0],
  40024. [0, 0, -1],
  40025. [0, -1, 0]],
  40026. //ZPOS face
  40027. [[1, 0, 0],
  40028. [0, -1, 0],
  40029. [0, 0, 1]],
  40030. //ZNEG face
  40031. [[-1, 0, 0],
  40032. [0, -1, 0],
  40033. [0, 0, -1]],
  40034. ];
  40035. //------------------------------------------------------------------------------
  40036. // D3D cube map face specification
  40037. // mapping from 3D x,y,z cube map lookup coordinates
  40038. // to 2D within face u,v coordinates
  40039. //
  40040. // --------------------> U direction
  40041. // | (within-face texture space)
  40042. // | _____
  40043. // | | |
  40044. // | | +Y |
  40045. // | _____|_____|_____ _____
  40046. // | | | | | |
  40047. // | | -X | +Z | +X | -Z |
  40048. // | |_____|_____|_____|_____|
  40049. // | | |
  40050. // | | -Y |
  40051. // | |_____|
  40052. // |
  40053. // v V direction
  40054. // (within-face texture space)
  40055. //------------------------------------------------------------------------------
  40056. //Information about neighbors and how texture coorrdinates change across faces
  40057. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  40058. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  40059. //Note this currently assumes the D3D cube face ordering and orientation
  40060. PMREMGenerator._sgCubeNgh = [
  40061. //XPOS face
  40062. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40063. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40064. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40065. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  40066. //XNEG face
  40067. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40068. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  40069. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  40070. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  40071. //YPOS face
  40072. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40073. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40074. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40075. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  40076. //YNEG face
  40077. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40078. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40079. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40080. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  40081. //ZPOS face
  40082. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40083. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40084. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40085. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  40086. //ZNEG face
  40087. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40088. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40089. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  40090. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  40091. ];
  40092. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  40093. // this table is used to average over the edges.
  40094. PMREMGenerator._sgCubeEdgeList = [
  40095. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40096. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40097. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40098. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40099. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40100. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40101. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40102. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40103. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  40104. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40105. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40106. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  40107. ];
  40108. //Information about which of the 8 cube corners are correspond to the
  40109. // the 4 corners in each cube face
  40110. // the order is upper left, upper right, lower left, lower right
  40111. PMREMGenerator._sgCubeCornerList = [
  40112. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  40113. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  40114. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  40115. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  40116. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  40117. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  40118. ];
  40119. return PMREMGenerator;
  40120. })();
  40121. Internals.PMREMGenerator = PMREMGenerator;
  40122. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40123. })(BABYLON || (BABYLON = {}));
  40124. var BABYLON;
  40125. (function (BABYLON) {
  40126. var Internals;
  40127. (function (Internals) {
  40128. var FileFaceOrientation = (function () {
  40129. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40130. this.name = name;
  40131. this.worldAxisForNormal = worldAxisForNormal;
  40132. this.worldAxisForFileX = worldAxisForFileX;
  40133. this.worldAxisForFileY = worldAxisForFileY;
  40134. }
  40135. return FileFaceOrientation;
  40136. })();
  40137. ;
  40138. var CubeMapToSphericalPolynomialTools = (function () {
  40139. function CubeMapToSphericalPolynomialTools() {
  40140. }
  40141. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40142. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40143. var totalSolidAngle = 0.0;
  40144. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40145. var du = 2.0 / cubeInfo.size;
  40146. var dv = du;
  40147. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40148. var minUV = du * 0.5 - 1.0;
  40149. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40150. var fileFace = this.FileFaces[faceIndex];
  40151. var dataArray = cubeInfo[fileFace.name];
  40152. var v = minUV;
  40153. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40154. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40155. // Because SP is still linear, so summation is fine in that basis.
  40156. for (var y = 0; y < cubeInfo.size; y++) {
  40157. var u = minUV;
  40158. for (var x = 0; x < cubeInfo.size; x++) {
  40159. // World direction (not normalised)
  40160. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40161. worldDirection.normalize();
  40162. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40163. if (1) {
  40164. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40165. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40166. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40167. var color = new BABYLON.Color3(r, g, b);
  40168. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40169. }
  40170. else {
  40171. if (faceIndex == 0) {
  40172. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40173. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40174. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40175. }
  40176. else if (faceIndex == 1) {
  40177. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40178. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40179. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40180. }
  40181. else if (faceIndex == 2) {
  40182. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40183. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40184. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40185. }
  40186. else if (faceIndex == 3) {
  40187. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40188. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40189. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40190. }
  40191. else if (faceIndex == 4) {
  40192. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40193. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40194. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40195. }
  40196. else if (faceIndex == 5) {
  40197. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40198. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40199. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40200. }
  40201. 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]);
  40202. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40203. }
  40204. totalSolidAngle += deltaSolidAngle;
  40205. u += du;
  40206. }
  40207. v += dv;
  40208. }
  40209. }
  40210. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40211. var correction = correctSolidAngle / totalSolidAngle;
  40212. sphericalHarmonics.scale(correction);
  40213. // Additionally scale by pi -- audit needed
  40214. sphericalHarmonics.scale(1.0 / Math.PI);
  40215. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40216. };
  40217. CubeMapToSphericalPolynomialTools.FileFaces = [
  40218. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40219. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40220. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40221. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40222. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40223. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40224. ];
  40225. return CubeMapToSphericalPolynomialTools;
  40226. })();
  40227. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40228. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40229. })(BABYLON || (BABYLON = {}));
  40230. var BABYLON;
  40231. (function (BABYLON) {
  40232. var Internals;
  40233. (function (Internals) {
  40234. var PanoramaToCubeMapTools = (function () {
  40235. function PanoramaToCubeMapTools() {
  40236. }
  40237. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40238. if (!float32Array) {
  40239. throw "ConvertPanoramaToCubemap: input cannot be null";
  40240. }
  40241. if (float32Array.length != inputWidth * inputHeight * 3) {
  40242. throw "ConvertPanoramaToCubemap: input size is wrong";
  40243. }
  40244. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40245. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40246. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40247. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40248. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40249. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40250. return {
  40251. front: textureFront,
  40252. back: textureBack,
  40253. left: textureLeft,
  40254. right: textureRight,
  40255. up: textureUp,
  40256. down: textureDown,
  40257. size: size
  40258. };
  40259. };
  40260. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40261. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40262. var textureArray = new Float32Array(buffer);
  40263. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40264. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40265. var dy = 1 / texSize;
  40266. var fy = 0;
  40267. for (var y = 0; y < texSize; y++) {
  40268. var xv1 = faceData[0];
  40269. var xv2 = faceData[2];
  40270. for (var x = 0; x < texSize; x++) {
  40271. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40272. v.normalize();
  40273. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40274. // 3 channels per pixels
  40275. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40276. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40277. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40278. xv1 = xv1.add(rotDX1);
  40279. xv2 = xv2.add(rotDX2);
  40280. }
  40281. fy += dy;
  40282. }
  40283. return textureArray;
  40284. };
  40285. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40286. var theta = Math.atan2(vDir.z, vDir.x);
  40287. var phi = Math.acos(vDir.y);
  40288. while (theta < -Math.PI)
  40289. theta += 2 * Math.PI;
  40290. while (theta > Math.PI)
  40291. theta -= 2 * Math.PI;
  40292. var dx = theta / Math.PI;
  40293. var dy = phi / Math.PI;
  40294. // recenter.
  40295. dx = dx * 0.5 + 0.5;
  40296. var px = Math.round(dx * inputWidth);
  40297. if (px < 0)
  40298. px = 0;
  40299. else if (px >= inputWidth)
  40300. px = inputWidth - 1;
  40301. var py = Math.round(dy * inputHeight);
  40302. if (py < 0)
  40303. py = 0;
  40304. else if (py >= inputHeight)
  40305. py = inputHeight - 1;
  40306. var inputY = (inputHeight - py - 1);
  40307. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40308. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40309. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40310. return {
  40311. r: r,
  40312. g: g,
  40313. b: b
  40314. };
  40315. };
  40316. PanoramaToCubeMapTools.FACE_FRONT = [
  40317. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40318. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40319. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40320. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40321. ];
  40322. PanoramaToCubeMapTools.FACE_BACK = [
  40323. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40324. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40325. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40326. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40327. ];
  40328. PanoramaToCubeMapTools.FACE_RIGHT = [
  40329. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40330. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40331. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40332. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40333. ];
  40334. PanoramaToCubeMapTools.FACE_LEFT = [
  40335. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40336. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40337. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40338. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40339. ];
  40340. PanoramaToCubeMapTools.FACE_DOWN = [
  40341. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40342. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40343. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40344. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40345. ];
  40346. PanoramaToCubeMapTools.FACE_UP = [
  40347. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40348. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40349. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40350. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40351. ];
  40352. return PanoramaToCubeMapTools;
  40353. })();
  40354. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40355. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40356. })(BABYLON || (BABYLON = {}));
  40357. var BABYLON;
  40358. (function (BABYLON) {
  40359. var Internals;
  40360. (function (Internals) {
  40361. ;
  40362. var HDRTools = (function () {
  40363. function HDRTools() {
  40364. }
  40365. HDRTools.Ldexp = function (mantissa, exponent) {
  40366. if (exponent > 1023) {
  40367. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40368. }
  40369. if (exponent < -1074) {
  40370. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40371. }
  40372. return mantissa * Math.pow(2, exponent);
  40373. };
  40374. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40375. if (exponent > 0) {
  40376. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40377. float32array[index + 0] = red * exponent;
  40378. float32array[index + 1] = green * exponent;
  40379. float32array[index + 2] = blue * exponent;
  40380. }
  40381. else {
  40382. float32array[index + 0] = 0;
  40383. float32array[index + 1] = 0;
  40384. float32array[index + 2] = 0;
  40385. }
  40386. };
  40387. HDRTools.readStringLine = function (uint8array, startIndex) {
  40388. var line = "";
  40389. var character = "";
  40390. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40391. character = String.fromCharCode(uint8array[i]);
  40392. if (character == "\n") {
  40393. break;
  40394. }
  40395. line += character;
  40396. }
  40397. return line;
  40398. };
  40399. /* minimal header reading. modify if you want to parse more information */
  40400. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40401. var height = 0;
  40402. var width = 0;
  40403. var line = this.readStringLine(uint8array, 0);
  40404. if (line[0] != '#' || line[1] != '?') {
  40405. throw "Bad HDR Format.";
  40406. }
  40407. var endOfHeader = false;
  40408. var findFormat = false;
  40409. var lineIndex = 0;
  40410. do {
  40411. lineIndex += (line.length + 1);
  40412. line = this.readStringLine(uint8array, lineIndex);
  40413. if (line == "FORMAT=32-bit_rle_rgbe") {
  40414. findFormat = true;
  40415. }
  40416. else if (line.length == 0) {
  40417. endOfHeader = true;
  40418. }
  40419. } while (!endOfHeader);
  40420. if (!findFormat) {
  40421. throw "HDR Bad header format, unsupported FORMAT";
  40422. }
  40423. lineIndex += (line.length + 1);
  40424. line = this.readStringLine(uint8array, lineIndex);
  40425. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40426. var match = sizeRegexp.exec(line);
  40427. // TODO. Support +Y and -X if needed.
  40428. if (match.length < 3) {
  40429. throw "HDR Bad header format, no size";
  40430. }
  40431. width = parseInt(match[2]);
  40432. height = parseInt(match[1]);
  40433. if (width < 8 || width > 0x7fff) {
  40434. throw "HDR Bad header format, unsupported size";
  40435. }
  40436. lineIndex += (line.length + 1);
  40437. return {
  40438. height: height,
  40439. width: width,
  40440. dataPosition: lineIndex
  40441. };
  40442. };
  40443. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40444. var uint8array = new Uint8Array(buffer);
  40445. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40446. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40447. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40448. return cubeMapData;
  40449. };
  40450. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40451. // Keep for multi format supports.
  40452. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40453. };
  40454. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40455. var num_scanlines = hdrInfo.height;
  40456. var scanline_width = hdrInfo.width;
  40457. var a, b, c, d, count;
  40458. var dataIndex = hdrInfo.dataPosition;
  40459. var index = 0, endIndex = 0, i = 0;
  40460. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40461. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40462. // 3 channels of 4 bytes per pixel in float.
  40463. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40464. var resultArray = new Float32Array(resultBuffer);
  40465. // read in each successive scanline
  40466. while (num_scanlines > 0) {
  40467. a = uint8array[dataIndex++];
  40468. b = uint8array[dataIndex++];
  40469. c = uint8array[dataIndex++];
  40470. d = uint8array[dataIndex++];
  40471. if (a != 2 || b != 2 || (c & 0x80)) {
  40472. // this file is not run length encoded
  40473. throw "HDR Bad header format, not RLE";
  40474. }
  40475. if (((c << 8) | d) != scanline_width) {
  40476. throw "HDR Bad header format, wrong scan line width";
  40477. }
  40478. index = 0;
  40479. // read each of the four channels for the scanline into the buffer
  40480. for (i = 0; i < 4; i++) {
  40481. endIndex = (i + 1) * scanline_width;
  40482. while (index < endIndex) {
  40483. a = uint8array[dataIndex++];
  40484. b = uint8array[dataIndex++];
  40485. if (a > 128) {
  40486. // a run of the same value
  40487. count = a - 128;
  40488. if ((count == 0) || (count > endIndex - index)) {
  40489. throw "HDR Bad Format, bad scanline data (run)";
  40490. }
  40491. while (count-- > 0) {
  40492. scanLineArray[index++] = b;
  40493. }
  40494. }
  40495. else {
  40496. // a non-run
  40497. count = a;
  40498. if ((count == 0) || (count > endIndex - index)) {
  40499. throw "HDR Bad Format, bad scanline data (non-run)";
  40500. }
  40501. scanLineArray[index++] = b;
  40502. if (--count > 0) {
  40503. for (var j = 0; j < count; j++) {
  40504. scanLineArray[index++] = uint8array[dataIndex++];
  40505. }
  40506. }
  40507. }
  40508. }
  40509. }
  40510. // now convert data from buffer into floats
  40511. for (i = 0; i < scanline_width; i++) {
  40512. a = scanLineArray[i];
  40513. b = scanLineArray[i + scanline_width];
  40514. c = scanLineArray[i + 2 * scanline_width];
  40515. d = scanLineArray[i + 3 * scanline_width];
  40516. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40517. }
  40518. num_scanlines--;
  40519. }
  40520. return resultArray;
  40521. };
  40522. return HDRTools;
  40523. })();
  40524. Internals.HDRTools = HDRTools;
  40525. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40526. })(BABYLON || (BABYLON = {}));
  40527. var BABYLON;
  40528. (function (BABYLON) {
  40529. var HDRCubeTexture = (function (_super) {
  40530. __extends(HDRCubeTexture, _super);
  40531. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  40532. if (noMipmap === void 0) { noMipmap = false; }
  40533. if (generateHarmonics === void 0) { generateHarmonics = true; }
  40534. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  40535. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  40536. _super.call(this, scene);
  40537. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40538. this._useInGammaSpace = false;
  40539. this._generateHarmonics = true;
  40540. this.sphericalPolynomial = null;
  40541. this.isPMREM = false;
  40542. this.name = url;
  40543. this.url = url;
  40544. this._noMipmap = noMipmap;
  40545. this.hasAlpha = false;
  40546. this._size = size;
  40547. this._useInGammaSpace = useInGammaSpace;
  40548. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  40549. this.isPMREM = this._usePMREMGenerator;
  40550. if (!url) {
  40551. return;
  40552. }
  40553. this._texture = this._getFromCache(url, noMipmap);
  40554. if (!this._texture) {
  40555. if (!scene.useDelayedTextureLoading) {
  40556. this.loadTexture();
  40557. }
  40558. else {
  40559. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40560. }
  40561. }
  40562. this.isCube = true;
  40563. this._textureMatrix = BABYLON.Matrix.Identity();
  40564. }
  40565. HDRCubeTexture.prototype.loadTexture = function () {
  40566. var _this = this;
  40567. var callback = function (buffer) {
  40568. // Extract the raw linear data.
  40569. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  40570. // Generate harmonics if needed.
  40571. if (_this._generateHarmonics) {
  40572. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  40573. }
  40574. var results = [];
  40575. var byteArray = null;
  40576. // Create uintarray fallback.
  40577. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  40578. // 3 channels of 1 bytes per pixel in bytes.
  40579. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  40580. byteArray = new Uint8Array(byteBuffer);
  40581. }
  40582. // Push each faces.
  40583. for (var j = 0; j < 6; j++) {
  40584. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  40585. // If special cases.
  40586. if (_this._useInGammaSpace || byteArray) {
  40587. for (var i = 0; i < _this._size * _this._size; i++) {
  40588. // Put in gamma space if requested.
  40589. if (_this._useInGammaSpace) {
  40590. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  40591. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  40592. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  40593. }
  40594. // Convert to int texture for fallback.
  40595. if (byteArray) {
  40596. // R
  40597. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  40598. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  40599. // G
  40600. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  40601. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  40602. // B
  40603. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  40604. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  40605. }
  40606. }
  40607. }
  40608. results.push(dataFace);
  40609. }
  40610. return results;
  40611. };
  40612. var mipmapGenerator = null;
  40613. if (!this._noMipmap && this._usePMREMGenerator) {
  40614. mipmapGenerator = function (data) {
  40615. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  40616. return generator.filterCubeMap();
  40617. };
  40618. }
  40619. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  40620. };
  40621. HDRCubeTexture.prototype.clone = function () {
  40622. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  40623. // Base texture
  40624. newTexture.level = this.level;
  40625. newTexture.wrapU = this.wrapU;
  40626. newTexture.wrapV = this.wrapV;
  40627. newTexture.coordinatesIndex = this.coordinatesIndex;
  40628. newTexture.coordinatesMode = this.coordinatesMode;
  40629. return newTexture;
  40630. };
  40631. // Methods
  40632. HDRCubeTexture.prototype.delayLoad = function () {
  40633. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40634. return;
  40635. }
  40636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40637. this._texture = this._getFromCache(this.url, this._noMipmap);
  40638. if (!this._texture) {
  40639. this.loadTexture();
  40640. }
  40641. };
  40642. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  40643. return this._textureMatrix;
  40644. };
  40645. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40646. var texture = null;
  40647. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40648. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  40649. texture.name = parsedTexture.name;
  40650. texture.hasAlpha = parsedTexture.hasAlpha;
  40651. texture.level = parsedTexture.level;
  40652. texture.coordinatesMode = parsedTexture.coordinatesMode;
  40653. }
  40654. return texture;
  40655. };
  40656. HDRCubeTexture.prototype.serialize = function () {
  40657. if (!this.name) {
  40658. return null;
  40659. }
  40660. var serializationObject = {};
  40661. serializationObject.name = this.name;
  40662. serializationObject.hasAlpha = this.hasAlpha;
  40663. serializationObject.isCube = true;
  40664. serializationObject.level = this.level;
  40665. serializationObject.size = this._size;
  40666. serializationObject.coordinatesMode = this.coordinatesMode;
  40667. serializationObject.useInGammaSpace = this._useInGammaSpace;
  40668. serializationObject.generateHarmonics = this._generateHarmonics;
  40669. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  40670. return serializationObject;
  40671. };
  40672. HDRCubeTexture._facesMapping = [
  40673. "right",
  40674. "up",
  40675. "front",
  40676. "left",
  40677. "down",
  40678. "back"
  40679. ];
  40680. return HDRCubeTexture;
  40681. })(BABYLON.BaseTexture);
  40682. BABYLON.HDRCubeTexture = HDRCubeTexture;
  40683. })(BABYLON || (BABYLON = {}));
  40684. 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);\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);\nfloat alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  40685. 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;var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.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=o.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],S=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*S,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*S,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,\ni.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var c=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  40686. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;\n}\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  40687. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  40688. module.exports = BABYLON;
  40689. };